Debian Codegraph @

basic/source/runtime/methods.cxx

raw
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 <tools/date.hxx>
23 #include <basic/sbxvar.hxx>
24 #include <basic/sbuno.hxx>
25 #include <osl/process.h>
26 #include <vcl/dibtools.hxx>
27 #include <vcl/svapp.hxx>
28 #include <vcl/settings.hxx>
29 #include <vcl/sound.hxx>
30 #include <vcl/wintypes.hxx>
31 #include <vcl/stdtext.hxx>
32 #include <vcl/weld.hxx>
33 #include <basic/sbx.hxx>
34 #include <svl/zforlist.hxx>
35 #include <rtl/character.hxx>
36 #include <rtl/math.hxx>
37 #include <tools/urlobj.hxx>
38 #include <osl/time.h>
39 #include <unotools/charclass.hxx>
40 #include <unotools/ucbstreamhelper.hxx>
41 #include <unotools/wincodepage.hxx>
42 #include <tools/wldcrd.hxx>
43 #include <i18nlangtag/lang.h>
44 #include <rtl/string.hxx>
45 #include <sal/log.hxx>
46 #include <comphelper/DirectoryHelper.hxx>
47 #include <comphelper/lok.hxx>
48
49 #include <runtime.hxx>
50 #include <sbunoobj.hxx>
51 #include <osl/file.hxx>
52 #include <errobject.hxx>
53
54 #include <comphelper/string.hxx>
55 #include <comphelper/processfactory.hxx>
56
57 #include <com/sun/star/uno/Sequence.hxx>
58 #include <com/sun/star/util/DateTime.hpp>
59 #include <com/sun/star/lang/Locale.hpp>
60 #include <com/sun/star/lang/XServiceInfo.hpp>
61 #include <com/sun/star/ucb/SimpleFileAccess.hpp>
62 #include <com/sun/star/script/XErrorQuery.hpp>
63 #include <ooo/vba/VbStrConv.hpp>
64 #include <ooo/vba/VbTriState.hpp>
65 #include <com/sun/star/bridge/oleautomation/XAutomationObject.hpp>
66 #include <memory>
67 #include <random>
68 #include <string_view>
69 #include <o3tl/char16_t2wchar_t.hxx>
70
71 // include search util
72 #include <com/sun/star/i18n/Transliteration.hpp>
73 #include <com/sun/star/util/SearchAlgorithms2.hpp>
74 #include <i18nutil/searchopt.hxx>
75 #include <unotools/textsearch.hxx>
76 #include <svl/numformat.hxx>
77
78 #include <date.hxx>
79 #include <sbstdobj.hxx>
80 #include <rtlproto.hxx>
81 #include <image.hxx>
82 #include <iosys.hxx>
83 #include "ddectrl.hxx"
84 #include <sbintern.hxx>
85 #include <basic/vbahelper.hxx>
86
87 #include <vector>
88 #include <stdio.h>
89 #include <errno.h>
90
91 #include <sbobjmod.hxx>
92 #include <sbxmod.hxx>
93
94 #ifdef _WIN32
95 #include <prewin.h>
96 #include <direct.h>
97 #include <io.h>
98 #include <postwin.h>
99 #else
100 #include <unistd.h>
101 #endif
102
103 #include <vcl/TypeSerializer.hxx>
104
105 using namespace comphelper;
106 using namespace osl;
107 using namespace com::sun::star;
108 using namespace com::sun::star::lang;
109 using namespace com::sun::star::uno;
110
111 static sal_Int32 GetDayDiff(const Date& rDate) { return rDate - Date(1899'12'30); }
112
113 #if HAVE_FEATURE_SCRIPTING
114
115 static sal_Int32 nanoSecToMilliSec(sal_Int64 nNanoSeconds)
116 {
117 // Rounding nanoseconds to milliseconds precision to avoid comparison inaccuracies
118 return o3tl::convert(nNanoSeconds, 1, tools::Time::nanoPerMilli);
119 }
120
121 static void FilterWhiteSpace( OUString& rStr )
122 {
123 if (rStr.isEmpty())
124 {
125 return;
126 }
127 OUStringBuffer aRet;
128
129 for (sal_Int32 i = 0; i < rStr.getLength(); ++i)
130 {
131 sal_Unicode cChar = rStr[i];
132 if ((cChar != ' ') && (cChar != '\t') &&
133 (cChar != '\n') && (cChar != '\r'))
134 {
135 aRet.append(cChar);
136 }
137 }
138
139 rStr = aRet.makeStringAndClear();
140 }
141
142 static const CharClass& GetCharClass()
143 {
144 static CharClass aCharClass( Application::GetSettings().GetLanguageTag() );
145 return aCharClass;
146 }
147
148 static bool isFolder( FileStatus::Type aType )
149 {
150 return ( aType == FileStatus::Directory || aType == FileStatus::Volume );
151 }
152
153
154 //*** UCB file access ***
155
156 // Converts possibly relative paths to absolute paths
157 // according to the setting done by ChDir/ChDrive
158 OUString getFullPath( const OUString& aRelPath )
159 {
160 OUString aFileURL;
161
162 // #80204 Try first if it already is a valid URL
163 INetURLObject aURLObj( aRelPath );
164 aFileURL = aURLObj.GetMainURL( INetURLObject::DecodeMechanism::NONE );
165
166 if( aFileURL.isEmpty() )
167 {
168 File::getFileURLFromSystemPath( aRelPath, aFileURL );
169 }
170
171 return aFileURL;
172 }
173
174 // TODO: -> SbiGlobals
175 static uno::Reference< ucb::XSimpleFileAccess3 > const & getFileAccess()
176 {
177 static uno::Reference< ucb::XSimpleFileAccess3 > xSFI = ucb::SimpleFileAccess::create( comphelper::getProcessComponentContext() );
178 return xSFI;
179 }
180
181
182 // Properties and methods lie down the return value at the Get (bPut = sal_False) in the
183 // element 0 of the Argv; the value of element 0 is saved at Put (bPut = sal_True)
184
185 // CreateObject( class )
186
187 void SbRtl_CreateObject(StarBASIC * pBasic, SbxArray & rPar, bool)
188 {
189 if( rPar.Count() != 2 )
190 return StarBASIC::Error( ERRCODE_BASIC_BAD_ARGUMENT );
191
192 OUString aClass(rPar.Get(1)->GetOUString());
193 SbxObjectRef p = SbxBase::CreateObject( aClass );
194 if( !p.is() )
195 return StarBASIC::Error( ERRCODE_BASIC_CANNOT_LOAD );
196
197 // Convenience: enter BASIC as parent
198 p->SetParent( pBasic );
199 rPar.Get(0)->PutObject(p.get());
200 }
201
202 // Error( n )
203
204 void SbRtl_Error(StarBASIC * pBasic, SbxArray & rPar, bool)
205 {
206 if( !pBasic )
207 return StarBASIC::Error( ERRCODE_BASIC_INTERNAL_ERROR );
208
209 OUString aErrorMsg;
210 ErrCode nErr = ERRCODE_NONE;
211 sal_Int32 nCode = 0;
212 if (rPar.Count() == 1)
213 {
214 nErr = StarBASIC::GetErrBasic();
215 aErrorMsg = StarBASIC::GetErrorMsg();
216 }
217 else
218 {
219 nCode = rPar.Get(1)->GetLong();
220 if( nCode > 65535 )
221 {
222 StarBASIC::Error( ERRCODE_BASIC_CONVERSION );
223 }
224 else
225 {
226 nErr = StarBASIC::GetSfxFromVBError( static_cast<sal_uInt16>(nCode) );
227 }
228 }
229 bool bVBA = SbiRuntime::isVBAEnabled();
230 OUString tmpErrMsg;
231 if( bVBA && !aErrorMsg.isEmpty())
232 {
233 tmpErrMsg = aErrorMsg;
234 }
235 else
236 {
237 StarBASIC::MakeErrorText( nErr, aErrorMsg );
238 tmpErrMsg = StarBASIC::GetErrorText();
239 }
240 // If this rtlfunc 'Error' passed an errcode the same as the active Err Objects's
241 // current err then return the description for the error message if it is set
242 // ( complicated isn't it ? )
243 if (bVBA && rPar.Count() > 1)
244 {
245 uno::Reference< ooo::vba::XErrObject > xErrObj( SbxErrObject::getUnoErrObject() );
246 if ( xErrObj.is() && xErrObj->getNumber() == nCode && !xErrObj->getDescription().isEmpty() )
247 {
248 tmpErrMsg = xErrObj->getDescription();
249 }
250 }
251 rPar.Get(0)->PutString(tmpErrMsg);
252 }
253
254 // Sinus
255
256 void SbRtl_Sin(StarBASIC *, SbxArray & rPar, bool)
257 {
258 if (rPar.Count() != 2)
259 return StarBASIC::Error( ERRCODE_BASIC_BAD_ARGUMENT );
260
261 SbxVariableRef pArg = rPar.Get(1);
262 rPar.Get(0)->PutDouble(sin(pArg->GetDouble()));
263 }
264
265
266 void SbRtl_Cos(StarBASIC *, SbxArray & rPar, bool)
267 {
268 if (rPar.Count() != 2)
269 return StarBASIC::Error( ERRCODE_BASIC_BAD_ARGUMENT );
270
271 SbxVariableRef pArg = rPar.Get(1);
272 rPar.Get(0)->PutDouble(cos(pArg->GetDouble()));
273 }
274
275
276 void SbRtl_Atn(StarBASIC *, SbxArray & rPar, bool)
277 {
278 if (rPar.Count() != 2)
279 return StarBASIC::Error( ERRCODE_BASIC_BAD_ARGUMENT );
280
281 SbxVariableRef pArg = rPar.Get(1);
282 rPar.Get(0)->PutDouble(atan(pArg->GetDouble()));
283 }
284
285
286 void SbRtl_Abs(StarBASIC *, SbxArray & rPar, bool)
287 {
288 if (rPar.Count() != 2)
289 return StarBASIC::Error( ERRCODE_BASIC_BAD_ARGUMENT );
290
291 SbxVariableRef pArg = rPar.Get(1);
292 rPar.Get(0)->PutDouble(fabs(pArg->GetDouble()));
293 }
294
295
296 void SbRtl_Asc(StarBASIC *, SbxArray & rPar, bool)
297 {
298 if (rPar.Count() < 2)
299 return StarBASIC::Error( ERRCODE_BASIC_BAD_ARGUMENT );
300
301 SbxVariableRef pArg = rPar.Get(1);
302 OUString aStr( pArg->GetOUString() );
303 if ( aStr.isEmpty())
304 {
305 StarBASIC::Error( ERRCODE_BASIC_BAD_ARGUMENT );
306 rPar.Get(0)->PutEmpty();
307 return;
308 }
309 sal_Unicode aCh = aStr[0];
310 rPar.Get(0)->PutLong(aCh);
311 }
312
313 static void implChr( SbxArray& rPar, bool bChrW )
314 {
315 if (rPar.Count() < 2)
316 return StarBASIC::Error( ERRCODE_BASIC_BAD_ARGUMENT );
317
318 SbxVariableRef pArg = rPar.Get(1);
319
320 OUString aStr;
321 if( !bChrW && SbiRuntime::isVBAEnabled() )
322 {
323 char c = static_cast<char>(pArg->GetByte());
324 aStr = OUString(&c, 1, osl_getThreadTextEncoding());
325 }
326 else
327 {
328 // Map negative 16-bit values to large positive ones, so that code like Chr(&H8000)
329 // still works after the fix for tdf#62326 changed those four-digit hex notations to
330 // produce negative values:
331 sal_Int32 aCh = pArg->GetLong();
332 if (aCh < -0x8000 || aCh > 0xFFFF)
333 {
334 StarBASIC::Error(ERRCODE_BASIC_MATH_OVERFLOW);
335 aCh = 0;
336 }
337 aStr = OUString(static_cast<sal_Unicode>(aCh));
338 }
339 rPar.Get(0)->PutString(aStr);
340 }
341
342 void SbRtl_Chr(StarBASIC *, SbxArray & rPar, bool)
343 {
344 implChr( rPar, false/*bChrW*/ );
345 }
346
347 void SbRtl_ChrW(StarBASIC *, SbxArray & rPar, bool)
348 {
349 implChr( rPar, true/*bChrW*/ );
350 }
351
352 #if defined _WIN32
353
354 namespace {
355
356 extern "C" void invalidParameterHandler(
357 wchar_t const * expression, wchar_t const * function, wchar_t const * file, unsigned int line,
358 uintptr_t)
359 {
360 SAL_INFO(
361 "basic",
362 "invalid parameter during _wgetdcwd; \""
363 << (expression ? OUString(o3tl::toU(expression)) : OUString("???"))
364 << "\" (" << (function ? OUString(o3tl::toU(function)) : OUString("???")) << ") at "
365 << (file ? OUString(o3tl::toU(file)) : OUString("???")) << ":" << line);
366 }
367
368 }
369
370 #endif
371
372 void SbRtl_CurDir(StarBASIC *, SbxArray & rPar, bool)
373 {
374 // #57064 Although this function doesn't work with DirEntry, it isn't touched
375 // by the adjustment to virtual URLs, as, using the DirEntry-functionality,
376 // there's no possibility to detect the current one in a way that a virtual URL
377 // could be delivered.
378
379 if (rPar.Count() > 2)
380 return StarBASIC::Error( ERRCODE_BASIC_BAD_ARGUMENT );
381
382 #if defined(_WIN32)
383 int nCurDir = 0; // Current dir // JSM
384 if (rPar.Count() == 2)
385 {
386 OUString aDrive = rPar.Get(1)->GetOUString();
387 if ( aDrive.getLength() != 1 )
388 return StarBASIC::Error( ERRCODE_BASIC_BAD_ARGUMENT );
389
390 auto c = rtl::toAsciiUpperCase(aDrive[0]);
391 if ( !rtl::isAsciiUpperCase( c ) )
392 return StarBASIC::Error( ERRCODE_BASIC_BAD_ARGUMENT );
393
394 nCurDir = c - 'A' + 1;
395 }
396 wchar_t pBuffer[ _MAX_PATH ];
397 // _wgetdcwd calls the C runtime's invalid parameter handler (which by default terminates the
398 // process) if nCurDir does not correspond to an existing drive, so temporarily set a "harmless"
399 // handler:
400 auto const handler = _set_thread_local_invalid_parameter_handler(&invalidParameterHandler);
401 auto const ok = _wgetdcwd( nCurDir, pBuffer, _MAX_PATH ) != nullptr;
402 _set_thread_local_invalid_parameter_handler(handler);
403 if ( !ok )
404 return StarBASIC::Error( ERRCODE_BASIC_NO_DEVICE );
405
406 rPar.Get(0)->PutString(OUString(o3tl::toU(pBuffer)));
407
408 #else
409
410 const int PATH_INCR = 250;
411
412 int nSize = PATH_INCR;
413 std::unique_ptr<char[]> pMem;
414 while( true )
415 {
416 pMem.reset(new char[nSize]);
417 if( !pMem )
418 return StarBASIC::Error( ERRCODE_BASIC_NO_MEMORY );
419
420 if( getcwd( pMem.get(), nSize-1 ) != nullptr )
421 {
422 rPar.Get(0)->PutString(OUString::createFromAscii(pMem.get()));
423 return;
424 }
425 if( errno != ERANGE )
426 return StarBASIC::Error( ERRCODE_BASIC_INTERNAL_ERROR );
427
428 nSize += PATH_INCR;
429 };
430
431 #endif
432 }
433
434 void SbRtl_ChDir(StarBASIC * pBasic, SbxArray & rPar, bool)
435 {
436 rPar.Get(0)->PutEmpty();
437 if (rPar.Count() != 2)
438 return StarBASIC::Error( ERRCODE_BASIC_BAD_ARGUMENT );
439
440 // VBA: track current directory per document type (separately for Writer, Calc, Impress, etc.)
441 if( SbiRuntime::isVBAEnabled() )
442 {
443 ::basic::vba::registerCurrentDirectory(getDocumentModel(pBasic),
444 rPar.Get(1)->GetOUString());
445 }
446 }
447
448 void SbRtl_ChDrive(StarBASIC *, SbxArray & rPar, bool)
449 {
450 rPar.Get(0)->PutEmpty();
451 if (rPar.Count() != 2)
452 return StarBASIC::Error( ERRCODE_BASIC_BAD_ARGUMENT );
453 }
454
455
456 // Implementation of StepRENAME with UCB
457 void implStepRenameUCB( const OUString& aSource, const OUString& aDest )
458 {
459 const uno::Reference< ucb::XSimpleFileAccess3 >& xSFI = getFileAccess();
460 if( !xSFI.is() )
461 return;
462
463 try
464 {
465 OUString aSourceFullPath = getFullPath( aSource );
466 if( !xSFI->exists( aSourceFullPath ) )
467 {
468 StarBASIC::Error( ERRCODE_BASIC_FILE_NOT_FOUND );
469 return;
470 }
471
472 OUString aDestFullPath = getFullPath( aDest );
473 if( xSFI->exists( aDestFullPath ) )
474 {
475 StarBASIC::Error( ERRCODE_BASIC_FILE_EXISTS );
476 }
477 else
478 {
479 xSFI->move( aSourceFullPath, aDestFullPath );
480 }
481 }
482 catch(const Exception & )
483 {
484 StarBASIC::Error( ERRCODE_BASIC_FILE_NOT_FOUND );
485 }
486 }
487
488 // Implementation of StepRENAME with OSL
489 void implStepRenameOSL( const OUString& aSource, const OUString& aDest )
490 {
491 FileBase::RC nRet = File::move( getFullPath( aSource ), getFullPath( aDest ) );
492 if( nRet != FileBase::E_None )
493 {
494 StarBASIC::Error( ERRCODE_BASIC_PATH_NOT_FOUND );
495 }
496 }
497
498 void SbRtl_FileCopy(StarBASIC *, SbxArray & rPar, bool)
499 {
500 rPar.Get(0)->PutEmpty();
501 if (rPar.Count() != 3)
502 return StarBASIC::Error( ERRCODE_BASIC_BAD_ARGUMENT );
503
504 OUString aSource = rPar.Get(1)->GetOUString();
505 OUString aDest = rPar.Get(2)->GetOUString();
506 if( hasUno() )
507 {
508 const uno::Reference< ucb::XSimpleFileAccess3 >& xSFI = getFileAccess();
509 if( xSFI.is() )
510 {
511 try
512 {
513 xSFI->copy( getFullPath( aSource ), getFullPath( aDest ) );
514 }
515 catch(const Exception & )
516 {
517 StarBASIC::Error( ERRCODE_BASIC_PATH_NOT_FOUND );
518 }
519 }
520 }
521 else
522 {
523 FileBase::RC nRet = File::copy( getFullPath( aSource ), getFullPath( aDest ) );
524 if( nRet != FileBase::E_None )
525 {
526 StarBASIC::Error( ERRCODE_BASIC_PATH_NOT_FOUND );
527 }
528 }
529 }
530
531 void SbRtl_Kill(StarBASIC *, SbxArray & rPar, bool)
532 {
533 rPar.Get(0)->PutEmpty();
534 if (rPar.Count() != 2)
535 return StarBASIC::Error( ERRCODE_BASIC_BAD_ARGUMENT );
536
537 OUString aFileSpec = rPar.Get(1)->GetOUString();
538
539 if( hasUno() )
540 {
541 const uno::Reference< ucb::XSimpleFileAccess3 >& xSFI = getFileAccess();
542 if( xSFI.is() )
543 {
544 OUString aFullPath = getFullPath( aFileSpec );
545 if( !xSFI->exists( aFullPath ) || xSFI->isFolder( aFullPath ) )
546 {
547 StarBASIC::Error( ERRCODE_BASIC_FILE_NOT_FOUND );
548 return;
549 }
550 try
551 {
552 xSFI->kill( aFullPath );
553 }
554 catch(const Exception & )
555 {
556 StarBASIC::Error( ERRCODE_IO_GENERAL );
557 }
558 }
559 }
560 else
561 {
562 File::remove( getFullPath( aFileSpec ) );
563 }
564 }
565
566 void SbRtl_MkDir(StarBASIC * pBasic, SbxArray & rPar, bool bWrite)
567 {
568 rPar.Get(0)->PutEmpty();
569 if (rPar.Count() != 2)
570 return StarBASIC::Error( ERRCODE_BASIC_BAD_ARGUMENT );
571
572 OUString aPath = rPar.Get(1)->GetOUString();
573 if ( SbiRuntime::isVBAEnabled() )
574 {
575 // In vba if the full path is not specified then
576 // folder is created relative to the curdir
577 INetURLObject aURLObj( getFullPath( aPath ) );
578 if ( aURLObj.GetProtocol() != INetProtocol::File )
579 {
580 SbxArrayRef pPar = new SbxArray();
581 SbxVariableRef pResult = new SbxVariable();
582 SbxVariableRef pParam = new SbxVariable();
583 pPar->Insert(pResult.get(), pPar->Count());
584 pPar->Insert(pParam.get(), pPar->Count());
585 SbRtl_CurDir( pBasic, *pPar, bWrite );
586
587 OUString sCurPathURL;
588 File::getFileURLFromSystemPath(pPar->Get(0)->GetOUString(), sCurPathURL);
589
590 aURLObj.SetURL( sCurPathURL );
591 aURLObj.Append( aPath );
592 File::getSystemPathFromFileURL(aURLObj.GetMainURL( INetURLObject::DecodeMechanism::ToIUri ),aPath ) ;
593 }
594 }
595
596 if( hasUno() )
597 {
598 const uno::Reference< ucb::XSimpleFileAccess3 >& xSFI = getFileAccess();
599 if( xSFI.is() )
600 {
601 try
602 {
603 xSFI->createFolder( getFullPath( aPath ) );
604 }
605 catch(const Exception & )
606 {
607 StarBASIC::Error( ERRCODE_IO_GENERAL );
608 }
609 }
610 }
611 else
612 {
613 Directory::create( getFullPath( aPath ) );
614 }
615 }
616
617
618 static void implRemoveDirRecursive( const OUString& aDirPath )
619 {
620 DirectoryItem aItem;
621 FileBase::RC nRet = DirectoryItem::get( aDirPath, aItem );
622 bool bExists = (nRet == FileBase::E_None);
623
624 FileStatus aFileStatus( osl_FileStatus_Mask_Type );
625 nRet = aItem.getFileStatus( aFileStatus );
626 bool bFolder = nRet == FileBase::E_None
627 && isFolder( aFileStatus.getFileType() );
628
629 if( !bExists || !bFolder )
630 {
631 return StarBASIC::Error( ERRCODE_BASIC_PATH_NOT_FOUND );
632 }
633
634 Directory aDir( aDirPath );
635 nRet = aDir.open();
636 if( nRet != FileBase::E_None )
637 {
638 return StarBASIC::Error( ERRCODE_BASIC_PATH_NOT_FOUND );
639 }
640 aDir.close();
641
642 comphelper::DirectoryHelper::deleteDirRecursively(aDirPath);
643 }
644
645
646 void SbRtl_RmDir(StarBASIC *, SbxArray & rPar, bool)
647 {
648 rPar.Get(0)->PutEmpty();
649 if (rPar.Count() != 2)
650 return StarBASIC::Error( ERRCODE_BASIC_BAD_ARGUMENT );
651
652 OUString aPath = rPar.Get(1)->GetOUString();
653 if( hasUno() )
654 {
655 const uno::Reference< ucb::XSimpleFileAccess3 >& xSFI = getFileAccess();
656 if( xSFI.is() )
657 {
658 try
659 {
660 if( !xSFI->isFolder( aPath ) )
661 {
662 return StarBASIC::Error( ERRCODE_BASIC_PATH_NOT_FOUND );
663 }
664 SbiInstance* pInst = GetSbData()->pInst;
665 bool bCompatibility = ( pInst && pInst->IsCompatibility() );
666 if( bCompatibility )
667 {
668 Sequence< OUString > aContent = xSFI->getFolderContents( aPath, true );
669 if( aContent.hasElements() )
670 {
671 return StarBASIC::Error( ERRCODE_BASIC_ACCESS_ERROR );
672 }
673 }
674
675 xSFI->kill( getFullPath( aPath ) );
676 }
677 catch(const Exception & )
678 {
679 StarBASIC::Error( ERRCODE_IO_GENERAL );
680 }
681 }
682 }
683 else
684 {
685 implRemoveDirRecursive( getFullPath( aPath ) );
686 }
687 }
688
689 void SbRtl_SendKeys(StarBASIC *, SbxArray & rPar, bool)
690 {
691 rPar.Get(0)->PutEmpty();
692 StarBASIC::Error(ERRCODE_BASIC_NOT_IMPLEMENTED);
693 }
694
695 void SbRtl_Exp(StarBASIC *, SbxArray & rPar, bool)
696 {
697 if (rPar.Count() != 2)
698 return StarBASIC::Error( ERRCODE_BASIC_BAD_ARGUMENT );
699
700 double aDouble = rPar.Get(1)->GetDouble();
701 aDouble = exp( aDouble );
702 checkArithmeticOverflow( aDouble );
703 rPar.Get(0)->PutDouble(aDouble);
704 }
705
706 void SbRtl_FileLen(StarBASIC *, SbxArray & rPar, bool)
707 {
708 if (rPar.Count() < 2)
709 {
710 return StarBASIC::Error( ERRCODE_BASIC_BAD_ARGUMENT );
711 }
712
713 SbxVariableRef pArg = rPar.Get(1);
714 OUString aStr( pArg->GetOUString() );
715 sal_Int32 nLen = 0;
716 if( hasUno() )
717 {
718 const uno::Reference< ucb::XSimpleFileAccess3 >& xSFI = getFileAccess();
719 if( xSFI.is() )
720 {
721 try
722 {
723 nLen = xSFI->getSize( getFullPath( aStr ) );
724 }
725 catch(const Exception & )
726 {
727 StarBASIC::Error( ERRCODE_IO_GENERAL );
728 }
729 }
730 }
731 else
732 {
733 DirectoryItem aItem;
734 (void)DirectoryItem::get( getFullPath( aStr ), aItem );
735 FileStatus aFileStatus( osl_FileStatus_Mask_FileSize );
736 (void)aItem.getFileStatus( aFileStatus );
737 nLen = static_cast<sal_Int32>(aFileStatus.getFileSize());
738 }
739 rPar.Get(0)->PutLong(nLen);
740 }
741
742
743
744 void SbRtl_Hex(StarBASIC *, SbxArray & rPar, bool)
745 {
746 if (rPar.Count() < 2)
747 {
748 return StarBASIC::Error( ERRCODE_BASIC_BAD_ARGUMENT );
749 }
750
751 SbxVariableRef pArg = rPar.Get(1);
752 // converting value to unsigned and limit to 2 or 4 byte representation
753 sal_uInt32 nVal = pArg->IsInteger() ?
754 static_cast<sal_uInt16>(pArg->GetInteger()) :
755 static_cast<sal_uInt32>(pArg->GetLong());
756 rPar.Get(0)->PutString(OUString::number(nVal, 16).toAsciiUpperCase());
757 }
758
759 void SbRtl_FuncCaller(StarBASIC *, SbxArray & rPar, bool)
760 {
761 if (!SbiRuntime::isVBAEnabled() || GetSbData()->pInst == nullptr || GetSbData()->pInst->pRun == nullptr)
762 return StarBASIC::Error(ERRCODE_BASIC_NOT_IMPLEMENTED);
763
764 if ( GetSbData()->pInst->pRun->GetExternalCaller() )
765 *rPar.Get(0) = *GetSbData()->pInst->pRun->GetExternalCaller();
766 else
767 {
768 SbxVariableRef pVar = new SbxVariable(SbxVARIANT);
769 *rPar.Get(0) = *pVar;
770 }
771 }
772 // InStr( [start],string,string,[compare] )
773
774 void SbRtl_InStr(StarBASIC *, SbxArray & rPar, bool)
775 {
776 const sal_uInt32 nArgCount = rPar.Count() - 1;
777 if ( nArgCount < 2 )
778 return StarBASIC::Error(ERRCODE_BASIC_BAD_ARGUMENT);
779
780 sal_Int32 nStartPos = 1;
781 sal_Int32 nFirstStringPos = 1;
782
783 if ( nArgCount >= 3 )
784 {
785 nStartPos = rPar.Get(1)->GetLong();
786 if( nStartPos <= 0 )
787 {
788 StarBASIC::Error( ERRCODE_BASIC_BAD_ARGUMENT );
789 nStartPos = 1;
790 }
791 nFirstStringPos++;
792 }
793
794 SbiInstance* pInst = GetSbData()->pInst;
795 bool bTextMode;
796 bool bCompatibility = ( pInst && pInst->IsCompatibility() );
797 if( bCompatibility )
798 {
799 SbiRuntime* pRT = pInst->pRun;
800 bTextMode = pRT && pRT->IsImageFlag( SbiImageFlags::COMPARETEXT );
801 }
802 else
803 {
804 bTextMode = true;
805 }
806 if ( nArgCount == 4 )
807 {
808 bTextMode = rPar.Get(4)->GetInteger();
809 }
810 sal_Int32 nPos;
811 const OUString aToken = rPar.Get(nFirstStringPos + 1)->GetOUString();
812
813 // #97545 Always find empty string
814 if( aToken.isEmpty() )
815 {
816 nPos = nStartPos;
817 }
818 else
819 {
820 const OUString aStr1 = rPar.Get(nFirstStringPos)->GetOUString();
821 const sal_Int32 nrStr1Len = aStr1.getLength();
822 if (nStartPos > nrStr1Len)
823 {
824 // Start position is greater than the string being searched
825 nPos = 0;
826 }
827 else
828 {
829 if( !bTextMode )
830 {
831 nPos = aStr1.indexOf( aToken, nStartPos - 1 ) + 1;
832 }
833 else
834 {
835 // tdf#139840 - case-insensitive operation for non-ASCII characters
836 i18nutil::SearchOptions2 aSearchOptions;
837 aSearchOptions.searchString = aToken;
838 aSearchOptions.AlgorithmType2 = util::SearchAlgorithms2::ABSOLUTE;
839 aSearchOptions.transliterateFlags |= TransliterationFlags::IGNORE_CASE;
840 utl::TextSearch textSearch(aSearchOptions);
841
842 sal_Int32 nStart = nStartPos - 1;
843 sal_Int32 nEnd = nrStr1Len;
844 nPos = textSearch.SearchForward(aStr1, &nStart, &nEnd) ? nStart + 1 : 0;
845 }
846 }
847 }
848 rPar.Get(0)->PutLong(nPos);
849 }
850
851
852 // InstrRev(string1, string2[, start[, compare]])
853
854 void SbRtl_InStrRev(StarBASIC *, SbxArray & rPar, bool)
855 {
856 const sal_uInt32 nArgCount = rPar.Count() - 1;
857 if ( nArgCount < 2 )
858 {
859 return StarBASIC::Error( ERRCODE_BASIC_BAD_ARGUMENT );
860 }
861
862 const OUString aStr1 = rPar.Get(1)->GetOUString();
863 const OUString aToken = rPar.Get(2)->GetOUString();
864
865 sal_Int32 nStartPos = -1;
866 if ( nArgCount >= 3 )
867 {
868 nStartPos = rPar.Get(3)->GetLong();
869 if( nStartPos <= 0 && nStartPos != -1 )
870 {
871 StarBASIC::Error( ERRCODE_BASIC_BAD_ARGUMENT );
872 nStartPos = -1;
873 }
874 }
875
876 SbiInstance* pInst = GetSbData()->pInst;
877 bool bTextMode;
878 bool bCompatibility = ( pInst && pInst->IsCompatibility() );
879 if( bCompatibility )
880 {
881 SbiRuntime* pRT = pInst->pRun;
882 bTextMode = pRT && pRT->IsImageFlag( SbiImageFlags::COMPARETEXT );
883 }
884 else
885 {
886 bTextMode = true;
887 }
888 if ( nArgCount == 4 )
889 {
890 bTextMode = rPar.Get(4)->GetInteger();
891 }
892 const sal_Int32 nStrLen = aStr1.getLength();
893 if( nStartPos == -1 )
894 {
895 nStartPos = nStrLen;
896 }
897
898 sal_Int32 nPos = 0;
899 if( nStartPos <= nStrLen )
900 {
901 sal_Int32 nTokenLen = aToken.getLength();
902 if( !nTokenLen )
903 {
904 // Always find empty string
905 nPos = nStartPos;
906 }
907 else if( nStrLen > 0 )
908 {
909 if( !bTextMode )
910 {
911 nPos = aStr1.lastIndexOf( aToken, nStartPos ) + 1;
912 }
913 else
914 {
915 // tdf#143332 - case-insensitive operation for non-ASCII characters
916 i18nutil::SearchOptions2 aSearchOptions;
917 aSearchOptions.searchString = aToken;
918 aSearchOptions.AlgorithmType2 = util::SearchAlgorithms2::ABSOLUTE;
919 aSearchOptions.transliterateFlags |= TransliterationFlags::IGNORE_CASE;
920 utl::TextSearch textSearch(aSearchOptions);
921
922 sal_Int32 nStart = 0;
923 sal_Int32 nEnd = nStartPos;
924 nPos = textSearch.SearchBackward(aStr1, &nEnd, &nStart) ? nStart : 0;
925 }
926 }
927 }
928 rPar.Get(0)->PutLong(nPos);
929 }
930
931
932 /*
933 Int( 2.8 ) = 2.0
934 Int( -2.8 ) = -3.0
935 Fix( 2.8 ) = 2.0
936 Fix( -2.8 ) = -2.0 <- !!
937 */
938
939 void SbRtl_Int(StarBASIC *, SbxArray & rPar, bool)
940 {
941 if (rPar.Count() != 2)
942 return StarBASIC::Error( ERRCODE_BASIC_BAD_ARGUMENT );
943
944 SbxVariableRef pArg = rPar.Get(1);
945 double aDouble= pArg->GetDouble();
946 /*
947 floor( 2.8 ) = 2.0
948 floor( -2.8 ) = -3.0
949 */
950 aDouble = floor( aDouble );
951 rPar.Get(0)->PutDouble(aDouble);
952 }
953
954
955 void SbRtl_Fix(StarBASIC *, SbxArray & rPar, bool)
956 {
957 if (rPar.Count() < 2)
958 return StarBASIC::Error( ERRCODE_BASIC_BAD_ARGUMENT );
959
960 SbxVariableRef pArg = rPar.Get(1);
961 double aDouble = pArg->GetDouble();
962 if ( aDouble >= 0.0 )
963 aDouble = floor( aDouble );
964 else
965 aDouble = ceil( aDouble );
966 rPar.Get(0)->PutDouble(aDouble);
967 }
968
969
970 void SbRtl_LCase(StarBASIC *, SbxArray & rPar, bool)
971 {
972 if (rPar.Count() < 2)
973 return StarBASIC::Error( ERRCODE_BASIC_BAD_ARGUMENT );
974
975 const CharClass& rCharClass = GetCharClass();
976 OUString aStr(rPar.Get(1)->GetOUString());
977 aStr = rCharClass.lowercase(aStr);
978 rPar.Get(0)->PutString(aStr);
979 }
980
981 void SbRtl_Left(StarBASIC *, SbxArray & rPar, bool)
982 {
983 if (rPar.Count() < 3)
984 return StarBASIC::Error( ERRCODE_BASIC_BAD_ARGUMENT );
985
986 OUString aStr(rPar.Get(1)->GetOUString());
987 sal_Int32 nResultLen = rPar.Get(2)->GetLong();
988 if( nResultLen < 0 )
989 {
990 nResultLen = 0;
991 StarBASIC::Error( ERRCODE_BASIC_BAD_ARGUMENT );
992 }
993 else if(nResultLen > aStr.getLength())
994 {
995 nResultLen = aStr.getLength();
996 }
997 aStr = aStr.copy(0, nResultLen );
998 rPar.Get(0)->PutString(aStr);
999 }
1000
1001 void SbRtl_Log(StarBASIC *, SbxArray & rPar, bool)
1002 {
1003 if (rPar.Count() < 2)
1004 return StarBASIC::Error( ERRCODE_BASIC_BAD_ARGUMENT );
1005
1006 double aArg = rPar.Get(1)->GetDouble();
1007 if ( aArg <= 0 )
1008 return StarBASIC::Error( ERRCODE_BASIC_BAD_ARGUMENT );
1009
1010 double d = log( aArg );
1011 checkArithmeticOverflow( d );
1012 rPar.Get(0)->PutDouble(d);
1013 }
1014
1015 void SbRtl_LTrim(StarBASIC *, SbxArray & rPar, bool)
1016 {
1017 if (rPar.Count() < 2)
1018 return StarBASIC::Error( ERRCODE_BASIC_BAD_ARGUMENT );
1019
1020 OUString aStr(comphelper::string::stripStart(rPar.Get(1)->GetOUString(), ' '));
1021 rPar.Get(0)->PutString(aStr);
1022 }
1023
1024
1025 // Mid( String, nStart, nLength )
1026
1027 void SbRtl_Mid(StarBASIC *, SbxArray & rPar, bool bWrite)
1028 {
1029 int nArgCount = rPar.Count() - 1;
1030 if ( nArgCount < 2 )
1031 {
1032 return StarBASIC::Error(ERRCODE_BASIC_BAD_ARGUMENT);
1033 }
1034 // #23178: replicate the functionality of Mid$ as a command
1035 // by adding a replacement-string as a fourth parameter.
1036 // In contrast to the original the third parameter (nLength)
1037 // can't be left out here. That's considered in bWrite already.
1038 if( nArgCount == 4 )
1039 {
1040 bWrite = true;
1041 }
1042 OUString aArgStr = rPar.Get(1)->GetOUString();
1043 sal_Int32 nStartPos = rPar.Get(2)->GetLong();
1044 if ( nStartPos < 1 )
1045 {
1046 return StarBASIC::Error( ERRCODE_BASIC_BAD_ARGUMENT );
1047 }
1048
1049 nStartPos--;
1050 sal_Int32 nLen = -1;
1051 bool bWriteNoLenParam = false;
1052 if ( nArgCount == 3 || bWrite )
1053 {
1054 sal_Int32 n = rPar.Get(3)->GetLong();
1055 if( bWrite && n == -1 )
1056 {
1057 bWriteNoLenParam = true;
1058 }
1059 nLen = n;
1060 }
1061 if ( bWrite )
1062 {
1063 sal_Int32 nArgLen = aArgStr.getLength();
1064 if( nStartPos > nArgLen )
1065 {
1066 SbiInstance* pInst = GetSbData()->pInst;
1067 bool bCompatibility = ( pInst && pInst->IsCompatibility() );
1068 if( bCompatibility )
1069 {
1070 return StarBASIC::Error( ERRCODE_BASIC_BAD_ARGUMENT );
1071 }
1072 nStartPos = nArgLen;
1073 }
1074
1075 OUString aReplaceStr = rPar.Get(4)->GetOUString();
1076 sal_Int32 nReplaceStrLen = aReplaceStr.getLength();
1077 sal_Int32 nReplaceLen;
1078 if( bWriteNoLenParam )
1079 {
1080 nReplaceLen = nArgLen - nStartPos;
1081 }
1082 else
1083 {
1084 nReplaceLen = nLen;
1085 if( nReplaceLen < 0 || nReplaceLen > nArgLen - nStartPos )
1086 {
1087 nReplaceLen = nArgLen - nStartPos;
1088 }
1089 }
1090
1091 OUStringBuffer aResultStr(aArgStr);
1092 sal_Int32 nErase = nReplaceLen;
1093 aResultStr.remove( nStartPos, nErase );
1094 aResultStr.insert(
1095 nStartPos, aReplaceStr.getStr(), std::min(nReplaceLen, nReplaceStrLen));
1096
1097 rPar.Get(1)->PutString(aResultStr.makeStringAndClear());
1098 }
1099 else
1100 {
1101 OUString aResultStr;
1102 if (nStartPos > aArgStr.getLength())
1103 {
1104 // do nothing
1105 }
1106 else if(nArgCount == 2)
1107 {
1108 aResultStr = aArgStr.copy( nStartPos);
1109 }
1110 else
1111 {
1112 if (nLen < 0)
1113 nLen = 0;
1114 if(nStartPos + nLen > aArgStr.getLength())
1115 {
1116 nLen = aArgStr.getLength() - nStartPos;
1117 }
1118 if (nLen > 0)
1119 aResultStr = aArgStr.copy( nStartPos, nLen );
1120 }
1121 rPar.Get(0)->PutString(aResultStr);
1122 }
1123 }
1124
1125 void SbRtl_Oct(StarBASIC *, SbxArray & rPar, bool)
1126 {
1127 if (rPar.Count() < 2)
1128 return StarBASIC::Error( ERRCODE_BASIC_BAD_ARGUMENT );
1129
1130 SbxVariableRef pArg = rPar.Get(1);
1131 // converting value to unsigned and limit to 2 or 4 byte representation
1132 sal_uInt32 nVal = pArg->IsInteger() ?
1133 static_cast<sal_uInt16>(pArg->GetInteger()) :
1134 static_cast<sal_uInt32>(pArg->GetLong());
1135 rPar.Get(0)->PutString(OUString::number(nVal, 8));
1136 }
1137
1138 // Replace(expression, find, replace[, start[, count[, compare]]])
1139
1140 void SbRtl_Replace(StarBASIC *, SbxArray & rPar, bool)
1141 {
1142 const sal_uInt32 nArgCount = rPar.Count() - 1;
1143 if ( nArgCount < 3 || nArgCount > 6 )
1144 return StarBASIC::Error( ERRCODE_BASIC_BAD_ARGUMENT );
1145
1146 sal_Int32 lStartPos = 1;
1147 if (nArgCount >= 4)
1148 {
1149 if (rPar.Get(4)->GetType() != SbxEMPTY)
1150 {
1151 lStartPos = rPar.Get(4)->GetLong();
1152 }
1153 if (lStartPos < 1)
1154 {
1155 return StarBASIC::Error(ERRCODE_BASIC_BAD_ARGUMENT);
1156 }
1157 }
1158 --lStartPos; // Make it 0-based
1159
1160 sal_Int32 lCount = -1;
1161 if (nArgCount >= 5)
1162 {
1163 if (rPar.Get(5)->GetType() != SbxEMPTY)
1164 {
1165 lCount = rPar.Get(5)->GetLong();
1166 }
1167 if (lCount < -1)
1168 {
1169 return StarBASIC::Error(ERRCODE_BASIC_BAD_ARGUMENT);
1170 }
1171 }
1172
1173 bool bCaseInsensitive;
1174 if (nArgCount == 6)
1175 {
1176 bCaseInsensitive = rPar.Get(6)->GetInteger();
1177 }
1178 else
1179 {
1180 SbiInstance* pInst = GetSbData()->pInst;
1181 if (pInst && pInst->IsCompatibility())
1182 {
1183 SbiRuntime* pRT = pInst->pRun;
1184 bCaseInsensitive = pRT && pRT->IsImageFlag(SbiImageFlags::COMPARETEXT);
1185 }
1186 else
1187 {
1188 bCaseInsensitive = true;
1189 }
1190 }
1191
1192 const OUString aExpStr = rPar.Get(1)->GetOUString();
1193 OUString aFindStr = rPar.Get(2)->GetOUString();
1194 const OUString aReplaceStr = rPar.Get(3)->GetOUString();
1195
1196 OUString aSrcStr(aExpStr);
1197 sal_Int32 nPrevPos = std::min(lStartPos, aSrcStr.getLength());
1198 css::uno::Sequence<sal_Int32> aOffset;
1199 if (bCaseInsensitive)
1200 {
1201 // tdf#132389: case-insensitive operation for non-ASCII characters
1202 // tdf#142487: use css::i18n::Transliteration to correctly handle ß -> ss expansion
1203 // tdf#132388: We can't use utl::TextSearch (css::i18n::XTextSearch), because each call to
1204 // css::i18n::XTextSearch::SearchForward transliterates input string, making
1205 // performance of repeated calls unacceptable
1206 auto xTrans = css::i18n::Transliteration::create(comphelper::getProcessComponentContext());
1207 xTrans->loadModule(css::i18n::TransliterationModules_IGNORE_CASE, {});
1208 aFindStr = xTrans->transliterate(aFindStr, 0, aFindStr.getLength(), aOffset);
1209 aSrcStr = xTrans->transliterate(aSrcStr, nPrevPos, aSrcStr.getLength() - nPrevPos, aOffset);
1210 nPrevPos = std::distance(aOffset.begin(),
1211 std::lower_bound(aOffset.begin(), aOffset.end(), nPrevPos));
1212 }
1213
1214 auto getExpStrPos = [aOffset, nExpLen = aExpStr.getLength()](sal_Int32 nSrcStrPos) -> sal_Int32
1215 {
1216 assert(!aOffset.hasElements() || aOffset.getLength() >= nSrcStrPos);
1217 if (!aOffset.hasElements())
1218 return nSrcStrPos;
1219 return aOffset.getLength() > nSrcStrPos ? aOffset[nSrcStrPos] : nExpLen;
1220 };
1221
1222 // Note: the result starts from lStartPos, removing everything to the left. See i#94895.
1223 OUStringBuffer sResult(aSrcStr.getLength() - nPrevPos);
1224 sal_Int32 nCounts = 0;
1225 while (lCount == -1 || lCount > nCounts)
1226 {
1227 sal_Int32 nPos = aSrcStr.indexOf(aFindStr, nPrevPos);
1228 if (nPos < 0)
1229 break;
1230
1231 lStartPos = getExpStrPos(nPrevPos);
1232 sResult.append(aExpStr.getStr() + lStartPos, getExpStrPos(nPos) - lStartPos);
1233 sResult.append(aReplaceStr);
1234 nPrevPos = nPos + aFindStr.getLength();
1235 nCounts++;
1236 }
1237 lStartPos = getExpStrPos(nPrevPos);
1238 sResult.append(aExpStr.getStr() + lStartPos, aExpStr.getLength() - lStartPos);
1239 rPar.Get(0)->PutString(sResult.makeStringAndClear());
1240 }
1241
1242 void SbRtl_Right(StarBASIC *, SbxArray & rPar, bool)
1243 {
1244 if (rPar.Count() < 3)
1245 return StarBASIC::Error( ERRCODE_BASIC_BAD_ARGUMENT );
1246
1247 const OUString aStr = rPar.Get(1)->GetOUString();
1248 int nResultLen = rPar.Get(2)->GetLong();
1249 if( nResultLen < 0 )
1250 {
1251 nResultLen = 0;
1252 StarBASIC::Error( ERRCODE_BASIC_BAD_ARGUMENT );
1253 }
1254 int nStrLen = aStr.getLength();
1255 if ( nResultLen > nStrLen )
1256 {
1257 nResultLen = nStrLen;
1258 }
1259 OUString aResultStr = aStr.copy( nStrLen - nResultLen );
1260 rPar.Get(0)->PutString(aResultStr);
1261 }
1262
1263 void SbRtl_RTL(StarBASIC * pBasic, SbxArray & rPar, bool)
1264 {
1265 rPar.Get(0)->PutObject(pBasic->getRTL().get());
1266 }
1267
1268 void SbRtl_RTrim(StarBASIC *, SbxArray & rPar, bool)
1269 {
1270 if (rPar.Count() < 2)
1271 return StarBASIC::Error( ERRCODE_BASIC_BAD_ARGUMENT );
1272
1273 OUString aStr(comphelper::string::stripEnd(rPar.Get(1)->GetOUString(), ' '));
1274 rPar.Get(0)->PutString(aStr);
1275 }
1276
1277 void SbRtl_Sgn(StarBASIC *, SbxArray & rPar, bool)
1278 {
1279 if (rPar.Count() < 2)
1280 return StarBASIC::Error( ERRCODE_BASIC_BAD_ARGUMENT );
1281
1282 double aDouble = rPar.Get(1)->GetDouble();
1283 sal_Int16 nResult = 0;
1284 if ( aDouble > 0 )
1285 {
1286 nResult = 1;
1287 }
1288 else if ( aDouble < 0 )
1289 {
1290 nResult = -1;
1291 }
1292 rPar.Get(0)->PutInteger(nResult);
1293 }
1294
1295 void SbRtl_Space(StarBASIC *, SbxArray & rPar, bool)
1296 {
1297 if (rPar.Count() < 2)
1298 {
1299 return StarBASIC::Error(ERRCODE_BASIC_BAD_ARGUMENT);
1300 }
1301
1302 sal_Int32 nCount = rPar.Get(1)->GetLong();
1303
1304 if (nCount < 0)
1305 {
1306 if (SbiRuntime::isVBAEnabled())
1307 {
1308 return StarBASIC::Error(ERRCODE_BASIC_BAD_ARGUMENT);
1309 }
1310
1311 nCount = 0;
1312 }
1313
1314 rPar.Get(0)->PutString(OUString::Concat(RepeatedUChar(' ', nCount)));
1315 }
1316
1317 void SbRtl_Sqr(StarBASIC *, SbxArray & rPar, bool)
1318 {
1319 if (rPar.Count() < 2)
1320 {
1321 return StarBASIC::Error(ERRCODE_BASIC_BAD_ARGUMENT);
1322 }
1323
1324 double aDouble = rPar.Get(1)->GetDouble();
1325 if ( aDouble < 0 )
1326 {
1327 return StarBASIC::Error( ERRCODE_BASIC_BAD_ARGUMENT );
1328 }
1329 rPar.Get(0)->PutDouble(sqrt(aDouble));
1330 }
1331
1332 void SbRtl_Str(StarBASIC *, SbxArray & rPar, bool)
1333 {
1334 if (rPar.Count() < 2)
1335 {
1336 return StarBASIC::Error(ERRCODE_BASIC_BAD_ARGUMENT);
1337 }
1338
1339 OUString aStr;
1340 OUString aStrNew;
1341 SbxVariableRef pArg = rPar.Get(1);
1342 const SbxDataType argType = pArg->GetType();
1343 if (argType == SbxSTRING)
1344 {
1345 // From Help: "If a string is passed as argument, it is returned without any changes"
1346 aStr = pArg->GetOUString();
1347 }
1348 else
1349 {
1350 pArg->Format(aStr);
1351 }
1352
1353 // Numbers start with a space
1354 if (argType != SbxBOOL && argType != SbxSTRING && pArg->IsNumericRTL())
1355 {
1356 // replace commas by points so that it's symmetric to Val!
1357 aStr = aStr.replaceFirst( ",", "." );
1358
1359 SbiInstance* pInst = GetSbData()->pInst;
1360 bool bCompatibility = ( pInst && pInst->IsCompatibility() );
1361 if( bCompatibility )
1362 {
1363 sal_Int32 nLen = aStr.getLength();
1364
1365 const sal_Unicode* pBuf = aStr.getStr();
1366
1367 bool bNeg = ( pBuf[0] == '-' );
1368 sal_Int32 iZeroSearch = 0;
1369 if( bNeg )
1370 {
1371 aStrNew += "-";
1372 iZeroSearch++;
1373 }
1374 else
1375 {
1376 if( pBuf[0] != ' ' )
1377 {
1378 aStrNew += " ";
1379 }
1380 }
1381 sal_Int32 iNext = iZeroSearch + 1;
1382 if( pBuf[iZeroSearch] == '0' && nLen > iNext && pBuf[iNext] == '.' )
1383 {
1384 iZeroSearch += 1;
1385 }
1386 aStrNew += aStr.subView(iZeroSearch);
1387 }
1388 else
1389 {
1390 if (!aStr.startsWith("-"))
1391 aStrNew = " ";
1392 aStrNew += aStr;
1393 }
1394 }
1395 else
1396 {
1397 aStrNew = aStr;
1398 }
1399 rPar.Get(0)->PutString(aStrNew);
1400 }
1401
1402 void SbRtl_StrComp(StarBASIC *, SbxArray & rPar, bool)
1403 {
1404 if (rPar.Count() < 3)
1405 {
1406 StarBASIC::Error( ERRCODE_BASIC_BAD_ARGUMENT );
1407 rPar.Get(0)->PutEmpty();
1408 return;
1409 }
1410 const OUString aStr1 = rPar.Get(1)->GetOUString();
1411 const OUString aStr2 = rPar.Get(2)->GetOUString();
1412
1413 SbiInstance* pInst = GetSbData()->pInst;
1414 bool bTextCompare;
1415 bool bCompatibility = ( pInst && pInst->IsCompatibility() );
1416 if( bCompatibility )
1417 {
1418 SbiRuntime* pRT = pInst->pRun;
1419 bTextCompare = pRT && pRT->IsImageFlag( SbiImageFlags::COMPARETEXT );
1420 }
1421 else
1422 {
1423 bTextCompare = true;
1424 }
1425 if (rPar.Count() == 4)
1426 bTextCompare = rPar.Get(3)->GetInteger();
1427
1428 if( !bCompatibility )
1429 {
1430 bTextCompare = !bTextCompare;
1431 }
1432 sal_Int32 nRetValue = 0;
1433 if( bTextCompare )
1434 {
1435 ::utl::TransliterationWrapper* pTransliterationWrapper = GetSbData()->pTransliterationWrapper.get();
1436 if( !pTransliterationWrapper )
1437 {
1438 const uno::Reference< uno::XComponentContext >& xContext = getProcessComponentContext();
1439 GetSbData()->pTransliterationWrapper.reset(
1440 new ::utl::TransliterationWrapper( xContext,
1441 TransliterationFlags::IGNORE_CASE |
1442 TransliterationFlags::IGNORE_KANA |
1443 TransliterationFlags::IGNORE_WIDTH ) );
1444 pTransliterationWrapper = GetSbData()->pTransliterationWrapper.get();
1445 }
1446
1447 LanguageType eLangType = Application::GetSettings().GetLanguageTag().getLanguageType();
1448 pTransliterationWrapper->loadModuleIfNeeded( eLangType );
1449 nRetValue = pTransliterationWrapper->compareString( aStr1, aStr2 );
1450 }
1451 else
1452 {
1453 sal_Int32 aResult;
1454 aResult = aStr1.compareTo( aStr2 );
1455 if ( aResult < 0 )
1456 {
1457 nRetValue = -1;
1458 }
1459 else if ( aResult > 0)
1460 {
1461 nRetValue = 1;
1462 }
1463 }
1464 rPar.Get(0)->PutInteger(sal::static_int_cast<sal_Int16>(nRetValue));
1465 }
1466
1467 void SbRtl_String(StarBASIC *, SbxArray & rPar, bool)
1468 {
1469 if (rPar.Count() < 2)
1470 {
1471 return StarBASIC::Error(ERRCODE_BASIC_BAD_ARGUMENT);
1472 }
1473
1474 sal_Unicode aFiller;
1475 sal_Int32 lCount = rPar.Get(1)->GetLong();
1476 if( lCount < 0 || lCount > 0xffff )
1477 {
1478 StarBASIC::Error( ERRCODE_BASIC_BAD_ARGUMENT );
1479 }
1480 if (rPar.Get(2)->GetType() == SbxINTEGER)
1481 {
1482 aFiller = static_cast<sal_Unicode>(rPar.Get(2)->GetInteger());
1483 }
1484 else
1485 {
1486 const OUString aStr = rPar.Get(2)->GetOUString();
1487 aFiller = aStr[0];
1488 }
1489 rPar.Get(0)->PutString(OUString::Concat(RepeatedUChar(aFiller, lCount)));
1490 }
1491
1492 void SbRtl_Tab(StarBASIC *, SbxArray & rPar, bool)
1493 {
1494 if (rPar.Count() < 2)
1495 {
1496 return StarBASIC::Error(ERRCODE_BASIC_BAD_ARGUMENT);
1497 }
1498
1499 const sal_Int32 nCount = std::max(rPar.Get(1)->GetLong(), sal_Int32(0));
1500 rPar.Get(0)->PutString(OUString::Concat(RepeatedUChar('\t', nCount)));
1501 }
1502
1503 void SbRtl_Tan(StarBASIC *, SbxArray & rPar, bool)
1504 {
1505 if (rPar.Count() < 2)
1506 {
1507 return StarBASIC::Error(ERRCODE_BASIC_BAD_ARGUMENT);
1508 }
1509
1510 SbxVariableRef pArg = rPar.Get(1);
1511 rPar.Get(0)->PutDouble(tan(pArg->GetDouble()));
1512 }
1513
1514 void SbRtl_UCase(StarBASIC *, SbxArray & rPar, bool)
1515 {
1516 if (rPar.Count() < 2)
1517 {
1518 return StarBASIC::Error(ERRCODE_BASIC_BAD_ARGUMENT);
1519 }
1520
1521 const CharClass& rCharClass = GetCharClass();
1522 OUString aStr(rPar.Get(1)->GetOUString());
1523 aStr = rCharClass.uppercase( aStr );
1524 rPar.Get(0)->PutString(aStr);
1525 }
1526
1527
1528 void SbRtl_Val(StarBASIC *, SbxArray & rPar, bool)
1529 {
1530 if (rPar.Count() < 2)
1531 {
1532 return StarBASIC::Error(ERRCODE_BASIC_BAD_ARGUMENT);
1533 }
1534 double nResult = 0.0;
1535
1536 OUString aStr(rPar.Get(1)->GetOUString());
1537
1538 FilterWhiteSpace( aStr );
1539 if ( aStr.getLength() > 1 && aStr[0] == '&' )
1540 {
1541 sal_Unicode aChar = aStr[1];
1542 if ( aChar == 'h' || aChar == 'H' )
1543 {
1544 nResult = static_cast<sal_Int16>(o3tl::toInt64(aStr.subView(2), 16));
1545 }
1546 else if ( aChar == 'o' || aChar == 'O' )
1547 {
1548 nResult = static_cast<sal_Int16>(o3tl::toInt64(aStr.subView(2), 8));
1549 }
1550 }
1551 else
1552 {
1553 rtl_math_ConversionStatus eStatus = rtl_math_ConversionStatus_Ok;
1554 sal_Int32 nParseEnd = 0;
1555 nResult = ::rtl::math::stringToDouble( aStr, '.', ',', &eStatus, &nParseEnd );
1556 if ( eStatus != rtl_math_ConversionStatus_Ok )
1557 StarBASIC::Error( ERRCODE_BASIC_MATH_OVERFLOW );
1558 /* TODO: we should check whether all characters were parsed here,
1559 * but earlier code silently ignored trailing nonsense such as "1x"
1560 * resulting in 1 with the side effect that any alpha-only-string
1561 * like "x" resulted in 0. Not changing that now (2013-03-22) as
1562 * user macros may rely on it. */
1563 #if 0
1564 else if ( nParseEnd != aStr.getLength() )
1565 StarBASIC::Error( ERRCODE_BASIC_CONVERSION );
1566 #endif
1567 }
1568
1569 rPar.Get(0)->PutDouble(nResult);
1570 }
1571
1572
1573 // Helper functions for date conversion
1574 sal_Int16 implGetDateDay( double aDate )
1575 {
1576 aDate = floor( aDate );
1577 Date aRefDate(1899'12'30);
1578 aRefDate.AddDays( aDate );
1579
1580 sal_Int16 nRet = static_cast<sal_Int16>( aRefDate.GetDay() );
1581 return nRet;
1582 }
1583
1584 sal_Int16 implGetDateMonth( double aDate )
1585 {
1586 Date aRefDate(1899'12'30);
1587 sal_Int32 nDays = static_cast<sal_Int32>(aDate);
1588 aRefDate.AddDays( nDays );
1589 sal_Int16 nRet = static_cast<sal_Int16>( aRefDate.GetMonth() );
1590 return nRet;
1591 }
1592
1593 css::util::Date SbxDateToUNODate( const SbxValue* const pVal )
1594 {
1595 double aDate = pVal->GetDate();
1596
1597 css::util::Date aUnoDate;
1598 aUnoDate.Day = implGetDateDay ( aDate );
1599 aUnoDate.Month = implGetDateMonth( aDate );
1600 aUnoDate.Year = implGetDateYear ( aDate );
1601
1602 return aUnoDate;
1603 }
1604
1605 void SbxDateFromUNODate( SbxValue *pVal, const css::util::Date& aUnoDate)
1606 {
1607 double dDate;
1608 if( implDateSerial( aUnoDate.Year, aUnoDate.Month, aUnoDate.Day, false, SbDateCorrection::None, dDate ) )
1609 {
1610 pVal->PutDate( dDate );
1611 }
1612 }
1613
1614 // Function to convert date to UNO date (com.sun.star.util.Date)
1615 void SbRtl_CDateToUnoDate(StarBASIC *, SbxArray & rPar, bool)
1616 {
1617 if (rPar.Count() != 2)
1618 {
1619 return StarBASIC::Error( ERRCODE_BASIC_BAD_ARGUMENT );
1620 }
1621
1622 unoToSbxValue(rPar.Get(0), Any(SbxDateToUNODate(rPar.Get(1))));
1623 }
1624
1625 // Function to convert date from UNO date (com.sun.star.util.Date)
1626 void SbRtl_CDateFromUnoDate(StarBASIC *, SbxArray & rPar, bool)
1627 {
1628 if (rPar.Count() != 2 || rPar.Get(1)->GetType() != SbxOBJECT)
1629 {
1630 return StarBASIC::Error( ERRCODE_BASIC_BAD_ARGUMENT );
1631 }
1632
1633 Any aAny(sbxToUnoValue(rPar.Get(1), cppu::UnoType<css::util::Date>::get()));
1634 css::util::Date aUnoDate;
1635 if(aAny >>= aUnoDate)
1636 SbxDateFromUNODate(rPar.Get(0), aUnoDate);
1637 else
1638 SbxBase::SetError( ERRCODE_BASIC_CONVERSION );
1639 }
1640
1641 css::util::Time SbxDateToUNOTime( const SbxValue* const pVal )
1642 {
1643 double aDate = pVal->GetDate();
1644
1645 css::util::Time aUnoTime;
1646 aUnoTime.Hours = implGetHour ( aDate );
1647 aUnoTime.Minutes = implGetMinute ( aDate );
1648 aUnoTime.Seconds = implGetSecond ( aDate );
1649 aUnoTime.NanoSeconds = implGetNanoSecond( aDate );
1650
1651 return aUnoTime;
1652 }
1653
1654 void SbxDateFromUNOTime( SbxValue *pVal, const css::util::Time& aUnoTime)
1655 {
1656 pVal->PutDate(implTimeSerial(aUnoTime.Hours, aUnoTime.Minutes, aUnoTime.Seconds,
1657 nanoSecToMilliSec(aUnoTime.NanoSeconds)));
1658 }
1659
1660 // Function to convert date to UNO time (com.sun.star.util.Time)
1661 void SbRtl_CDateToUnoTime(StarBASIC *, SbxArray & rPar, bool)
1662 {
1663 if (rPar.Count() != 2)
1664 {
1665 return StarBASIC::Error( ERRCODE_BASIC_BAD_ARGUMENT );
1666 }
1667
1668 unoToSbxValue(rPar.Get(0), Any(SbxDateToUNOTime(rPar.Get(1))));
1669 }
1670
1671 // Function to convert date from UNO time (com.sun.star.util.Time)
1672 void SbRtl_CDateFromUnoTime(StarBASIC *, SbxArray & rPar, bool)
1673 {
1674 if (rPar.Count() != 2 || rPar.Get(1)->GetType() != SbxOBJECT)
1675 {
1676 return StarBASIC::Error( ERRCODE_BASIC_BAD_ARGUMENT );
1677 }
1678
1679 Any aAny(sbxToUnoValue(rPar.Get(1), cppu::UnoType<css::util::Time>::get()));
1680 css::util::Time aUnoTime;
1681 if(aAny >>= aUnoTime)
1682 SbxDateFromUNOTime(rPar.Get(0), aUnoTime);
1683 else
1684 SbxBase::SetError( ERRCODE_BASIC_CONVERSION );
1685 }
1686
1687 css::util::DateTime SbxDateToUNODateTime( const SbxValue* const pVal )
1688 {
1689 double aDate = pVal->GetDate();
1690
1691 css::util::DateTime aUnoDT;
1692 aUnoDT.Day = implGetDateDay ( aDate );
1693 aUnoDT.Month = implGetDateMonth( aDate );
1694 aUnoDT.Year = implGetDateYear ( aDate );
1695 aUnoDT.Hours = implGetHour ( aDate );
1696 aUnoDT.Minutes = implGetMinute ( aDate );
1697 aUnoDT.Seconds = implGetSecond ( aDate );
1698 aUnoDT.NanoSeconds = implGetNanoSecond( aDate );
1699
1700 return aUnoDT;
1701 }
1702
1703 void SbxDateFromUNODateTime( SbxValue *pVal, const css::util::DateTime& aUnoDT)
1704 {
1705 double dDate(0.0);
1706 if (implDateTimeSerial(aUnoDT.Year, aUnoDT.Month, aUnoDT.Day, aUnoDT.Hours, aUnoDT.Minutes,
1707 aUnoDT.Seconds, nanoSecToMilliSec(aUnoDT.NanoSeconds), dDate))
1708 {
1709 pVal->PutDate( dDate );
1710 }
1711 }
1712
1713 // Function to convert date to UNO date (com.sun.star.util.Date)
1714 void SbRtl_CDateToUnoDateTime(StarBASIC *, SbxArray & rPar, bool)
1715 {
1716 if (rPar.Count() != 2)
1717 {
1718 return StarBASIC::Error( ERRCODE_BASIC_BAD_ARGUMENT );
1719 }
1720
1721 unoToSbxValue(rPar.Get(0), Any(SbxDateToUNODateTime(rPar.Get(1))));
1722 }
1723
1724 // Function to convert date from UNO date (com.sun.star.util.Date)
1725 void SbRtl_CDateFromUnoDateTime(StarBASIC *, SbxArray & rPar, bool)
1726 {
1727 if (rPar.Count() != 2 || rPar.Get(1)->GetType() != SbxOBJECT)
1728 {
1729 return StarBASIC::Error( ERRCODE_BASIC_BAD_ARGUMENT );
1730 }
1731
1732 Any aAny(sbxToUnoValue(rPar.Get(1), cppu::UnoType<css::util::DateTime>::get()));
1733 css::util::DateTime aUnoDT;
1734 if(aAny >>= aUnoDT)
1735 SbxDateFromUNODateTime(rPar.Get(0), aUnoDT);
1736 else
1737 SbxBase::SetError( ERRCODE_BASIC_CONVERSION );
1738 }
1739
1740 // Function to convert date to ISO 8601 date format YYYYMMDD
1741 void SbRtl_CDateToIso(StarBASIC *, SbxArray & rPar, bool)
1742 {
1743 if (rPar.Count() != 2)
1744 return StarBASIC::Error(ERRCODE_BASIC_BAD_ARGUMENT);
1745
1746 double aDate = rPar.Get(1)->GetDate();
1747
1748 // Date may actually even be -YYYYYMMDD
1749 char Buffer[11];
1750 sal_Int16 nYear = implGetDateYear(aDate);
1751 snprintf(Buffer, sizeof(Buffer), (nYear < 0 ? "%05d%02d%02d" : "%04d%02d%02d"),
1752 static_cast<int>(nYear), static_cast<int>(implGetDateMonth(aDate)),
1753 static_cast<int>(implGetDateDay(aDate)));
1754 OUString aRetStr = OUString::createFromAscii(Buffer);
1755 rPar.Get(0)->PutString(aRetStr);
1756 }
1757
1758 // Function to convert date from ISO 8601 date format YYYYMMDD or YYYY-MM-DD
1759 // And even YYMMDD for compatibility, sigh...
1760 void SbRtl_CDateFromIso(StarBASIC *, SbxArray & rPar, bool)
1761 {
1762 if (rPar.Count() != 2)
1763 return StarBASIC::Error( ERRCODE_BASIC_BAD_ARGUMENT );
1764 OUString aStr = rPar.Get(1)->GetOUString();
1765 if (aStr.isEmpty())
1766 return SbxBase::SetError( ERRCODE_BASIC_BAD_PARAMETER );
1767
1768 // Valid formats are
1769 // YYYYMMDD -YYYMMDD YYYYYMMDD -YYYYYMMDD YYMMDD
1770 // YYYY-MM-DD -YYYY-MM-DD YYYYY-MM-DD -YYYYY-MM-DD
1771
1772 sal_Int32 nSign = 1;
1773 if (aStr[0] == '-')
1774 {
1775 nSign = -1;
1776 aStr = aStr.copy(1);
1777 }
1778 const sal_Int32 nLen = aStr.getLength();
1779
1780 // Signed YYMMDD two digit year is invalid.
1781 if (nLen == 6 && nSign == -1)
1782 return SbxBase::SetError( ERRCODE_BASIC_BAD_PARAMETER );
1783
1784 // Now valid
1785 // YYYYMMDD YYYYYMMDD YYMMDD
1786 // YYYY-MM-DD YYYYY-MM-DD
1787 if (nLen != 6 && (nLen < 8 || 11 < nLen))
1788 return SbxBase::SetError( ERRCODE_BASIC_BAD_PARAMETER );
1789
1790 bool bUseTwoDigitYear = false;
1791 std::u16string_view aYearStr, aMonthStr, aDayStr;
1792 if (nLen == 6 || nLen == 8 || nLen == 9)
1793 {
1794 // ((Y)YY)YYMMDD
1795 if (!comphelper::string::isdigitAsciiString(aStr))
1796 return SbxBase::SetError( ERRCODE_BASIC_BAD_PARAMETER );
1797
1798 const sal_Int32 nMonthPos = (nLen == 8 ? 4 : (nLen == 6 ? 2 : 5));
1799 if (nMonthPos == 2)
1800 bUseTwoDigitYear = true;
1801 aYearStr = aStr.subView( 0, nMonthPos );
1802 aMonthStr = aStr.subView( nMonthPos, 2 );
1803 aDayStr = aStr.subView( nMonthPos + 2, 2 );
1804 }
1805 else
1806 {
1807 // (Y)YYYY-MM-DD
1808 const sal_Int32 nMonthSep = (nLen == 11 ? 5 : 4);
1809 if (aStr.indexOf('-') != nMonthSep)
1810 return SbxBase::SetError( ERRCODE_BASIC_BAD_PARAMETER );
1811 if (aStr.indexOf('-', nMonthSep + 1) != nMonthSep + 3)
1812 return SbxBase::SetError( ERRCODE_BASIC_BAD_PARAMETER );
1813
1814 aYearStr = aStr.subView( 0, nMonthSep );
1815 aMonthStr = aStr.subView( nMonthSep + 1, 2 );
1816 aDayStr = aStr.subView( nMonthSep + 4, 2 );
1817 if ( !comphelper::string::isdigitAsciiString(aYearStr) ||
1818 !comphelper::string::isdigitAsciiString(aMonthStr) ||
1819 !comphelper::string::isdigitAsciiString(aDayStr))
1820 return SbxBase::SetError( ERRCODE_BASIC_BAD_PARAMETER );
1821 }
1822
1823 double dDate;
1824 if (!implDateSerial( static_cast<sal_Int16>(nSign * o3tl::toInt32(aYearStr)),
1825 static_cast<sal_Int16>(o3tl::toInt32(aMonthStr)), static_cast<sal_Int16>(o3tl::toInt32(aDayStr)),
1826 bUseTwoDigitYear, SbDateCorrection::None, dDate ))
1827 return SbxBase::SetError( ERRCODE_BASIC_BAD_PARAMETER );
1828
1829 rPar.Get(0)->PutDate(dDate);
1830 }
1831
1832 void SbRtl_DateSerial(StarBASIC *, SbxArray & rPar, bool)
1833 {
1834 if (rPar.Count() < 4)
1835 {
1836 return StarBASIC::Error( ERRCODE_BASIC_BAD_ARGUMENT );
1837 }
1838 sal_Int16 nYear = rPar.Get(1)->GetInteger();
1839 sal_Int16 nMonth = rPar.Get(2)->GetInteger();
1840 sal_Int16 nDay = rPar.Get(3)->GetInteger();
1841
1842 double dDate;
1843 if( implDateSerial( nYear, nMonth, nDay, true, SbDateCorrection::RollOver, dDate ) )
1844 {
1845 rPar.Get(0)->PutDate(dDate);
1846 }
1847 }
1848
1849 void SbRtl_TimeSerial(StarBASIC *, SbxArray & rPar, bool)
1850 {
1851 if (rPar.Count() < 4)
1852 {
1853 return StarBASIC::Error( ERRCODE_BASIC_BAD_ARGUMENT );
1854 }
1855 sal_Int16 nHour = rPar.Get(1)->GetInteger();
1856 if ( nHour == 24 )
1857 {
1858 nHour = 0; // because of UNO DateTimes, which go till 24 o'clock
1859 }
1860 sal_Int16 nMinute = rPar.Get(2)->GetInteger();
1861 sal_Int16 nSecond = rPar.Get(3)->GetInteger();
1862 if ((nHour < 0 || nHour > 23) ||
1863 (nMinute < 0 || nMinute > 59 ) ||
1864 (nSecond < 0 || nSecond > 59 ))
1865 {
1866 return StarBASIC::Error( ERRCODE_BASIC_BAD_ARGUMENT );
1867 }
1868
1869 rPar.Get(0)->PutDate(implTimeSerial(nHour, nMinute, nSecond, 0)); // JSM
1870 }
1871
1872 void SbRtl_DateValue(StarBASIC *, SbxArray & rPar, bool)
1873 {
1874 if (rPar.Count() < 2)
1875 {
1876 StarBASIC::Error( ERRCODE_BASIC_BAD_ARGUMENT );
1877 }
1878 else
1879 {
1880 // #39629 check GetSbData()->pInst, can be called from the URL line
1881 std::shared_ptr<SvNumberFormatter> pFormatter;
1882 if( GetSbData()->pInst )
1883 {
1884 pFormatter = GetSbData()->pInst->GetNumberFormatter();
1885 }
1886 else
1887 {
1888 sal_uInt32 n; // Dummy
1889 pFormatter = SbiInstance::PrepareNumberFormatter( n, n, n );
1890 }
1891
1892 LanguageType eLangType = Application::GetSettings().GetLanguageTag().getLanguageType();
1893 sal_uInt32 nIndex = pFormatter->GetStandardIndex( eLangType);
1894 double fResult;
1895 OUString aStr(rPar.Get(1)->GetOUString());
1896 bool bSuccess = pFormatter->IsNumberFormat( aStr, nIndex, fResult );
1897 SvNumFormatType nType = pFormatter->GetType( nIndex );
1898
1899 // DateValue("February 12, 1969") raises error if the system locale is not en_US
1900 // It seems that both locale number formatter and English number
1901 // formatter are supported in Visual Basic.
1902 if( !bSuccess && ( eLangType != LANGUAGE_ENGLISH_US ) )
1903 {
1904 // Try using LANGUAGE_ENGLISH_US to get the date value.
1905 nIndex = pFormatter->GetStandardIndex( LANGUAGE_ENGLISH_US);
1906 bSuccess = pFormatter->IsNumberFormat( aStr, nIndex, fResult );
1907 nType = pFormatter->GetType( nIndex );
1908 }
1909
1910 if(bSuccess && (nType==SvNumFormatType::DATE || nType==SvNumFormatType::DATETIME))
1911 {
1912 if ( nType == SvNumFormatType::DATETIME )
1913 {
1914 // cut time
1915 if ( fResult > 0.0 )
1916 {
1917 fResult = floor( fResult );
1918 }
1919 else
1920 {
1921 fResult = ceil( fResult );
1922 }
1923 }
1924 rPar.Get(0)->PutDate(fResult);
1925 }
1926 else
1927 {
1928 StarBASIC::Error( ERRCODE_BASIC_CONVERSION );
1929 }
1930 }
1931 }
1932
1933 void SbRtl_TimeValue(StarBASIC *, SbxArray & rPar, bool)
1934 {
1935 if (rPar.Count() < 2)
1936 {
1937 StarBASIC::Error( ERRCODE_BASIC_BAD_ARGUMENT );
1938 }
1939 else
1940 {
1941 std::shared_ptr<SvNumberFormatter> pFormatter;
1942 if( GetSbData()->pInst )
1943 pFormatter = GetSbData()->pInst->GetNumberFormatter();
1944 else
1945 {
1946 sal_uInt32 n;
1947 pFormatter = SbiInstance::PrepareNumberFormatter( n, n, n );
1948 }
1949
1950 sal_uInt32 nIndex = 0;
1951 double fResult;
1952 bool bSuccess = pFormatter->IsNumberFormat(rPar.Get(1)->GetOUString(),
1953 nIndex, fResult );
1954 SvNumFormatType nType = pFormatter->GetType(nIndex);
1955 if(bSuccess && (nType==SvNumFormatType::TIME||nType==SvNumFormatType::DATETIME))
1956 {
1957 if ( nType == SvNumFormatType::DATETIME )
1958 {
1959 // cut days
1960 fResult = fmod( fResult, 1 );
1961 }
1962 rPar.Get(0)->PutDate(fResult);
1963 }
1964 else
1965 {
1966 StarBASIC::Error( ERRCODE_BASIC_CONVERSION );
1967 }
1968 }
1969 }
1970
1971 void SbRtl_Day(StarBASIC *, SbxArray & rPar, bool)
1972 {
1973 if (rPar.Count() != 2)
1974 return StarBASIC::Error( ERRCODE_BASIC_BAD_ARGUMENT );
1975 SbxVariableRef pArg = rPar.Get(1);
1976 double aDate = pArg->GetDate();
1977
1978 sal_Int16 nDay = implGetDateDay( aDate );
1979 rPar.Get(0)->PutInteger(nDay);
1980 }
1981
1982 void SbRtl_Year(StarBASIC *, SbxArray & rPar, bool)
1983 {
1984 if (rPar.Count() != 2)
1985 return StarBASIC::Error( ERRCODE_BASIC_BAD_ARGUMENT );
1986 sal_Int16 nYear = implGetDateYear(rPar.Get(1)->GetDate());
1987 rPar.Get(0)->PutInteger(nYear);
1988 }
1989
1990 sal_Int16 implGetHour( double dDate )
1991 {
1992 double nFrac = (dDate - floor(dDate)) * ::tools::Time::milliSecPerDay;
1993 sal_uInt64 nMilliSeconds = static_cast<sal_uInt64>(nFrac + 0.5);
1994 return static_cast<sal_Int16>((nMilliSeconds / ::tools::Time::milliSecPerHour)
1995 % ::tools::Time::hourPerDay);
1996 }
1997
1998 void SbRtl_Hour(StarBASIC *, SbxArray & rPar, bool)
1999 {
2000 if (rPar.Count() != 2)
2001 return StarBASIC::Error( ERRCODE_BASIC_BAD_ARGUMENT );
2002 double nArg = rPar.Get(1)->GetDate();
2003 sal_Int16 nHour = implGetHour( nArg );
2004 rPar.Get(0)->PutInteger(nHour);
2005 }
2006
2007 void SbRtl_Minute(StarBASIC *, SbxArray & rPar, bool)
2008 {
2009 if (rPar.Count() != 2)
2010 return StarBASIC::Error( ERRCODE_BASIC_BAD_ARGUMENT );
2011 double nArg = rPar.Get(1)->GetDate();
2012 sal_Int16 nMin = implGetMinute( nArg );
2013 rPar.Get(0)->PutInteger(nMin);
2014 }
2015
2016 void SbRtl_Month(StarBASIC *, SbxArray & rPar, bool)
2017 {
2018 if (rPar.Count() != 2)
2019 return StarBASIC::Error( ERRCODE_BASIC_BAD_ARGUMENT );
2020 sal_Int16 nMonth = implGetDateMonth(rPar.Get(1)->GetDate());
2021 rPar.Get(0)->PutInteger(nMonth);
2022 }
2023
2024 sal_Int16 implGetSecond( double dDate )
2025 {
2026 double nFrac = (dDate - floor(dDate)) * ::tools::Time::milliSecPerDay;
2027 sal_uInt64 nMilliSeconds = static_cast<sal_uInt64>(nFrac + 0.5);
2028 return static_cast<sal_Int16>((nMilliSeconds / ::tools::Time::milliSecPerSec)
2029 % ::tools::Time::secondPerMinute);
2030 }
2031
2032 sal_Int32 implGetNanoSecond(double dDate)
2033 {
2034 double nFrac = (dDate - floor(dDate)) * ::tools::Time::milliSecPerDay;
2035 sal_uInt64 nMilliSeconds = static_cast<sal_uInt64>(nFrac + 0.5);
2036 nMilliSeconds %= ::tools::Time::milliSecPerSec;
2037
2038 return static_cast<sal_Int32>(nMilliSeconds * ::tools::Time ::nanoPerMilli);
2039 }
2040
2041 void SbRtl_Second(StarBASIC *, SbxArray & rPar, bool)
2042 {
2043 if (rPar.Count() != 2)
2044 return StarBASIC::Error( ERRCODE_BASIC_BAD_ARGUMENT );
2045 double nArg = rPar.Get(1)->GetDate();
2046 sal_Int16 nSecond = implGetSecond( nArg );
2047 rPar.Get(0)->PutInteger(nSecond);
2048 }
2049
2050 double Now_Impl()
2051 {
2052 // tdf#161469 - align implementation with the now function in calc, i.e., include subseconds
2053 DateTime aActTime(DateTime::SYSTEM);
2054 return static_cast<double>(GetDayDiff(aActTime))
2055 + implTimeSerial(aActTime.GetHour(), aActTime.GetMin(), aActTime.GetSec(),
2056 nanoSecToMilliSec(aActTime.GetNanoSec()));
2057 }
2058
2059 // Date Now()
2060
2061 void SbRtl_Now(StarBASIC*, SbxArray& rPar, bool)
2062 {
2063 if (rPar.Count() != 1)
2064 return StarBASIC::Error( ERRCODE_BASIC_BAD_ARGUMENT );
2065
2066 rPar.Get(0)->PutDate(Now_Impl());
2067 }
2068
2069 // Date Time()
2070
2071 void SbRtl_Time(StarBASIC *, SbxArray & rPar, bool bWrite)
2072 {
2073 if (bWrite)
2074 return StarBASIC::Error( ERRCODE_BASIC_NOT_IMPLEMENTED );
2075
2076 tools::Time aTime( tools::Time::SYSTEM );
2077 SbxVariable* pMeth = rPar.Get(0);
2078 if (!pMeth->IsString())
2079 {
2080 pMeth->PutDate(aTime.GetTimeInDays());
2081 return;
2082 }
2083 OUString aRes;
2084 if( pMeth->IsFixed() )
2085 {
2086 // Time$: hh:mm:ss
2087 char buf[ 20 ];
2088 snprintf( buf, sizeof(buf), "%02d:%02d:%02d",
2089 aTime.GetHour(), aTime.GetMin(), aTime.GetSec() );
2090 aRes = OUString::createFromAscii( buf );
2091 }
2092 else
2093 {
2094 // Time: system dependent
2095 tools::Long nSeconds=aTime.GetHour();
2096 nSeconds *= 3600;
2097 nSeconds += aTime.GetMin() * 60;
2098 nSeconds += aTime.GetSec();
2099 double nDays = static_cast<double>(nSeconds) * ( 1.0 / (24.0*3600.0) );
2100 const Color* pCol;
2101
2102 std::shared_ptr<SvNumberFormatter> pFormatter;
2103 sal_uInt32 nIndex;
2104 if( GetSbData()->pInst )
2105 {
2106 pFormatter = GetSbData()->pInst->GetNumberFormatter();
2107 nIndex = GetSbData()->pInst->GetStdTimeIdx();
2108 }
2109 else
2110 {
2111 sal_uInt32 n; // Dummy
2112 pFormatter = SbiInstance::PrepareNumberFormatter( n, nIndex, n );
2113 }
2114
2115 pFormatter->GetOutputString( nDays, nIndex, aRes, &pCol );
2116 }
2117 pMeth->PutString( aRes );
2118 }
2119
2120 void SbRtl_Timer(StarBASIC *, SbxArray & rPar, bool)
2121 {
2122 tools::Time aTime( tools::Time::SYSTEM );
2123 tools::Long nSeconds = aTime.GetHour();
2124 nSeconds *= 3600;
2125 nSeconds += aTime.GetMin() * 60;
2126 nSeconds += aTime.GetSec();
2127 rPar.Get(0)->PutDate(static_cast<double>(nSeconds));
2128 }
2129
2130
2131 void SbRtl_Date(StarBASIC *, SbxArray & rPar, bool bWrite)
2132 {
2133 if (bWrite)
2134 return StarBASIC::Error(ERRCODE_BASIC_NOT_IMPLEMENTED);
2135
2136 Date aToday( Date::SYSTEM );
2137 double nDays = static_cast<double>(GetDayDiff( aToday ));
2138 SbxVariable* pMeth = rPar.Get(0);
2139 if( pMeth->IsString() )
2140 {
2141 OUString aRes;
2142 const Color* pCol;
2143
2144 std::shared_ptr<SvNumberFormatter> pFormatter;
2145 sal_uInt32 nIndex;
2146 if( GetSbData()->pInst )
2147 {
2148 pFormatter = GetSbData()->pInst->GetNumberFormatter();
2149 nIndex = GetSbData()->pInst->GetStdDateIdx();
2150 }
2151 else
2152 {
2153 sal_uInt32 n;
2154 pFormatter = SbiInstance::PrepareNumberFormatter( nIndex, n, n );
2155 }
2156
2157 pFormatter->GetOutputString( nDays, nIndex, aRes, &pCol );
2158 pMeth->PutString( aRes );
2159 }
2160 else
2161 {
2162 pMeth->PutDate( nDays );
2163 }
2164 }
2165
2166 void SbRtl_IsArray(StarBASIC *, SbxArray & rPar, bool)
2167 {
2168 if (rPar.Count() != 2)
2169 return StarBASIC::Error( ERRCODE_BASIC_BAD_ARGUMENT );
2170
2171 rPar.Get(0)->PutBool((rPar.Get(1)->GetType() & SbxARRAY) != 0);
2172 }
2173
2174 void SbRtl_IsObject(StarBASIC *, SbxArray & rPar, bool)
2175 {
2176 if (rPar.Count() != 2)
2177 return StarBASIC::Error( ERRCODE_BASIC_BAD_ARGUMENT );
2178
2179 SbxVariable* pVar = rPar.Get(1);
2180 bool bObject = pVar->IsObject();
2181 SbxBase* pObj = (bObject ? pVar->GetObject() : nullptr);
2182
2183 if( auto pUnoClass = dynamic_cast<SbUnoClass*>( pObj) )
2184 {
2185 bObject = pUnoClass->getUnoClass().is();
2186 }
2187 rPar.Get(0)->PutBool(bObject);
2188 }
2189
2190 void SbRtl_IsDate(StarBASIC *, SbxArray & rPar, bool)
2191 {
2192 if (rPar.Count() != 2)
2193 return StarBASIC::Error( ERRCODE_BASIC_BAD_ARGUMENT );
2194
2195 // #46134 only string is converted, all other types result in sal_False
2196 SbxVariableRef xArg = rPar.Get(1);
2197 SbxDataType eType = xArg->GetType();
2198 bool bDate = false;
2199
2200 if( eType == SbxDATE )
2201 {
2202 bDate = true;
2203 }
2204 else if( eType == SbxSTRING )
2205 {
2206 ErrCode nPrevError = SbxBase::GetError();
2207 SbxBase::ResetError();
2208
2209 // force conversion of the parameter to SbxDATE
2210 xArg->SbxValue::GetDate();
2211
2212 bDate = !SbxBase::IsError();
2213
2214 SbxBase::ResetError();
2215 SbxBase::SetError( nPrevError );
2216 }
2217 rPar.Get(0)->PutBool(bDate);
2218 }
2219
2220 void SbRtl_IsEmpty(StarBASIC *, SbxArray & rPar, bool)
2221 {
2222 if (rPar.Count() != 2)
2223 return StarBASIC::Error( ERRCODE_BASIC_BAD_ARGUMENT );
2224
2225 SbxVariable* pVar = nullptr;
2226 if( SbiRuntime::isVBAEnabled() )
2227 {
2228 pVar = getDefaultProp(rPar.Get(1));
2229 }
2230 if ( pVar )
2231 {
2232 pVar->Broadcast( SfxHintId::BasicDataWanted );
2233 rPar.Get(0)->PutBool(pVar->IsEmpty());
2234 }
2235 else
2236 {
2237 rPar.Get(0)->PutBool(rPar.Get(1)->IsEmpty());
2238 }
2239 }
2240
2241 void SbRtl_IsError(StarBASIC *, SbxArray & rPar, bool)
2242 {
2243 if (rPar.Count() != 2)
2244 return StarBASIC::Error( ERRCODE_BASIC_BAD_ARGUMENT );
2245
2246 SbxVariable* pVar = rPar.Get(1);
2247 SbUnoObject* pObj = dynamic_cast<SbUnoObject*>( pVar );
2248 if ( !pObj )
2249 {
2250 if ( SbxBase* pBaseObj = (pVar->IsObject() ? pVar->GetObject() : nullptr) )
2251 {
2252 pObj = dynamic_cast<SbUnoObject*>( pBaseObj );
2253 }
2254 }
2255 uno::Reference< script::XErrorQuery > xError;
2256 if ( pObj )
2257 {
2258 xError.set( pObj->getUnoAny(), uno::UNO_QUERY );
2259 }
2260 if ( xError.is() )
2261 {
2262 rPar.Get(0)->PutBool(xError->hasError());
2263 }
2264 else
2265 {
2266 rPar.Get(0)->PutBool(rPar.Get(1)->IsErr());
2267 }
2268 }
2269
2270 void SbRtl_IsNull(StarBASIC *, SbxArray & rPar, bool)
2271 {
2272 if (rPar.Count() != 2)
2273 return StarBASIC::Error( ERRCODE_BASIC_BAD_ARGUMENT );
2274
2275 // #51475 because of Uno-objects return true
2276 // even if the pObj value is NULL
2277 SbxVariableRef pArg = rPar.Get(1);
2278 bool bNull = rPar.Get(1)->IsNull();
2279 if( !bNull && pArg->GetType() == SbxOBJECT )
2280 {
2281 SbxBase* pObj = pArg->GetObject();
2282 if( !pObj )
2283 {
2284 bNull = true;
2285 }
2286 }
2287 rPar.Get(0)->PutBool(bNull);
2288 }
2289
2290 void SbRtl_IsNumeric(StarBASIC *, SbxArray & rPar, bool)
2291 {
2292 if (rPar.Count() != 2)
2293 return StarBASIC::Error( ERRCODE_BASIC_BAD_ARGUMENT );
2294
2295 rPar.Get(0)->PutBool(rPar.Get(1)->IsNumericRTL());
2296 }
2297
2298
2299 void SbRtl_IsMissing(StarBASIC *, SbxArray & rPar, bool)
2300 {
2301 if (rPar.Count() != 2)
2302 return StarBASIC::Error( ERRCODE_BASIC_BAD_ARGUMENT );
2303
2304 // #57915 Missing is reported by an error
2305 rPar.Get(0)->PutBool(rPar.Get(1)->IsErr());
2306 }
2307
2308 // Function looks for wildcards, removes them and always returns the pure path
2309 static OUString implSetupWildcard(const OUString& rFileParam, SbiRTLData& rRTLData)
2310 {
2311 static const char cDelim1 = '/';
2312 static const char cDelim2 = '\\';
2313 static const char cWild1 = '*';
2314 static const char cWild2 = '?';
2315
2316 rRTLData.moWildCard.reset();
2317 rRTLData.sFullNameToBeChecked.clear();
2318
2319 OUString aFileParam = rFileParam;
2320 sal_Int32 nLastWild = aFileParam.lastIndexOf( cWild1 );
2321 if( nLastWild < 0 )
2322 {
2323 nLastWild = aFileParam.lastIndexOf( cWild2 );
2324 }
2325 bool bHasWildcards = ( nLastWild >= 0 );
2326
2327
2328 sal_Int32 nLastDelim = aFileParam.lastIndexOf( cDelim1 );
2329 if( nLastDelim < 0 )
2330 {
2331 nLastDelim = aFileParam.lastIndexOf( cDelim2 );
2332 }
2333 if( bHasWildcards )
2334 {
2335 // Wildcards in path?
2336 if( nLastDelim >= 0 && nLastDelim > nLastWild )
2337 {
2338 return aFileParam;
2339 }
2340 }
2341 else
2342 {
2343 OUString aPathStr = getFullPath( aFileParam );
2344 if( nLastDelim != aFileParam.getLength() - 1 )
2345 {
2346 rRTLData.sFullNameToBeChecked = aPathStr;
2347 }
2348 return aPathStr;
2349 }
2350
2351 OUString aPureFileName;
2352 if( nLastDelim < 0 )
2353 {
2354 aPureFileName = aFileParam;
2355 aFileParam.clear();
2356 }
2357 else
2358 {
2359 aPureFileName = aFileParam.copy( nLastDelim + 1 );
2360 aFileParam = aFileParam.copy( 0, nLastDelim );
2361 }
2362
2363 // Try again to get a valid URL/UNC-path with only the path
2364 OUString aPathStr = getFullPath( aFileParam );
2365
2366 // Is there a pure file name left? Otherwise the path is
2367 // invalid anyway because it was not accepted by OSL before
2368 if (aPureFileName != "*")
2369 {
2370 rRTLData.moWildCard.emplace(aPureFileName);
2371 }
2372 return aPathStr;
2373 }
2374
2375 static bool implCheckWildcard(std::u16string_view rName, SbiRTLData const& rRTLData)
2376 {
2377 bool bMatch = true;
2378
2379 if (rRTLData.moWildCard)
2380 {
2381 bMatch = rRTLData.moWildCard->Matches(rName);
2382 }
2383 return bMatch;
2384 }
2385
2386
2387 static bool isRootDir( std::u16string_view aDirURLStr )
2388 {
2389 INetURLObject aDirURLObj( aDirURLStr );
2390 bool bRoot = false;
2391
2392 // Check if it's a root directory
2393 sal_Int32 nCount = aDirURLObj.getSegmentCount();
2394
2395 // No segment means Unix root directory "file:///"
2396 if( nCount == 0 )
2397 {
2398 bRoot = true;
2399 }
2400 // Exactly one segment needs further checking, because it
2401 // can be Unix "file:///foo/" -> no root
2402 // or Windows "file:///c:/" -> root
2403 else if( nCount == 1 )
2404 {
2405 OUString aSeg1 = aDirURLObj.getName( 0, true,
2406 INetURLObject::DecodeMechanism::WithCharset );
2407 if( aSeg1[1] == ':' )
2408 {
2409 bRoot = true;
2410 }
2411 }
2412 // More than one segments can never be root
2413 // so bRoot remains false
2414
2415 return bRoot;
2416 }
2417
2418 void SbRtl_Dir(StarBASIC *, SbxArray & rPar, bool)
2419 {
2420 OUString aPath;
2421
2422 const sal_uInt32 nParCount = rPar.Count();
2423 if( nParCount > 3 )
2424 return StarBASIC::Error(ERRCODE_BASIC_BAD_ARGUMENT);
2425
2426 SbiRTLData& rRTLData = GetSbData()->pInst->GetRTLData();
2427 if( hasUno() )
2428 {
2429 const uno::Reference< ucb::XSimpleFileAccess3 >& xSFI = getFileAccess();
2430 if( xSFI.is() )
2431 {
2432 if ( nParCount >= 2 )
2433 {
2434 OUString aFileParam = rPar.Get(1)->GetOUString();
2435
2436 OUString aFileURLStr = implSetupWildcard(aFileParam, rRTLData);
2437 if (!rRTLData.sFullNameToBeChecked.isEmpty())
2438 {
2439 bool bExists = false;
2440 try { bExists = xSFI->exists( aFileURLStr ); }
2441 catch(const Exception & ) {}
2442
2443 OUString aNameOnlyStr;
2444 if( bExists )
2445 {
2446 INetURLObject aFileURL( aFileURLStr );
2447 aNameOnlyStr = aFileURL.getName( INetURLObject::LAST_SEGMENT,
2448 true, INetURLObject::DecodeMechanism::WithCharset );
2449 }
2450 rPar.Get(0)->PutString(aNameOnlyStr);
2451 return;
2452 }
2453
2454 try
2455 {
2456 OUString aDirURLStr;
2457 bool bFolder = xSFI->isFolder( aFileURLStr );
2458
2459 if( bFolder )
2460 {
2461 aDirURLStr = aFileURLStr;
2462 }
2463 else
2464 {
2465 rPar.Get(0)->PutString(u""_ustr);
2466 }
2467
2468 sal_Int16 nFlags = SbAttributes::NORMAL;
2469 if ( nParCount > 2 )
2470 {
2471 rRTLData.nDirFlags = nFlags = rPar.Get(2)->GetInteger();
2472 }
2473 else
2474 {
2475 rRTLData.nDirFlags = SbAttributes::NORMAL;
2476 }
2477 // Read directory
2478 bool bIncludeFolders = bool(nFlags & SbAttributes::DIRECTORY);
2479 rRTLData.aDirSeq = xSFI->getFolderContents(aDirURLStr, bIncludeFolders);
2480 rRTLData.nCurDirPos = 0;
2481
2482 // #78651 Add "." and ".." directories for VB compatibility
2483 if( bIncludeFolders )
2484 {
2485 bool bRoot = isRootDir( aDirURLStr );
2486
2487 // If it's no root directory we flag the need for
2488 // the "." and ".." directories by the value -2
2489 // for the actual position. Later for -2 will be
2490 // returned "." and for -1 ".."
2491 if( !bRoot )
2492 {
2493 rRTLData.nCurDirPos = -2;
2494 }
2495 }
2496 }
2497 catch(const Exception & )
2498 {
2499 }
2500 }
2501
2502
2503 if (rRTLData.aDirSeq.hasElements())
2504 {
2505 bool bFolderFlag = bool(rRTLData.nDirFlags & SbAttributes::DIRECTORY);
2506
2507 SbiInstance* pInst = GetSbData()->pInst;
2508 bool bCompatibility = ( pInst && pInst->IsCompatibility() );
2509 for( ;; )
2510 {
2511 if (rRTLData.nCurDirPos < 0)
2512 {
2513 if (rRTLData.nCurDirPos == -2)
2514 {
2515 aPath = ".";
2516 }
2517 else if (rRTLData.nCurDirPos == -1)
2518 {
2519 aPath = "..";
2520 }
2521 rRTLData.nCurDirPos++;
2522 }
2523 else if (rRTLData.nCurDirPos >= rRTLData.aDirSeq.getLength())
2524 {
2525 rRTLData.aDirSeq.realloc(0);
2526 aPath.clear();
2527 break;
2528 }
2529 else
2530 {
2531 OUString aFile
2532 = rRTLData.aDirSeq.getConstArray()[rRTLData.nCurDirPos++];
2533
2534 if( bCompatibility )
2535 {
2536 if( !bFolderFlag )
2537 {
2538 bool bFolder = xSFI->isFolder( aFile );
2539 if( bFolder )
2540 {
2541 continue;
2542 }
2543 }
2544 }
2545 else
2546 {
2547 // Only directories
2548 if( bFolderFlag )
2549 {
2550 bool bFolder = xSFI->isFolder( aFile );
2551 if( !bFolder )
2552 {
2553 continue;
2554 }
2555 }
2556 }
2557
2558 INetURLObject aURL( aFile );
2559 aPath = aURL.getName( INetURLObject::LAST_SEGMENT, true,
2560 INetURLObject::DecodeMechanism::WithCharset );
2561 }
2562
2563 bool bMatch = implCheckWildcard(aPath, rRTLData);
2564 if( !bMatch )
2565 {
2566 continue;
2567 }
2568 break;
2569 }
2570 }
2571 rPar.Get(0)->PutString(aPath);
2572 }
2573 }
2574 else
2575 {
2576 // TODO: OSL
2577 if ( nParCount >= 2 )
2578 {
2579 OUString aFileParam = rPar.Get(1)->GetOUString();
2580
2581 OUString aDirURL = implSetupWildcard(aFileParam, rRTLData);
2582
2583 sal_Int16 nFlags = SbAttributes::NORMAL;
2584 if ( nParCount > 2 )
2585 {
2586 rRTLData.nDirFlags = nFlags = rPar.Get(2)->GetInteger();
2587 }
2588 else
2589 {
2590 rRTLData.nDirFlags = SbAttributes::NORMAL;
2591 }
2592
2593 // Read directory
2594 bool bIncludeFolders = bool(nFlags & SbAttributes::DIRECTORY);
2595 rRTLData.pDir = std::make_unique<Directory>(aDirURL);
2596 FileBase::RC nRet = rRTLData.pDir->open();
2597 if( nRet != FileBase::E_None )
2598 {
2599 rRTLData.pDir.reset();
2600 rPar.Get(0)->PutString(OUString());
2601 return;
2602 }
2603
2604 // #86950 Add "." and ".." directories for VB compatibility
2605 rRTLData.nCurDirPos = 0;
2606 if( bIncludeFolders )
2607 {
2608 bool bRoot = isRootDir( aDirURL );
2609
2610 // If it's no root directory we flag the need for
2611 // the "." and ".." directories by the value -2
2612 // for the actual position. Later for -2 will be
2613 // returned "." and for -1 ".."
2614 if( !bRoot )
2615 {
2616 rRTLData.nCurDirPos = -2;
2617 }
2618 }
2619
2620 }
2621
2622 if (rRTLData.pDir)
2623 {
2624 bool bFolderFlag = bool(rRTLData.nDirFlags & SbAttributes::DIRECTORY);
2625 for( ;; )
2626 {
2627 if (rRTLData.nCurDirPos < 0)
2628 {
2629 if (rRTLData.nCurDirPos == -2)
2630 {
2631 aPath = ".";
2632 }
2633 else if (rRTLData.nCurDirPos == -1)
2634 {
2635 aPath = "..";
2636 }
2637 rRTLData.nCurDirPos++;
2638 }
2639 else
2640 {
2641 DirectoryItem aItem;
2642 FileBase::RC nRet = rRTLData.pDir->getNextItem(aItem);
2643 if( nRet != FileBase::E_None )
2644 {
2645 rRTLData.pDir.reset();
2646 aPath.clear();
2647 break;
2648 }
2649
2650 // Handle flags
2651 FileStatus aFileStatus( osl_FileStatus_Mask_Type | osl_FileStatus_Mask_FileName );
2652 nRet = aItem.getFileStatus( aFileStatus );
2653 if( nRet != FileBase::E_None )
2654 {
2655 SAL_WARN("basic", "getFileStatus failed");
2656 continue;
2657 }
2658
2659 // Only directories?
2660 if( bFolderFlag )
2661 {
2662 FileStatus::Type aType = aFileStatus.getFileType();
2663 bool bFolder = isFolder( aType );
2664 if( !bFolder )
2665 {
2666 continue;
2667 }
2668 }
2669
2670 aPath = aFileStatus.getFileName();
2671 }
2672
2673 bool bMatch = implCheckWildcard(aPath, rRTLData);
2674 if( !bMatch )
2675 {
2676 continue;
2677 }
2678 break;
2679 }
2680 }
2681 rPar.Get(0)->PutString(aPath);
2682 }
2683 }
2684
2685
2686 void SbRtl_GetAttr(StarBASIC *, SbxArray & rPar, bool)
2687 {
2688 if (rPar.Count() != 2)
2689 return StarBASIC::Error( ERRCODE_BASIC_BAD_ARGUMENT );
2690 sal_Int16 nFlags = SbAttributes::NORMAL;
2691
2692 // In Windows, we want to use Windows API to get the file attributes
2693 // for VBA interoperability.
2694 #if defined(_WIN32)
2695 if( SbiRuntime::isVBAEnabled() )
2696 {
2697 OUString aPathURL = getFullPath(rPar.Get(1)->GetOUString());
2698 OUString aPath;
2699 FileBase::getSystemPathFromFileURL( aPathURL, aPath );
2700 DWORD nRealFlags = GetFileAttributesW (o3tl::toW(aPath.getStr()));
2701 if (nRealFlags != 0xffffffff)
2702 {
2703 if (nRealFlags == FILE_ATTRIBUTE_NORMAL)
2704 {
2705 nRealFlags = 0;
2706 }
2707 nFlags = static_cast<sal_Int16>(nRealFlags);
2708 }
2709 else
2710 {
2711 StarBASIC::Error( ERRCODE_BASIC_FILE_NOT_FOUND );
2712 }
2713 rPar.Get(0)->PutInteger(nFlags);
2714
2715 return;
2716 }
2717 #endif
2718
2719 if( hasUno() )
2720 {
2721 const uno::Reference< ucb::XSimpleFileAccess3 >& xSFI = getFileAccess();
2722 if( xSFI.is() )
2723 {
2724 try
2725 {
2726 OUString aPath = getFullPath(rPar.Get(1)->GetOUString());
2727 bool bExists = false;
2728 try { bExists = xSFI->exists( aPath ); }
2729 catch(const Exception & ) {}
2730 if( !bExists )
2731 {
2732 return StarBASIC::Error( ERRCODE_BASIC_FILE_NOT_FOUND );
2733 }
2734
2735 bool bReadOnly = xSFI->isReadOnly( aPath );
2736 bool bHidden = xSFI->isHidden( aPath );
2737 bool bDirectory = xSFI->isFolder( aPath );
2738 if( bReadOnly )
2739 {
2740 nFlags |= SbAttributes::READONLY;
2741 }
2742 if( bHidden )
2743 {
2744 nFlags |= SbAttributes::HIDDEN;
2745 }
2746 if( bDirectory )
2747 {
2748 nFlags |= SbAttributes::DIRECTORY;
2749 }
2750 }
2751 catch(const Exception & )
2752 {
2753 StarBASIC::Error( ERRCODE_IO_GENERAL );
2754 }
2755 }
2756 }
2757 else
2758 {
2759 DirectoryItem aItem;
2760 (void)DirectoryItem::get(getFullPath(rPar.Get(1)->GetOUString()), aItem);
2761 FileStatus aFileStatus( osl_FileStatus_Mask_Attributes | osl_FileStatus_Mask_Type );
2762 (void)aItem.getFileStatus( aFileStatus );
2763 sal_uInt64 nAttributes = aFileStatus.getAttributes();
2764 bool bReadOnly = (nAttributes & osl_File_Attribute_ReadOnly) != 0;
2765
2766 FileStatus::Type aType = aFileStatus.getFileType();
2767 bool bDirectory = isFolder( aType );
2768 if( bReadOnly )
2769 {
2770 nFlags |= SbAttributes::READONLY;
2771 }
2772 if( bDirectory )
2773 {
2774 nFlags |= SbAttributes::DIRECTORY;
2775 }
2776 }
2777 rPar.Get(0)->PutInteger(nFlags);
2778 }
2779
2780
2781 void SbRtl_FileDateTime(StarBASIC *, SbxArray & rPar, bool)
2782 {
2783 if (rPar.Count() != 2)
2784 return StarBASIC::Error(ERRCODE_BASIC_BAD_ARGUMENT);
2785
2786 OUString aPath = rPar.Get(1)->GetOUString();
2787 tools::Time aTime( tools::Time::EMPTY );
2788 Date aDate( Date::EMPTY );
2789 if( hasUno() )
2790 {
2791 const uno::Reference< ucb::XSimpleFileAccess3 >& xSFI = getFileAccess();
2792 if( xSFI.is() )
2793 {
2794 try
2795 {
2796 util::DateTime aUnoDT = xSFI->getDateTimeModified( aPath );
2797 aTime = tools::Time( aUnoDT );
2798 aDate = Date( aUnoDT );
2799 }
2800 catch(const Exception & )
2801 {
2802 StarBASIC::Error( ERRCODE_IO_GENERAL );
2803 }
2804 }
2805 }
2806 else
2807 {
2808 bool bSuccess = false;
2809 do
2810 {
2811 DirectoryItem aItem;
2812 if (DirectoryItem::get( getFullPath( aPath ), aItem ) != FileBase::E_None)
2813 break;
2814
2815 FileStatus aFileStatus( osl_FileStatus_Mask_ModifyTime );
2816 if (aItem.getFileStatus( aFileStatus ) != FileBase::E_None)
2817 break;
2818
2819 TimeValue aTimeVal = aFileStatus.getModifyTime();
2820 oslDateTime aDT;
2821 if (!osl_getDateTimeFromTimeValue( &aTimeVal, &aDT ))
2822 // Strictly spoken this is not an i/o error but some other failure.
2823 break;
2824
2825 aTime = tools::Time( aDT.Hours, aDT.Minutes, aDT.Seconds, aDT.NanoSeconds );
2826 aDate = Date( aDT.Day, aDT.Month, aDT.Year );
2827 bSuccess = true;
2828 }
2829 while(false);
2830
2831 if (!bSuccess)
2832 StarBASIC::Error( ERRCODE_IO_GENERAL );
2833 }
2834
2835 // An empty date shall not result in a formatted null-date (1899-12-30
2836 // or 1900-01-01) or even worse -0001-12-03 or some such due to how
2837 // GetDayDiff() treats things. There should be an error set in this
2838 // case anyway because of a missing file or other error above, but... so
2839 // do not even bother to use the number formatter.
2840 OUString aRes;
2841 if (aDate.IsEmpty())
2842 {
2843 aRes = "0000-00-00 00:00:00";
2844 }
2845 else
2846 {
2847 double fSerial = static_cast<double>(GetDayDiff( aDate ));
2848 tools::Long nSeconds = aTime.GetHour();
2849 nSeconds *= 3600;
2850 nSeconds += aTime.GetMin() * 60;
2851 nSeconds += aTime.GetSec();
2852 double nDays = static_cast<double>(nSeconds) / (24.0*3600.0);
2853 fSerial += nDays;
2854
2855 const Color* pCol;
2856
2857 std::shared_ptr<SvNumberFormatter> pFormatter;
2858 sal_uInt32 nIndex;
2859 if( GetSbData()->pInst )
2860 {
2861 pFormatter = GetSbData()->pInst->GetNumberFormatter();
2862 nIndex = GetSbData()->pInst->GetStdDateTimeIdx();
2863 }
2864 else
2865 {
2866 sal_uInt32 n;
2867 pFormatter = SbiInstance::PrepareNumberFormatter( n, n, nIndex );
2868 }
2869
2870 pFormatter->GetOutputString( fSerial, nIndex, aRes, &pCol );
2871 }
2872 rPar.Get(0)->PutString(aRes);
2873 }
2874
2875 void SbRtl_EOF(StarBASIC *, SbxArray & rPar, bool)
2876 {
2877 // No changes for UCB
2878 if (rPar.Count() != 2)
2879 {
2880 StarBASIC::Error( ERRCODE_BASIC_BAD_ARGUMENT );
2881 }
2882 else
2883 {
2884 sal_Int16 nChannel = rPar.Get(1)->GetInteger();
2885 SbiIoSystem* pIO = GetSbData()->pInst->GetIoSystem();
2886 SbiStream* pSbStrm = pIO->GetStream( nChannel );
2887 if ( !pSbStrm )
2888 {
2889 return StarBASIC::Error( ERRCODE_BASIC_BAD_CHANNEL );
2890 }
2891 bool beof;
2892 SvStream* pSvStrm = pSbStrm->GetStrm();
2893 if ( pSbStrm->IsText() )
2894 {
2895 char cBla;
2896 (*pSvStrm).ReadChar( cBla ); // can we read another character?
2897 beof = pSvStrm->eof();
2898 if ( !beof )
2899 {
2900 pSvStrm->SeekRel( -1 );
2901 }
2902 }
2903 else
2904 {
2905 beof = pSvStrm->eof(); // for binary data!
2906 }
2907 rPar.Get(0)->PutBool(beof);
2908 }
2909 }
2910
2911 void SbRtl_FileAttr(StarBASIC *, SbxArray & rPar, bool)
2912 {
2913 // No changes for UCB
2914 // #57064 Although this function doesn't operate with DirEntry, it is
2915 // not touched by the adjustment to virtual URLs, as it only works on
2916 // already opened files and the name doesn't matter there.
2917
2918 if (rPar.Count() != 3)
2919 {
2920 StarBASIC::Error( ERRCODE_BASIC_BAD_ARGUMENT );
2921 }
2922 else
2923 {
2924 sal_Int16 nChannel = rPar.Get(1)->GetInteger();
2925 SbiIoSystem* pIO = GetSbData()->pInst->GetIoSystem();
2926 SbiStream* pSbStrm = pIO->GetStream( nChannel );
2927 if ( !pSbStrm )
2928 {
2929 return StarBASIC::Error( ERRCODE_BASIC_BAD_CHANNEL );
2930 }
2931 sal_Int16 nRet;
2932 if (rPar.Get(2)->GetInteger() == 1)
2933 {
2934 nRet = static_cast<sal_Int16>(pSbStrm->GetMode());
2935 }
2936 else
2937 {
2938 nRet = 0; // System file handle not supported
2939 }
2940 rPar.Get(0)->PutInteger(nRet);
2941 }
2942 }
2943 void SbRtl_Loc(StarBASIC *, SbxArray & rPar, bool)
2944 {
2945 // No changes for UCB
2946 if (rPar.Count() != 2)
2947 {
2948 StarBASIC::Error( ERRCODE_BASIC_BAD_ARGUMENT );
2949 }
2950 else
2951 {
2952 sal_Int16 nChannel = rPar.Get(1)->GetInteger();
2953 SbiIoSystem* pIO = GetSbData()->pInst->GetIoSystem();
2954 SbiStream* pSbStrm = pIO->GetStream( nChannel );
2955 if ( !pSbStrm )
2956 {
2957 return StarBASIC::Error( ERRCODE_BASIC_BAD_CHANNEL );
2958 }
2959 SvStream* pSvStrm = pSbStrm->GetStrm();
2960 std::size_t nPos;
2961 if( pSbStrm->IsRandom())
2962 {
2963 short nBlockLen = pSbStrm->GetBlockLen();
2964 nPos = nBlockLen ? (pSvStrm->Tell() / nBlockLen) : 0;
2965 nPos++; // block positions starting at 1
2966 }
2967 else if ( pSbStrm->IsText() )
2968 {
2969 nPos = pSbStrm->GetLine();
2970 }
2971 else if( pSbStrm->IsBinary() )
2972 {
2973 nPos = pSvStrm->Tell();
2974 }
2975 else if ( pSbStrm->IsSeq() )
2976 {
2977 nPos = ( pSvStrm->Tell()+1 ) / 128;
2978 }
2979 else
2980 {
2981 nPos = pSvStrm->Tell();
2982 }
2983 rPar.Get(0)->PutLong(static_cast<sal_Int32>(nPos));
2984 }
2985 }
2986
2987 void SbRtl_Lof(StarBASIC *, SbxArray & rPar, bool)
2988 {
2989 // No changes for UCB
2990 if (rPar.Count() != 2)
2991 {
2992 StarBASIC::Error( ERRCODE_BASIC_BAD_ARGUMENT );
2993 }
2994 else
2995 {
2996 sal_Int16 nChannel = rPar.Get(1)->GetInteger();
2997 SbiIoSystem* pIO = GetSbData()->pInst->GetIoSystem();
2998 SbiStream* pSbStrm = pIO->GetStream( nChannel );
2999 if ( !pSbStrm )
3000 {
3001 return StarBASIC::Error( ERRCODE_BASIC_BAD_CHANNEL );
3002 }
3003 SvStream* pSvStrm = pSbStrm->GetStrm();
3004 sal_uInt64 const nLen = pSvStrm->TellEnd();
3005 rPar.Get(0)->PutLong(static_cast<sal_Int32>(nLen));
3006 }
3007 }
3008
3009
3010 void SbRtl_Seek(StarBASIC *, SbxArray & rPar, bool)
3011 {
3012 // No changes for UCB
3013 int nArgs = static_cast<int>(rPar.Count());
3014 if ( nArgs < 2 || nArgs > 3 )
3015 {
3016 return StarBASIC::Error( ERRCODE_BASIC_BAD_ARGUMENT );
3017 }
3018 sal_Int16 nChannel = rPar.Get(1)->GetInteger();
3019 SbiIoSystem* pIO = GetSbData()->pInst->GetIoSystem();
3020 SbiStream* pSbStrm = pIO->GetStream( nChannel );
3021 if ( !pSbStrm )
3022 {
3023 return StarBASIC::Error( ERRCODE_BASIC_BAD_CHANNEL );
3024 }
3025 SvStream* pStrm = pSbStrm->GetStrm();
3026
3027 if ( nArgs == 2 ) // Seek-Function
3028 {
3029 sal_uInt64 nPos = pStrm->Tell();
3030 if( pSbStrm->IsRandom() )
3031 {
3032 nPos = nPos / pSbStrm->GetBlockLen();
3033 }
3034 nPos++; // Basic counts from 1
3035 rPar.Get(0)->PutLong(static_cast<sal_Int32>(nPos));
3036 }
3037 else // Seek-Statement
3038 {
3039 sal_Int32 nPos = rPar.Get(2)->GetLong();
3040 if ( nPos < 1 )
3041 {
3042 return StarBASIC::Error( ERRCODE_BASIC_BAD_ARGUMENT );
3043 }
3044 nPos--; // Basic counts from 1, SvStreams count from 0
3045 pSbStrm->SetExpandOnWriteTo( 0 );
3046 if ( pSbStrm->IsRandom() )
3047 {
3048 nPos *= pSbStrm->GetBlockLen();
3049 }
3050 pStrm->Seek( static_cast<sal_uInt64>(nPos) );
3051 pSbStrm->SetExpandOnWriteTo( nPos );
3052 }
3053 }
3054
3055 void SbRtl_Format(StarBASIC *, SbxArray & rPar, bool)
3056 {
3057 const sal_uInt32 nArgCount = rPar.Count();
3058 if ( nArgCount < 2 || nArgCount > 3 )
3059 {
3060 StarBASIC::Error( ERRCODE_BASIC_BAD_ARGUMENT );
3061 }
3062 else
3063 {
3064 OUString aResult;
3065 if( nArgCount == 2 )
3066 {
3067 rPar.Get(1)->Format(aResult);
3068 }
3069 else
3070 {
3071 OUString aFmt(rPar.Get(2)->GetOUString());
3072 rPar.Get(1)->Format(aResult, &aFmt);
3073 }
3074 rPar.Get(0)->PutString(aResult);
3075 }
3076 }
3077
3078 static bool IsMissing(SbxArray& rPar, const sal_uInt32 i)
3079 {
3080 const sal_uInt32 nArgCount = rPar.Count();
3081 if (nArgCount <= i)
3082 return true;
3083
3084 SbxVariable* aPar = rPar.Get(i);
3085 return (aPar->GetType() == SbxERROR && SbiRuntime::IsMissing(aPar, 1));
3086 }
3087
3088 static sal_Int16 GetOptionalIntegerParamOrDefault(SbxArray& rPar, const sal_uInt32 i,
3089 const sal_Int16 defaultValue)
3090 {
3091 return IsMissing(rPar, i) ? defaultValue : rPar.Get(i)->GetInteger();
3092 }
3093
3094 static OUString GetOptionalOUStringParamOrDefault(SbxArray& rPar, const sal_uInt32 i,
3095 const OUString& defaultValue)
3096 {
3097 return IsMissing(rPar, i) ? defaultValue : rPar.Get(i)->GetOUString();
3098 }
3099
3100 static void lcl_FormatNumberPercent(SbxArray& rPar, bool isPercent)
3101 {
3102 const sal_uInt32 nArgCount = rPar.Count();
3103 if (nArgCount < 2 || nArgCount > 6)
3104 {
3105 return StarBASIC::Error(ERRCODE_BASIC_BAD_ARGUMENT);
3106 }
3107
3108 // The UI locale never changes -> we can use static value here
3109 static const LocaleDataWrapper localeData(Application::GetSettings().GetUILanguageTag());
3110 sal_Int16 nNumDigitsAfterDecimal = -1;
3111 if (nArgCount > 2 && !rPar.Get(2)->IsEmpty())
3112 {
3113 nNumDigitsAfterDecimal = rPar.Get(2)->GetInteger();
3114 if (nNumDigitsAfterDecimal < -1)
3115 {
3116 return StarBASIC::Error(ERRCODE_BASIC_BAD_ARGUMENT);
3117 }
3118 else if (nNumDigitsAfterDecimal > 255)
3119 nNumDigitsAfterDecimal %= 256;
3120 }
3121 if (nNumDigitsAfterDecimal == -1)
3122 nNumDigitsAfterDecimal = LocaleDataWrapper::getNumDigits();
3123
3124 bool bIncludeLeadingDigit = LocaleDataWrapper::isNumLeadingZero();
3125 if (nArgCount > 3 && !rPar.Get(3)->IsEmpty())
3126 {
3127 switch (rPar.Get(3)->GetInteger())
3128 {
3129 case ooo::vba::VbTriState::vbFalse:
3130 bIncludeLeadingDigit = false;
3131 break;
3132 case ooo::vba::VbTriState::vbTrue:
3133 bIncludeLeadingDigit = true;
3134 break;
3135 case ooo::vba::VbTriState::vbUseDefault:
3136 // do nothing;
3137 break;
3138 default:
3139 return StarBASIC::Error(ERRCODE_BASIC_BAD_ARGUMENT);
3140 }
3141 }
3142
3143 bool bUseParensForNegativeNumbers = false;
3144 if (nArgCount > 4 && !rPar.Get(4)->IsEmpty())
3145 {
3146 switch (rPar.Get(4)->GetInteger())
3147 {
3148 case ooo::vba::VbTriState::vbFalse:
3149 case ooo::vba::VbTriState::vbUseDefault:
3150 // do nothing
3151 break;
3152 case ooo::vba::VbTriState::vbTrue:
3153 bUseParensForNegativeNumbers = true;
3154 break;
3155 default:
3156 return StarBASIC::Error(ERRCODE_BASIC_BAD_ARGUMENT);
3157 }
3158 }
3159
3160 bool bGroupDigits = false;
3161 if (nArgCount > 5 && !rPar.Get(5)->IsEmpty())
3162 {
3163 switch (rPar.Get(5)->GetInteger())
3164 {
3165 case ooo::vba::VbTriState::vbFalse:
3166 case ooo::vba::VbTriState::vbUseDefault:
3167 // do nothing
3168 break;
3169 case ooo::vba::VbTriState::vbTrue:
3170 bGroupDigits = true;
3171 break;
3172 default:
3173 return StarBASIC::Error(ERRCODE_BASIC_BAD_ARGUMENT);
3174 }
3175 }
3176
3177 double fVal = rPar.Get(1)->GetDouble();
3178 if (isPercent)
3179 fVal *= 100;
3180 const bool bNegative = fVal < 0;
3181 if (bNegative)
3182 fVal = fabs(fVal); // Always work with non-negatives, to easily handle leading zero
3183
3184 static const sal_Unicode decSep = localeData.getNumDecimalSep().toChar();
3185 OUStringBuffer aResult;
3186 rtl::math::doubleToUStringBuffer(aResult,
3187 fVal, rtl_math_StringFormat_F, nNumDigitsAfterDecimal, decSep,
3188 bGroupDigits ? localeData.getDigitGrouping().getConstArray() : nullptr,
3189 localeData.getNumThousandSep().toChar());
3190
3191 if (!bIncludeLeadingDigit && aResult.getLength() > 1)
3192 aResult.stripStart('0');
3193
3194 if (nNumDigitsAfterDecimal > 0)
3195 {
3196 const sal_Int32 nSepPos = aResult.indexOf(decSep);
3197
3198 // VBA allows up to 255 digits; rtl::math::doubleToUString outputs up to 15 digits
3199 // for ~small numbers, so pad them as appropriate.
3200 if (nSepPos >= 0)
3201 comphelper::string::padToLength(aResult, nSepPos + nNumDigitsAfterDecimal + 1, '0');
3202 }
3203
3204 if (bNegative)
3205 {
3206 if (bUseParensForNegativeNumbers)
3207 aResult.insert(0, '(').append(')');
3208 else
3209 aResult.insert(0, '-');
3210 }
3211 if (isPercent)
3212 aResult.append('%');
3213 rPar.Get(0)->PutString(aResult.makeStringAndClear());
3214 }
3215
3216 // https://docs.microsoft.com/en-us/office/vba/Language/Reference/User-Interface-Help/formatnumber-function
3217 void SbRtl_FormatNumber(StarBASIC*, SbxArray& rPar, bool)
3218 {
3219 return lcl_FormatNumberPercent(rPar, false);
3220 }
3221
3222 // https://docs.microsoft.com/en-us/office/vba/Language/Reference/User-Interface-Help/formatpercent-function
3223 void SbRtl_FormatPercent(StarBASIC*, SbxArray& rPar, bool)
3224 {
3225 return lcl_FormatNumberPercent(rPar, true);
3226 }
3227
3228 namespace {
3229
3230 // note: BASIC does not use comphelper::random, because
3231 // Randomize(int) must be supported and should not affect non-BASIC random use
3232 struct RandomNumberGenerator
3233 {
3234 std::mt19937 global_rng;
3235
3236 RandomNumberGenerator()
3237 {
3238 try
3239 {
3240 std::random_device rd;
3241 // initialises the state of the global random number generator
3242 // should only be called once.
3243 // (note, a few std::variate_generator<> (like normal) have their
3244 // own state which would need a reset as well to guarantee identical
3245 // sequence of numbers, e.g. via myrand.distribution().reset())
3246 global_rng.seed(rd() ^ time(nullptr));
3247 }
3248 catch (std::runtime_error& e)
3249 {
3250 SAL_WARN("basic", "Using std::random_device failed: " << e.what());
3251 global_rng.seed(time(nullptr));
3252 }
3253 }
3254 };
3255
3256 RandomNumberGenerator& theRandomNumberGenerator()
3257 {
3258 static RandomNumberGenerator theGenerator;
3259 return theGenerator;
3260 }
3261
3262 }
3263
3264 void SbRtl_Randomize(StarBASIC *, SbxArray & rPar, bool)
3265 {
3266 if (rPar.Count() > 2)
3267 {
3268 StarBASIC::Error( ERRCODE_BASIC_BAD_ARGUMENT );
3269 }
3270 if (rPar.Count() == 2)
3271 {
3272 int nSeed = static_cast<int>(rPar.Get(1)->GetInteger());
3273 theRandomNumberGenerator().global_rng.seed(nSeed);
3274 }
3275 // without parameter, no need to do anything - RNG is seeded at first use
3276 }
3277
3278 void SbRtl_Rnd(StarBASIC *, SbxArray & rPar, bool)
3279 {
3280 if (rPar.Count() > 2)
3281 return StarBASIC::Error( ERRCODE_BASIC_BAD_ARGUMENT );
3282
3283 std::uniform_real_distribution<double> dist(0.0, 1.0);
3284 double const tmp(dist(theRandomNumberGenerator().global_rng));
3285 rPar.Get(0)->PutDouble(tmp);
3286 }
3287
3288
3289 // Syntax: Shell("Path",[ Window-Style,[ "Params", [ bSync = sal_False ]]])
3290 // WindowStyles (VBA compatible):
3291 // 2 == Minimized
3292 // 3 == Maximized
3293 // 10 == Full-Screen (text mode applications OS/2, WIN95, WNT)
3294 // HACK: The WindowStyle will be passed to
3295 // Application::StartApp in Creator. Format: "xxxx2"
3296
3297
3298 void SbRtl_Shell(StarBASIC *, SbxArray & rPar, bool)
3299 {
3300 const sal_uInt32 nArgCount = rPar.Count();
3301 if ( nArgCount < 2 || nArgCount > 5 )
3302 {
3303 rPar.Get(0)->PutLong(0);
3304 StarBASIC::Error( ERRCODE_BASIC_BAD_ARGUMENT );
3305 }
3306 else
3307 {
3308 // Just go straight to error in this case
3309 if (comphelper::LibreOfficeKit::isActive())
3310 {
3311 StarBASIC::Error(ERRCODE_BASIC_FILE_NOT_FOUND);
3312 return;
3313 }
3314
3315 oslProcessOption nOptions = osl_Process_SEARCHPATH | osl_Process_DETACHED;
3316
3317 OUString aCmdLine = rPar.Get(1)->GetOUString();
3318 // attach additional parameters - everything must be parsed anyway
3319 if( nArgCount >= 4 )
3320 {
3321 OUString tmp = rPar.Get(3)->GetOUString().trim();
3322 if (!tmp.isEmpty())
3323 {
3324 aCmdLine += " " + tmp;
3325 }
3326 }
3327 sal_Int32 nLen = aCmdLine.getLength();
3328
3329 // #55735 if there are parameters, they have to be separated
3330 // #72471 also separate the single parameters
3331 std::vector<OUString> aTokenVector;
3332 for (sal_Int32 i = 0; i < nLen;)
3333 {
3334 sal_Unicode c = aCmdLine[i];
3335 if (c == ' ' || c == '\t')
3336 {
3337 ++i;
3338 continue;
3339 }
3340
3341 OUString aToken;
3342 if( c == '\"' || c == '\'' )
3343 {
3344 sal_Int32 iFoundPos = aCmdLine.indexOf( c, i + 1 );
3345
3346 if( iFoundPos < 0 )
3347 {
3348 aToken = aCmdLine.copy( i);
3349 i = nLen;
3350 }
3351 else
3352 {
3353 aToken = aCmdLine.copy( i + 1, (iFoundPos - i - 1) );
3354 i = iFoundPos + 1;
3355 }
3356 }
3357 else
3358 {
3359 sal_Int32 iFoundSpacePos = aCmdLine.indexOf( ' ', i );
3360 sal_Int32 iFoundTabPos = aCmdLine.indexOf( '\t', i );
3361 sal_Int32 iFoundPos = iFoundSpacePos >= 0 ? iFoundTabPos >= 0 ? std::min( iFoundSpacePos, iFoundTabPos ) : iFoundSpacePos : -1;
3362
3363 if( iFoundPos < 0 )
3364 {
3365 aToken = aCmdLine.copy( i );
3366 i = nLen;
3367 }
3368 else
3369 {
3370 aToken = aCmdLine.copy( i, (iFoundPos - i) );
3371 i = iFoundPos;
3372 }
3373 }
3374
3375 // insert into the list
3376 aTokenVector.push_back( aToken );
3377 }
3378 // #55735 / #72471 end
3379
3380 if (aTokenVector.empty())
3381 return StarBASIC::Error(ERRCODE_BASIC_BAD_ARGUMENT);
3382
3383 sal_Int16 nWinStyle = 0;
3384 if( nArgCount >= 3 )
3385 {
3386 nWinStyle = rPar.Get(2)->GetInteger();
3387 switch( nWinStyle )
3388 {
3389 case 2:
3390 nOptions |= osl_Process_MINIMIZED;
3391 break;
3392 case 3:
3393 nOptions |= osl_Process_MAXIMIZED;
3394 break;
3395 case 10:
3396 nOptions |= osl_Process_FULLSCREEN;
3397 break;
3398 }
3399
3400 bool bSync = false;
3401 if( nArgCount >= 5 )
3402 {
3403 bSync = rPar.Get(4)->GetBool();
3404 }
3405 if( bSync )
3406 {
3407 nOptions |= osl_Process_WAIT;
3408 }
3409 }
3410
3411 // #72471 work parameter(s) up
3412 std::vector<OUString>::const_iterator iter = aTokenVector.begin();
3413 OUString aOUStrProgURL = getFullPath( *iter );
3414
3415 ++iter;
3416
3417 sal_uInt16 nParamCount = sal::static_int_cast< sal_uInt16 >(aTokenVector.size() - 1 );
3418 std::unique_ptr<rtl_uString*[]> pParamList;
3419 if( nParamCount )
3420 {
3421 pParamList.reset( new rtl_uString*[nParamCount]);
3422 for(int iVector = 0; iter != aTokenVector.end(); ++iVector, ++iter)
3423 {
3424 const OUString& rParamStr = *iter;
3425 pParamList[iVector] = nullptr;
3426 rtl_uString_assign(&(pParamList[iVector]), rParamStr.pData);
3427 }
3428 }
3429
3430 oslProcess pApp;
3431 bool bSucc = osl_executeProcess(
3432 aOUStrProgURL.pData,
3433 pParamList.get(),
3434 nParamCount,
3435 nOptions,
3436 nullptr,
3437 nullptr,
3438 nullptr, 0,
3439 &pApp ) == osl_Process_E_None;
3440
3441 // 53521 only free process handle on success
3442 if (bSucc)
3443 {
3444 osl_freeProcessHandle( pApp );
3445 }
3446
3447 for(int j = 0; j < nParamCount; ++j)
3448 {
3449 rtl_uString_release(pParamList[j]);
3450 }
3451
3452 if( !bSucc )
3453 {
3454 StarBASIC::Error( ERRCODE_BASIC_FILE_NOT_FOUND );
3455 }
3456 else
3457 {
3458 rPar.Get(0)->PutLong(0);
3459 }
3460 }
3461 }
3462
3463 void SbRtl_VarType(StarBASIC *, SbxArray & rPar, bool)
3464 {
3465 if (rPar.Count() != 2)
3466 {
3467 StarBASIC::Error( ERRCODE_BASIC_BAD_ARGUMENT );
3468 }
3469 else
3470 {
3471 SbxDataType eType = rPar.Get(1)->GetType();
3472 rPar.Get(0)->PutInteger(static_cast<sal_Int16>(eType));
3473 }
3474 }
3475
3476 // Exported function
3477 const OUString & getBasicTypeName( SbxDataType eType )
3478 {
3479 static constexpr OUString pTypeNames[] =
3480 {
3481 u"Empty"_ustr, // SbxEMPTY
3482 u"Null"_ustr, // SbxNULL
3483 u"Integer"_ustr, // SbxINTEGER
3484 u"Long"_ustr, // SbxLONG
3485 u"Single"_ustr, // SbxSINGLE
3486 u"Double"_ustr, // SbxDOUBLE
3487 u"Currency"_ustr, // SbxCURRENCY
3488 u"Date"_ustr, // SbxDATE
3489 u"String"_ustr, // SbxSTRING
3490 u"Object"_ustr, // SbxOBJECT
3491 u"Error"_ustr, // SbxERROR
3492 u"Boolean"_ustr, // SbxBOOL
3493 u"Variant"_ustr, // SbxVARIANT
3494 u"DataObject"_ustr, // SbxDATAOBJECT
3495 u"Unknown Type"_ustr,
3496 u"Unknown Type"_ustr,
3497 u"Char"_ustr, // SbxCHAR
3498 u"Byte"_ustr, // SbxBYTE
3499 u"UShort"_ustr, // SbxUSHORT
3500 u"ULong"_ustr, // SbxULONG
3501 u"Long64"_ustr, // SbxLONG64
3502 u"ULong64"_ustr, // SbxULONG64
3503 u"Int"_ustr, // SbxINT
3504 u"UInt"_ustr, // SbxUINT
3505 u"Void"_ustr, // SbxVOID
3506 u"HResult"_ustr, // SbxHRESULT
3507 u"Pointer"_ustr, // SbxPOINTER
3508 u"DimArray"_ustr, // SbxDIMARRAY
3509 u"CArray"_ustr, // SbxCARRAY
3510 u"Userdef"_ustr, // SbxUSERDEF
3511 u"Lpstr"_ustr, // SbxLPSTR
3512 u"Lpwstr"_ustr, // SbxLPWSTR
3513 u"Unknown Type"_ustr, // SbxCoreSTRING
3514 u"WString"_ustr, // SbxWSTRING
3515 u"WChar"_ustr, // SbxWCHAR
3516 u"Int64"_ustr, // SbxSALINT64
3517 u"UInt64"_ustr, // SbxSALUINT64
3518 u"Decimal"_ustr, // SbxDECIMAL
3519 };
3520
3521 size_t nPos = static_cast<size_t>(eType) & 0x0FFF;
3522 const size_t nTypeNameCount = std::size( pTypeNames );
3523 if ( nPos >= nTypeNameCount )
3524 {
3525 nPos = nTypeNameCount - 1;
3526 }
3527 return pTypeNames[nPos];
3528 }
3529
3530 static OUString getObjectTypeName( SbxVariable* pVar )
3531 {
3532 OUString sRet( u"Object"_ustr );
3533 if ( pVar )
3534 {
3535 SbxBase* pBaseObj = pVar->GetObject();
3536 if( !pBaseObj )
3537 {
3538 sRet = "Nothing";
3539 }
3540 else
3541 {
3542 SbUnoObject* pUnoObj = dynamic_cast<SbUnoObject*>( pVar );
3543 if ( !pUnoObj )
3544 {
3545 pUnoObj = dynamic_cast<SbUnoObject*>( pBaseObj );
3546 }
3547 if ( pUnoObj )
3548 {
3549 Any aObj = pUnoObj->getUnoAny();
3550 // For upstreaming unless we start to build oovbaapi by default
3551 // we need to get detect the vba-ness of the object in some
3552 // other way
3553 // note: Automation objects do not support XServiceInfo
3554 uno::Reference< XServiceInfo > xServInfo( aObj, uno::UNO_QUERY );
3555 if ( xServInfo.is() )
3556 {
3557 // is this a VBA object ?
3558 Sequence< OUString > sServices = xServInfo->getSupportedServiceNames();
3559 if ( sServices.hasElements() )
3560 {
3561 sRet = sServices[ 0 ];
3562 }
3563 }
3564 else
3565 {
3566 uno::Reference< bridge::oleautomation::XAutomationObject > xAutoMation( aObj, uno::UNO_QUERY );
3567 if ( xAutoMation.is() )
3568 {
3569 uno::Reference< script::XInvocation > xInv( aObj, uno::UNO_QUERY );
3570 if ( xInv.is() )
3571 {
3572 try
3573 {
3574 xInv->getValue( u"$GetTypeName"_ustr ) >>= sRet;
3575 }
3576 catch(const Exception& )
3577 {
3578 }
3579 }
3580 }
3581 }
3582 sal_Int32 nDot = sRet.lastIndexOf( '.' );
3583 if ( nDot != -1 && nDot < sRet.getLength() )
3584 {
3585 sRet = sRet.copy( nDot + 1 );
3586 }
3587 }
3588 }
3589 }
3590 return sRet;
3591 }
3592
3593 void SbRtl_TypeName(StarBASIC *, SbxArray & rPar, bool)
3594 {
3595 if (rPar.Count() != 2)
3596 {
3597 StarBASIC::Error( ERRCODE_BASIC_BAD_ARGUMENT );
3598 }
3599 else
3600 {
3601 SbxDataType eType = rPar.Get(1)->GetType();
3602 bool bIsArray = ( ( eType & SbxARRAY ) != 0 );
3603
3604 OUString aRetStr;
3605 if ( SbiRuntime::isVBAEnabled() && eType == SbxOBJECT )
3606 {
3607 aRetStr = getObjectTypeName(rPar.Get(1));
3608 }
3609 else
3610 {
3611 aRetStr = getBasicTypeName( eType );
3612 }
3613 if( bIsArray )
3614 {
3615 aRetStr += "()";
3616 }
3617 rPar.Get(0)->PutString(aRetStr);
3618 }
3619 }
3620
3621 void SbRtl_Len(StarBASIC *, SbxArray & rPar, bool)
3622 {
3623 if (rPar.Count() != 2)
3624 return StarBASIC::Error( ERRCODE_BASIC_BAD_ARGUMENT );
3625 const OUString aStr = rPar.Get(1)->GetOUString();
3626 rPar.Get(0)->PutLong(aStr.getLength());
3627 }
3628
3629 void SbRtl_DDEInitiate(StarBASIC *, SbxArray & rPar, bool)
3630 {
3631 int nArgs = static_cast<int>(rPar.Count());
3632 if ( nArgs != 3 )
3633 {
3634 return StarBASIC::Error( ERRCODE_BASIC_BAD_ARGUMENT );
3635 }
3636 const OUString aApp = rPar.Get(1)->GetOUString();
3637 const OUString aTopic = rPar.Get(2)->GetOUString();
3638
3639 SbiDdeControl* pDDE = GetSbData()->pInst->GetDdeControl();
3640 size_t nChannel;
3641 ErrCode nDdeErr = pDDE->Initiate( aApp, aTopic, nChannel );
3642 if( nDdeErr )
3643 {
3644 StarBASIC::Error( nDdeErr );
3645 }
3646 else
3647 {
3648 rPar.Get(0)->PutInteger(static_cast<sal_Int16>(nChannel));
3649 }
3650 }
3651
3652 void SbRtl_DDETerminate(StarBASIC *, SbxArray & rPar, bool)
3653 {
3654 rPar.Get(0)->PutEmpty();
3655 int nArgs = static_cast<int>(rPar.Count());
3656 if ( nArgs != 2 )
3657 {
3658 StarBASIC::Error( ERRCODE_BASIC_BAD_ARGUMENT );
3659 return;
3660 }
3661 size_t nChannel = rPar.Get(1)->GetInteger();
3662 SbiDdeControl* pDDE = GetSbData()->pInst->GetDdeControl();
3663 ErrCode nDdeErr = pDDE->Terminate( nChannel );
3664 if( nDdeErr )
3665 {
3666 StarBASIC::Error( nDdeErr );
3667 }
3668 }
3669
3670 void SbRtl_DDETerminateAll(StarBASIC *, SbxArray & rPar, bool)
3671 {
3672 rPar.Get(0)->PutEmpty();
3673 int nArgs = static_cast<int>(rPar.Count());
3674 if ( nArgs != 1 )
3675 {
3676 return StarBASIC::Error( ERRCODE_BASIC_BAD_ARGUMENT );
3677 }
3678
3679 SbiDdeControl* pDDE = GetSbData()->pInst->GetDdeControl();
3680 ErrCode nDdeErr = pDDE->TerminateAll();
3681 if( nDdeErr )
3682 {
3683 StarBASIC::Error( nDdeErr );
3684 }
3685 }
3686
3687 void SbRtl_DDERequest(StarBASIC *, SbxArray & rPar, bool)
3688 {
3689 int nArgs = static_cast<int>(rPar.Count());
3690 if ( nArgs != 3 )
3691 {
3692 return StarBASIC::Error( ERRCODE_BASIC_BAD_ARGUMENT );
3693 }
3694 size_t nChannel = rPar.Get(1)->GetInteger();
3695 const OUString aItem = rPar.Get(2)->GetOUString();
3696 SbiDdeControl* pDDE = GetSbData()->pInst->GetDdeControl();
3697 OUString aResult;
3698 ErrCode nDdeErr = pDDE->Request( nChannel, aItem, aResult );
3699 if( nDdeErr )
3700 {
3701 StarBASIC::Error( nDdeErr );
3702 }
3703 else
3704 {
3705 rPar.Get(0)->PutString(aResult);
3706 }
3707 }
3708
3709 void SbRtl_DDEExecute(StarBASIC *, SbxArray & rPar, bool)
3710 {
3711 rPar.Get(0)->PutEmpty();
3712 int nArgs = static_cast<int>(rPar.Count());
3713 if ( nArgs != 3 )
3714 {
3715 return StarBASIC::Error( ERRCODE_BASIC_BAD_ARGUMENT );
3716 }
3717 size_t nChannel = rPar.Get(1)->GetInteger();
3718 const OUString aCommand = rPar.Get(2)->GetOUString();
3719 SbiDdeControl* pDDE = GetSbData()->pInst->GetDdeControl();
3720 ErrCode nDdeErr = pDDE->Execute( nChannel, aCommand );
3721 if( nDdeErr )
3722 {
3723 StarBASIC::Error( nDdeErr );
3724 }
3725 }
3726
3727 void SbRtl_DDEPoke(StarBASIC *, SbxArray & rPar, bool)
3728 {
3729 rPar.Get(0)->PutEmpty();
3730 int nArgs = static_cast<int>(rPar.Count());
3731 if ( nArgs != 4 )
3732 {
3733 return StarBASIC::Error( ERRCODE_BASIC_BAD_ARGUMENT );
3734 }
3735 size_t nChannel = rPar.Get(1)->GetInteger();
3736 const OUString aItem = rPar.Get(2)->GetOUString();
3737 const OUString aData = rPar.Get(3)->GetOUString();
3738 SbiDdeControl* pDDE = GetSbData()->pInst->GetDdeControl();
3739 ErrCode nDdeErr = pDDE->Poke( nChannel, aItem, aData );
3740 if( nDdeErr )
3741 {
3742 StarBASIC::Error( nDdeErr );
3743 }
3744 }
3745
3746
3747 void SbRtl_FreeFile(StarBASIC *, SbxArray & rPar, bool)
3748 {
3749 if (rPar.Count() != 1)
3750 {
3751 return StarBASIC::Error( ERRCODE_BASIC_BAD_ARGUMENT );
3752 }
3753 SbiIoSystem* pIO = GetSbData()->pInst->GetIoSystem();
3754 short nChannel = 1;
3755 while( nChannel < CHANNELS )
3756 {
3757 SbiStream* pStrm = pIO->GetStream( nChannel );
3758 if( !pStrm )
3759 {
3760 rPar.Get(0)->PutInteger(nChannel);
3761 return;
3762 }
3763 nChannel++;
3764 }
3765 StarBASIC::Error( ERRCODE_BASIC_TOO_MANY_FILES );
3766 }
3767
3768 void SbRtl_LBound(StarBASIC *, SbxArray & rPar, bool)
3769 {
3770 const sal_uInt32 nParCount = rPar.Count();
3771 if ( nParCount != 3 && nParCount != 2 )
3772 return StarBASIC::Error( ERRCODE_BASIC_BAD_ARGUMENT );
3773
3774 SbxBase* pParObj = rPar.Get(1)->GetObject();
3775 SbxDimArray* pArr = dynamic_cast<SbxDimArray*>( pParObj );
3776 if( !pArr )
3777 return StarBASIC::Error( ERRCODE_BASIC_MUST_HAVE_DIMS );
3778
3779 sal_Int32 nLower, nUpper;
3780 short nDim = (nParCount == 3) ? static_cast<short>(rPar.Get(2)->GetInteger()) : 1;
3781 if (!pArr->GetDim(nDim, nLower, nUpper))
3782 return StarBASIC::Error( ERRCODE_BASIC_OUT_OF_RANGE );
3783 rPar.Get(0)->PutLong(nLower);
3784 }
3785
3786 void SbRtl_UBound(StarBASIC *, SbxArray & rPar, bool)
3787 {
3788 const sal_uInt32 nParCount = rPar.Count();
3789 if ( nParCount != 3 && nParCount != 2 )
3790 return StarBASIC::Error( ERRCODE_BASIC_BAD_ARGUMENT );
3791
3792 SbxBase* pParObj = rPar.Get(1)->GetObject();
3793 SbxDimArray* pArr = dynamic_cast<SbxDimArray*>( pParObj );
3794 if( !pArr )
3795 return StarBASIC::Error( ERRCODE_BASIC_MUST_HAVE_DIMS );
3796
3797 sal_Int32 nLower, nUpper;
3798 short nDim = (nParCount == 3) ? static_cast<short>(rPar.Get(2)->GetInteger()) : 1;
3799 if (!pArr->GetDim(nDim, nLower, nUpper))
3800 return StarBASIC::Error( ERRCODE_BASIC_OUT_OF_RANGE );
3801 rPar.Get(0)->PutLong(nUpper);
3802 }
3803
3804 void SbRtl_RGB(StarBASIC *, SbxArray & rPar, bool)
3805 {
3806 if (rPar.Count() != 4)
3807 return StarBASIC::Error( ERRCODE_BASIC_BAD_ARGUMENT );
3808
3809 sal_Int32 nRed = rPar.Get(1)->GetInteger() & 0xFF;
3810 sal_Int32 nGreen = rPar.Get(2)->GetInteger() & 0xFF;
3811 sal_Int32 nBlue = rPar.Get(3)->GetInteger() & 0xFF;
3812 sal_Int32 nRGB;
3813
3814 SbiInstance* pInst = GetSbData()->pInst;
3815 bool bCompatibility = ( pInst && pInst->IsCompatibility() );
3816 // See discussion in tdf#145725, here's the quotation from a link indicated in the bugtracker
3817 // which explains why we need to manage RGB differently according to VB compatibility
3818 // "In other words, the individual color components are stored in the opposite order one would expect.
3819 // VB stores the red color component in the low-order byte of the long integer's low-order word,
3820 // the green color in the high-order byte of the low-order word, and the blue color in the low-order byte of the high-order word"
3821 if( bCompatibility )
3822 {
3823 nRGB = (nBlue << 16) | (nGreen << 8) | nRed;
3824 }
3825 else
3826 {
3827 nRGB = (nRed << 16) | (nGreen << 8) | nBlue;
3828 }
3829 rPar.Get(0)->PutLong(nRGB);
3830 }
3831
3832 void SbRtl_QBColor(StarBASIC *, SbxArray & rPar, bool)
3833 {
3834 static const sal_Int32 pRGB[] =
3835 {
3836 0x000000,
3837 0x800000,
3838 0x008000,
3839 0x808000,
3840 0x000080,
3841 0x800080,
3842 0x008080,
3843 0xC0C0C0,
3844 0x808080,
3845 0xFF0000,
3846 0x00FF00,
3847 0xFFFF00,
3848 0x0000FF,
3849 0xFF00FF,
3850 0x00FFFF,
3851 0xFFFFFF,
3852 };
3853
3854 if (rPar.Count() != 2)
3855 {
3856 return StarBASIC::Error( ERRCODE_BASIC_BAD_ARGUMENT );
3857 }
3858
3859 sal_Int16 nCol = rPar.Get(1)->GetInteger();
3860 if( nCol < 0 || nCol > 15 )
3861 {
3862 return StarBASIC::Error( ERRCODE_BASIC_BAD_ARGUMENT );
3863 }
3864 sal_Int32 nRGB = pRGB[ nCol ];
3865 rPar.Get(0)->PutLong(nRGB);
3866 }
3867
3868 static std::vector<sal_uInt8> byteArray2Vec(SbxArray* pArr)
3869 {
3870 std::vector<sal_uInt8> result;
3871 if (pArr)
3872 {
3873 const sal_uInt32 nCount = pArr->Count();
3874 result.reserve(nCount + 1); // to avoid reallocation when padding in vbFromUnicode
3875 for (sal_uInt32 i = 0; i < nCount; i++)
3876 result.push_back(pArr->Get(i)->GetByte());
3877 }
3878 return result;
3879 }
3880
3881 // Makes sure to get the byte array if passed, or the string converted to the bytes using
3882 // StringToByteArray in basic/source/sbx/sbxstr.cxx
3883 static std::vector<sal_uInt8> getByteArray(const SbxValue& val)
3884 {
3885 if (val.GetFullType() == SbxOBJECT)
3886 if (auto pObj = val.GetObject())
3887 if (pObj->GetType() == (SbxARRAY | SbxBYTE))
3888 if (auto pArr = dynamic_cast<SbxArray*>(pObj))
3889 return byteArray2Vec(pArr);
3890
3891 // Convert to string
3892 tools::SvRef<SbxValue> pStringValue(new SbxValue(SbxSTRING));
3893 *pStringValue = val;
3894
3895 // Convert string to byte array
3896 tools::SvRef<SbxValue> pValue(new SbxValue(SbxOBJECT));
3897 pValue->PutObject(new SbxArray(SbxBYTE));
3898 *pValue = *pStringValue; // Does the magic of conversion of strings to byte arrays
3899 return byteArray2Vec(dynamic_cast<SbxArray*>(pValue->GetObject()));
3900 }
3901
3902 // StrConv(string, conversion, LCID)
3903 void SbRtl_StrConv(StarBASIC *, SbxArray & rPar, bool)
3904 {
3905 const sal_uInt32 nArgCount = rPar.Count() - 1;
3906 if( nArgCount < 2 || nArgCount > 3 )
3907 {
3908 return StarBASIC::Error( ERRCODE_BASIC_BAD_ARGUMENT );
3909 }
3910
3911 sal_Int32 nConversion = rPar.Get(2)->GetLong();
3912 LanguageType nLanguage = LANGUAGE_SYSTEM;
3913 if (nArgCount == 3)
3914 {
3915 sal_Int32 lcid = rPar.Get(3)->GetLong();
3916 nLanguage = LanguageType(lcid);
3917 }
3918
3919 if (nConversion == ooo::vba::VbStrConv::vbUnicode) // This mode does not combine
3920 {
3921 // Assume that the passed byte array is encoded in the defined encoding, convert to
3922 // UTF-16 and store as string. Passed strings are converted to byte array first.
3923 auto inArray = getByteArray(*rPar.Get(1));
3924 std::string_view s(reinterpret_cast<char*>(inArray.data()), inArray.size() / sizeof(char));
3925 const auto encoding = utl_getWinTextEncodingFromLangStr(LanguageTag(nLanguage).getBcp47());
3926 OUString aOUStr = OStringToOUString(s, encoding);
3927 rPar.Get(0)->PutString(aOUStr);
3928 return;
3929 }
3930
3931 if (nConversion == ooo::vba::VbStrConv::vbFromUnicode) // This mode does not combine
3932 {
3933 // Assume that the passed byte array is UTF-16-encoded (system-endian), convert to specified
3934 // encoding and store as byte array. Passed strings are converted to byte array first.
3935 auto inArray = getByteArray(*rPar.Get(1));
3936 while (inArray.size() % sizeof(sal_Unicode))
3937 inArray.push_back('\0');
3938 std::u16string_view s(reinterpret_cast<sal_Unicode*>(inArray.data()),
3939 inArray.size() / sizeof(sal_Unicode));
3940 const auto encoding = utl_getWinTextEncodingFromLangStr(LanguageTag(nLanguage).getBcp47());
3941 OString aOStr = OUStringToOString(s, encoding);
3942 const sal_Int32 lb = IsBaseIndexOne() ? 1 : 0;
3943 const sal_Int32 ub = lb + aOStr.getLength() - 1;
3944 SbxDimArray* pArray = new SbxDimArray(SbxBYTE);
3945 pArray->unoAddDim(lb, ub);
3946
3947 for (sal_Int32 i = 0; i < aOStr.getLength(); ++i)
3948 {
3949 SbxVariable* pNew = new SbxVariable(SbxBYTE);
3950 pNew->PutByte(aOStr[i]);
3951 pArray->Put(pNew, i);
3952 }
3953
3954 SbxVariable* retVar = rPar.Get(0);
3955 SbxFlagBits nFlags = retVar->GetFlags();
3956 retVar->ResetFlag(SbxFlagBits::Fixed);
3957 retVar->PutObject(pArray);
3958 retVar->SetFlags(nFlags);
3959 retVar->SetParameters(nullptr);
3960 return;
3961 }
3962
3963 std::vector<TransliterationFlags> aTranslitSet;
3964 auto check = [&nConversion, &aTranslitSet](sal_Int32 conv, TransliterationFlags flag)
3965 {
3966 if ((nConversion & conv) != conv)
3967 return false;
3968
3969 aTranslitSet.push_back(flag);
3970 nConversion &= ~conv;
3971 return true;
3972 };
3973
3974 // Check mutually exclusive bits together
3975
3976 if (!check(ooo::vba::VbStrConv::vbProperCase, TransliterationFlags::TITLE_CASE))
3977 if (!check(ooo::vba::VbStrConv::vbUpperCase, TransliterationFlags::LOWERCASE_UPPERCASE))
3978 check(ooo::vba::VbStrConv::vbLowerCase, TransliterationFlags::UPPERCASE_LOWERCASE);
3979
3980 if (!check(ooo::vba::VbStrConv::vbWide, TransliterationFlags::HALFWIDTH_FULLWIDTH))
3981 check(ooo::vba::VbStrConv::vbNarrow, TransliterationFlags::FULLWIDTH_HALFWIDTH);
3982
3983 if (!check(ooo::vba::VbStrConv::vbKatakana, TransliterationFlags::HIRAGANA_KATAKANA))
3984 check(ooo::vba::VbStrConv::vbHiragana, TransliterationFlags::KATAKANA_HIRAGANA);
3985
3986 if (nConversion) // unknown / incorrectly combined bits
3987 return StarBASIC::Error(ERRCODE_BASIC_BAD_ARGUMENT);
3988
3989 OUString aStr = rPar.Get(1)->GetOUString();
3990 if (!aStr.isEmpty() && !aTranslitSet.empty())
3991 {
3992 const uno::Reference< uno::XComponentContext >& xContext = getProcessComponentContext();
3993
3994 for (auto transliterationFlag : aTranslitSet)
3995 {
3996 if (transliterationFlag == TransliterationFlags::TITLE_CASE)
3997 {
3998 // TransliterationWrapper only handles the first character of the passed string
3999 // when handling TITLE_CASE; see Transliteration_titlecase::transliterateImpl in
4000 // i18npool/source/transliteration/transliteration_body.cxx
4001 CharClass aCharClass{ xContext, LanguageTag(nLanguage) };
4002 aStr = aCharClass.titlecase(aCharClass.lowercase(aStr));
4003 }
4004 else
4005 {
4006 utl::TransliterationWrapper aWrapper(xContext, transliterationFlag);
4007 aStr = aWrapper.transliterate(aStr, nLanguage, 0, aStr.getLength(), nullptr);
4008 }
4009 }
4010 }
4011
4012 rPar.Get(0)->PutString(aStr);
4013 }
4014
4015
4016 void SbRtl_Beep(StarBASIC *, SbxArray & rPar, bool)
4017 {
4018 if (rPar.Count() != 1)
4019 {
4020 return StarBASIC::Error( ERRCODE_BASIC_BAD_ARGUMENT );
4021 }
4022 Sound::Beep();
4023 }
4024
4025 void SbRtl_Load(StarBASIC *, SbxArray & rPar, bool)
4026 {
4027 if (rPar.Count() != 2)
4028 {
4029 return StarBASIC::Error( ERRCODE_BASIC_BAD_ARGUMENT );
4030 }
4031
4032
4033 SbxBase* pObj = rPar.Get(1)->GetObject();
4034 if ( !pObj )
4035 return;
4036
4037 if (SbUserFormModule* pModule = dynamic_cast<SbUserFormModule*>(pObj))
4038 {
4039 pModule->Load();
4040 }
4041 else if (SbxObject* pSbxObj = dynamic_cast<SbxObject*>(pObj))
4042 {
4043 SbxVariable* pVar = pSbxObj->Find(u"Load"_ustr, SbxClassType::Method);
4044 if( pVar )
4045 {
4046 pVar->GetInteger();
4047 }
4048 }
4049 }
4050
4051 void SbRtl_Unload(StarBASIC *, SbxArray & rPar, bool)
4052 {
4053 rPar.Get(0)->PutEmpty();
4054 if (rPar.Count() != 2)
4055 {
4056 return StarBASIC::Error( ERRCODE_BASIC_BAD_ARGUMENT );
4057 }
4058
4059
4060 SbxBase* pObj = rPar.Get(1)->GetObject();
4061 if ( !pObj )
4062 return;
4063
4064 if (SbUserFormModule* pFormModule = dynamic_cast<SbUserFormModule*>(pObj))
4065 {
4066 pFormModule->Unload();
4067 }
4068 else if (SbxObject *pSbxObj = dynamic_cast<SbxObject*>(pObj))
4069 {
4070 SbxVariable* pVar = pSbxObj->Find(u"Unload"_ustr, SbxClassType::Method);
4071 if( pVar )
4072 {
4073 pVar->GetInteger();
4074 }
4075 }
4076 }
4077
4078 void SbRtl_LoadPicture(StarBASIC *, SbxArray & rPar, bool)
4079 {
4080 if (rPar.Count() != 2)
4081 {
4082 return StarBASIC::Error( ERRCODE_BASIC_BAD_ARGUMENT );
4083 }
4084
4085 OUString aFileURL = getFullPath(rPar.Get(1)->GetOUString());
4086 std::unique_ptr<SvStream> pStream(utl::UcbStreamHelper::CreateStream( aFileURL, StreamMode::READ ));
4087 if( pStream )
4088 {
4089 Bitmap aBmp;
4090 ReadDIB(aBmp, *pStream, true);
4091 Graphic aGraphic(aBmp);
4092
4093 SbxObjectRef xRef = new SbStdPicture;
4094 static_cast<SbStdPicture*>(xRef.get())->SetGraphic( aGraphic );
4095 rPar.Get(0)->PutObject(xRef.get());
4096 }
4097 }
4098
4099 void SbRtl_SavePicture(StarBASIC *, SbxArray & rPar, bool)
4100 {
4101 rPar.Get(0)->PutEmpty();
4102 if (rPar.Count() != 3)
4103 {
4104 return StarBASIC::Error( ERRCODE_BASIC_BAD_ARGUMENT );
4105 }
4106
4107 SbxBase* pObj = rPar.Get(1)->GetObject();
4108 if (SbStdPicture *pPicture = dynamic_cast<SbStdPicture*>(pObj))
4109 {
4110 SvFileStream aOStream(rPar.Get(2)->GetOUString(), StreamMode::WRITE | StreamMode::TRUNC);
4111 const Graphic& aGraphic = pPicture->GetGraphic();
4112 TypeSerializer aSerializer(aOStream);
4113 aSerializer.writeGraphic(aGraphic);
4114 }
4115 }
4116
4117 void SbRtl_MsgBox(StarBASIC *, SbxArray & rPar, bool)
4118 {
4119 const sal_uInt32 nArgCount = rPar.Count();
4120 if( nArgCount < 2 || nArgCount > 6 )
4121 {
4122 return StarBASIC::Error( ERRCODE_BASIC_BAD_ARGUMENT );
4123 }
4124
4125 // tdf#147529 - check for missing parameters
4126 if (IsMissing(rPar, 1))
4127 {
4128 return StarBASIC::Error(ERRCODE_BASIC_NOT_OPTIONAL);
4129 }
4130
4131 // tdf#151012 - initialize optional parameters with their default values (number of buttons)
4132 sal_Int16 nType = GetOptionalIntegerParamOrDefault(rPar, 2, SbMB::OK);
4133
4134 OUString aMsg = rPar.Get(1)->GetOUString();
4135 // tdf#151012 - initialize optional parameters with their default values (title of dialog box)
4136 OUString aTitle = GetOptionalOUStringParamOrDefault(rPar, 3, Application::GetDisplayName());
4137
4138 sal_Int16 nDialogType = nType & (SbMB::ICONSTOP | SbMB::ICONQUESTION | SbMB::ICONINFORMATION);
4139
4140 SolarMutexGuard aSolarGuard;
4141 weld::Widget* pParent = Application::GetDefDialogParent();
4142
4143 VclMessageType eType = VclMessageType::Other;
4144
4145 switch (nDialogType)
4146 {
4147 case SbMB::ICONSTOP:
4148 eType = VclMessageType::Error;
4149 break;
4150 case SbMB::ICONQUESTION:
4151 eType = VclMessageType::Question;
4152 break;
4153 case SbMB::ICONEXCLAMATION:
4154 eType = VclMessageType::Warning;
4155 break;
4156 case SbMB::ICONINFORMATION:
4157 eType = VclMessageType::Info;
4158 break;
4159 }
4160
4161 std::unique_ptr<weld::MessageDialog> xBox(Application::CreateMessageDialog(pParent,
4162 eType, VclButtonsType::NONE, aMsg, GetpApp()));
4163
4164 std::vector<std::pair<StandardButtonType, sal_Int16>> buttons;
4165 switch (nType & 0x0F) // delete bits 4-16
4166 {
4167 case SbMB::OK:
4168 default:
4169 buttons.emplace_back(StandardButtonType::OK, SbMB::Response::OK);
4170 break;
4171 case SbMB::OKCANCEL:
4172 buttons.emplace_back(StandardButtonType::OK, SbMB::Response::OK);
4173 buttons.emplace_back(StandardButtonType::Cancel, SbMB::Response::CANCEL);
4174 break;
4175 case SbMB::ABORTRETRYIGNORE:
4176 buttons.emplace_back(StandardButtonType::Abort, SbMB::Response::ABORT);
4177 buttons.emplace_back(StandardButtonType::Retry, SbMB::Response::RETRY);
4178 buttons.emplace_back(StandardButtonType::Ignore, SbMB::Response::IGNORE);
4179 break;
4180 case SbMB::YESNOCANCEL:
4181 buttons.emplace_back(StandardButtonType::Yes, SbMB::Response::YES);
4182 buttons.emplace_back(StandardButtonType::No, SbMB::Response::NO);
4183 buttons.emplace_back(StandardButtonType::Cancel, SbMB::Response::CANCEL);
4184 break;
4185 case SbMB::YESNO:
4186 buttons.emplace_back(StandardButtonType::Yes, SbMB::Response::YES);
4187 buttons.emplace_back(StandardButtonType::No, SbMB::Response::NO);
4188 break;
4189 case SbMB::RETRYCANCEL:
4190 buttons.emplace_back(StandardButtonType::Retry, SbMB::Response::RETRY);
4191 buttons.emplace_back(StandardButtonType::Cancel, SbMB::Response::CANCEL);
4192 break;
4193 }
4194
4195 for (auto [buttonType, buttonResponse] : buttons)
4196 xBox->add_button(GetStandardText(buttonType), buttonResponse);
4197
4198 std::size_t default_button = 0;
4199 if (nType & SbMB::DEFBUTTON2)
4200 default_button = 1;
4201 else if (nType & SbMB::DEFBUTTON3)
4202 default_button = 2;
4203 xBox->set_default_response(buttons[std::min(default_button, buttons.size() - 1)].second);
4204
4205 xBox->set_title(aTitle);
4206 sal_Int16 nRet = xBox->run();
4207 rPar.Get(0)->PutInteger(nRet);
4208 }
4209
4210 void SbRtl_SetAttr(StarBASIC *, SbxArray & rPar, bool)
4211 {
4212 rPar.Get(0)->PutEmpty();
4213 if (rPar.Count() == 3)
4214 {
4215 OUString aStr = rPar.Get(1)->GetOUString();
4216 sal_Int16 nFlags = rPar.Get(2)->GetInteger();
4217
4218 if( hasUno() )
4219 {
4220 const uno::Reference< ucb::XSimpleFileAccess3 >& xSFI = getFileAccess();
4221 if( xSFI.is() )
4222 {
4223 try
4224 {
4225 bool bReadOnly = bool(nFlags & SbAttributes::READONLY);
4226 xSFI->setReadOnly( aStr, bReadOnly );
4227 bool bHidden = bool(nFlags & SbAttributes::HIDDEN);
4228 xSFI->setHidden( aStr, bHidden );
4229 }
4230 catch(const Exception & )
4231 {
4232 StarBASIC::Error( ERRCODE_IO_GENERAL );
4233 }
4234 }
4235 }
4236 }
4237 else
4238 {
4239 StarBASIC::Error( ERRCODE_BASIC_BAD_ARGUMENT );
4240 }
4241 }
4242
4243 void SbRtl_Reset(StarBASIC *, SbxArray &, bool)
4244 {
4245 SbiIoSystem* pIO = GetSbData()->pInst->GetIoSystem();
4246 if (pIO)
4247 {
4248 pIO->CloseAll();
4249 }
4250 }
4251
4252 void SbRtl_DumpAllObjects(StarBASIC * pBasic, SbxArray & rPar, bool)
4253 {
4254 const sal_uInt32 nArgCount = rPar.Count();
4255 if( nArgCount < 2 || nArgCount > 3 )
4256 {
4257 StarBASIC::Error( ERRCODE_BASIC_BAD_ARGUMENT );
4258 }
4259 else if( !pBasic )
4260 {
4261 StarBASIC::Error( ERRCODE_BASIC_INTERNAL_ERROR );
4262 }
4263 else
4264 {
4265 SbxObject* p = pBasic;
4266 while( p->GetParent() )
4267 {
4268 p = p->GetParent();
4269 }
4270 SvFileStream aStrm(rPar.Get(1)->GetOUString(),
4271 StreamMode::WRITE | StreamMode::TRUNC );
4272 p->Dump(aStrm, rPar.Get(2)->GetBool());
4273 aStrm.Close();
4274 if( aStrm.GetError() != ERRCODE_NONE )
4275 {
4276 StarBASIC::Error( ERRCODE_BASIC_IO_ERROR );
4277 }
4278 }
4279 }
4280
4281
4282 void SbRtl_FileExists(StarBASIC *, SbxArray & rPar, bool)
4283 {
4284 if (rPar.Count() != 2)
4285 return StarBASIC::Error( ERRCODE_BASIC_BAD_ARGUMENT );
4286
4287 OUString aStr = rPar.Get(1)->GetOUString();
4288 bool bExists = false;
4289
4290 if( hasUno() )
4291 {
4292 const uno::Reference< ucb::XSimpleFileAccess3 >& xSFI = getFileAccess();
4293 if( xSFI.is() )
4294 {
4295 try
4296 {
4297 bExists = xSFI->exists( aStr );
4298 }
4299 catch(const Exception & )
4300 {
4301 StarBASIC::Error( ERRCODE_IO_GENERAL );
4302 }
4303 }
4304 }
4305 else
4306 {
4307 DirectoryItem aItem;
4308 FileBase::RC nRet = DirectoryItem::get( getFullPath( aStr ), aItem );
4309 bExists = (nRet == FileBase::E_None);
4310 }
4311 rPar.Get(0)->PutBool(bExists);
4312 }
4313
4314 void SbRtl_Partition(StarBASIC *, SbxArray & rPar, bool)
4315 {
4316 if (rPar.Count() != 5)
4317 {
4318 return StarBASIC::Error( ERRCODE_BASIC_BAD_ARGUMENT );
4319 }
4320
4321 sal_Int32 nNumber = rPar.Get(1)->GetLong();
4322 sal_Int32 nStart = rPar.Get(2)->GetLong();
4323 sal_Int32 nStop = rPar.Get(3)->GetLong();
4324 sal_Int32 nInterval = rPar.Get(4)->GetLong();
4325
4326 if( nStart < 0 || nStop <= nStart || nInterval < 1 )
4327 {
4328 return StarBASIC::Error( ERRCODE_BASIC_BAD_ARGUMENT );
4329 }
4330
4331 // the Partition function inserts leading spaces before lowervalue and uppervalue
4332 // so that they both have the same number of characters as the string
4333 // representation of the value (Stop + 1). This ensures that if you use the output
4334 // of the Partition function with several values of Number, the resulting text
4335 // will be handled properly during any subsequent sort operation.
4336
4337 // calculate the maximum number of characters before lowervalue and uppervalue
4338 OUString aBeforeStart = OUString::number( nStart - 1 );
4339 OUString aAfterStop = OUString::number( nStop + 1 );
4340 sal_Int32 nLen1 = aBeforeStart.getLength();
4341 sal_Int32 nLen2 = aAfterStop.getLength();
4342 sal_Int32 nLen = nLen1 >= nLen2 ? nLen1:nLen2;
4343
4344 OUStringBuffer aRetStr( nLen * 2 + 1);
4345 OUString aLowerValue;
4346 OUString aUpperValue;
4347 if( nNumber < nStart )
4348 {
4349 aUpperValue = aBeforeStart;
4350 }
4351 else if( nNumber > nStop )
4352 {
4353 aLowerValue = aAfterStop;
4354 }
4355 else
4356 {
4357 sal_Int32 nLowerValue = nNumber;
4358 sal_Int32 nUpperValue = nLowerValue;
4359 if( nInterval > 1 )
4360 {
4361 nLowerValue = ((( nNumber - nStart ) / nInterval ) * nInterval ) + nStart;
4362 nUpperValue = nLowerValue + nInterval - 1;
4363 }
4364 aLowerValue = OUString::number( nLowerValue );
4365 aUpperValue = OUString::number( nUpperValue );
4366 }
4367
4368 nLen1 = aLowerValue.getLength();
4369 nLen2 = aUpperValue.getLength();
4370
4371 if( nLen > nLen1 )
4372 {
4373 // appending the leading spaces for the lowervalue
4374 for ( sal_Int32 i= nLen - nLen1; i > 0; --i )
4375 {
4376 aRetStr.append(" ");
4377 }
4378 }
4379 aRetStr.append( aLowerValue + ":");
4380 if( nLen > nLen2 )
4381 {
4382 // appending the leading spaces for the uppervalue
4383 for ( sal_Int32 i= nLen - nLen2; i > 0; --i )
4384 {
4385 aRetStr.append(" ");
4386 }
4387 }
4388 aRetStr.append( aUpperValue );
4389 rPar.Get(0)->PutString(aRetStr.makeStringAndClear());
4390 }
4391
4392 #endif
4393
4394 sal_Int16 implGetDateYear( double aDate )
4395 {
4396 Date aRefDate(1899'12'30);
4397 sal_Int32 nDays = static_cast<sal_Int32>(aDate);
4398 aRefDate.AddDays( nDays );
4399 sal_Int16 nRet = aRefDate.GetYear();
4400 return nRet;
4401 }
4402
4403 bool implDateSerial( sal_Int16 nYear, sal_Int16 nMonth, sal_Int16 nDay,
4404 bool bUseTwoDigitYear, SbDateCorrection eCorr, double& rdRet )
4405 {
4406 // XXX NOTE: For VBA years<0 are invalid and years in the range 0..29 and
4407 // 30..99 can not be input as they are 2-digit for 2000..2029 and
4408 // 1930..1999, VBA mode overrides bUseTwoDigitYear (as if that was always
4409 // true). For VBA years > 9999 are invalid.
4410 // For StarBASIC, if bUseTwoDigitYear==true then years in the range 0..99
4411 // can not be input as they are 2-digit for 1900..1999, years<0 are
4412 // accepted. If bUseTwoDigitYear==false then all years are accepted, but
4413 // year 0 is invalid (last day BCE -0001-12-31, first day CE 0001-01-01).
4414 #if HAVE_FEATURE_SCRIPTING
4415 if ( (nYear < 0 || 9999 < nYear) && SbiRuntime::isVBAEnabled() )
4416 {
4417 StarBASIC::Error( ERRCODE_BASIC_BAD_ARGUMENT );
4418 return false;
4419 }
4420 else if ( nYear < 30 && SbiRuntime::isVBAEnabled() )
4421 {
4422 nYear += 2000;
4423 }
4424 else
4425 #endif
4426 {
4427 if ( 0 <= nYear && nYear < 100 &&
4428 #if HAVE_FEATURE_SCRIPTING
4429 (bUseTwoDigitYear || SbiRuntime::isVBAEnabled())
4430 #else
4431 bUseTwoDigitYear
4432 #endif
4433 )
4434 {
4435 nYear += 1900;
4436 }
4437 }
4438
4439 sal_Int32 nAddMonths = 0;
4440 sal_Int32 nAddDays = 0;
4441 // Always sanitize values to set date and to use for validity detection.
4442 if (nMonth < 1 || 12 < nMonth)
4443 {
4444 sal_Int16 nM = ((nMonth < 1) ? (12 + (nMonth % 12)) : (nMonth % 12));
4445 nAddMonths = nMonth - nM;
4446 nMonth = nM;
4447 }
4448 // Day 0 would already be normalized during Date::Normalize(), include
4449 // it in negative days, also to detect non-validity. The actual day of
4450 // month is 1+(nDay-1)
4451 if (nDay < 1)
4452 {
4453 nAddDays = nDay - 1;
4454 nDay = 1;
4455 }
4456 else if (nDay > 31)
4457 {
4458 nAddDays = nDay - 31;
4459 nDay = 31;
4460 }
4461
4462 Date aCurDate( nDay, nMonth, nYear );
4463
4464 /* TODO: we could enable the same rollover mechanism for StarBASIC to be
4465 * compatible with VBA (just with our wider supported date range), then
4466 * documentation would need to be adapted. As is, the DateSerial() runtime
4467 * function works as dumb as documented... (except that the resulting date
4468 * is checked for validity now and not just day<=31 and month<=12).
4469 * If change wanted then simply remove overriding RollOver here and adapt
4470 * documentation.*/
4471 #if HAVE_FEATURE_SCRIPTING
4472 if (eCorr == SbDateCorrection::RollOver && !SbiRuntime::isVBAEnabled())
4473 eCorr = SbDateCorrection::None;
4474 #endif
4475
4476 if (nYear == 0 || (eCorr == SbDateCorrection::None && (nAddMonths || nAddDays || !aCurDate.IsValidDate())))
4477 {
4478 #if HAVE_FEATURE_SCRIPTING
4479 StarBASIC::Error( ERRCODE_BASIC_BAD_ARGUMENT );
4480 #endif
4481 return false;
4482 }
4483
4484 if (eCorr != SbDateCorrection::None)
4485 {
4486 aCurDate.Normalize();
4487 if (nAddMonths)
4488 aCurDate.AddMonths( nAddMonths);
4489 if (nAddDays)
4490 aCurDate.AddDays( nAddDays);
4491 if (eCorr == SbDateCorrection::TruncateToMonth && aCurDate.GetMonth() != nMonth)
4492 {
4493 if (aCurDate.GetYear() == SAL_MAX_INT16 && nMonth == 12)
4494 {
4495 // Roll over and back not possible, hard max.
4496 aCurDate.SetMonth(12);
4497 aCurDate.SetDay(31);
4498 }
4499 else
4500 {
4501 aCurDate.SetMonth(nMonth);
4502 aCurDate.SetDay(1);
4503 aCurDate.AddMonths(1);
4504 aCurDate.AddDays(-1);
4505 }
4506 }
4507 }
4508
4509 rdRet = GetDayDiff(aCurDate);
4510 return true;
4511 }
4512
4513 double implTimeSerial(sal_Int16 nHours, sal_Int16 nMinutes, sal_Int16 nSeconds,
4514 sal_Int32 nMilliSeconds)
4515 {
4516 return (nHours * ::tools::Time::milliSecPerHour + nMinutes * ::tools::Time::milliSecPerMinute
4517 + nSeconds * ::tools::Time::milliSecPerSec + nMilliSeconds)
4518 / static_cast<double>(::tools::Time::milliSecPerDay);
4519 }
4520
4521 bool implDateTimeSerial(sal_Int16 nYear, sal_Int16 nMonth, sal_Int16 nDay, sal_Int16 nHour,
4522 sal_Int16 nMinute, sal_Int16 nSecond, sal_Int32 nMilliSecond, double& rdRet)
4523 {
4524 double dDate;
4525 if(!implDateSerial(nYear, nMonth, nDay, false/*bUseTwoDigitYear*/, SbDateCorrection::None, dDate))
4526 return false;
4527 rdRet += dDate + implTimeSerial(nHour, nMinute, nSecond, nMilliSecond);
4528 return true;
4529 }
4530
4531 sal_Int16 implGetMinute( double dDate )
4532 {
4533 double nFrac = (dDate - floor(dDate)) * ::tools::Time::milliSecPerDay;
4534 sal_uInt64 nMilliSeconds = static_cast<sal_uInt64>(nFrac + 0.5);
4535 return static_cast<sal_Int16>((nMilliSeconds / ::tools::Time::milliSecPerMinute)
4536 % ::tools::Time::minutePerHour);
4537 }
4538
4539 /* vim:set shiftwidth=4 softtabstop=4 expandtab: */