LibreOffice Module sw (master)  1
dbmgr.cxx
Go to the documentation of this file.
1 /* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
2 /*
3  * This file is part of the LibreOffice project.
4  *
5  * This Source Code Form is subject to the terms of the Mozilla Public
6  * License, v. 2.0. If a copy of the MPL was not distributed with this
7  * file, You can obtain one at http://mozilla.org/MPL/2.0/.
8  *
9  * This file incorporates work covered by the following license notice:
10  *
11  * Licensed to the Apache Software Foundation (ASF) under one or more
12  * contributor license agreements. See the NOTICE file distributed
13  * with this work for additional information regarding copyright
14  * ownership. The ASF licenses this file to you under the Apache
15  * License, Version 2.0 (the "License"); you may not use this file
16  * except in compliance with the License. You may obtain a copy of
17  * the License at http://www.apache.org/licenses/LICENSE-2.0 .
18  */
19 
20 #include <sal/config.h>
21 
22 #include <cassert>
23 #include <cstdarg>
24 
25 #include <unotxdoc.hxx>
26 #include <sfx2/app.hxx>
27 #include <sfx2/printer.hxx>
28 #include <com/sun/star/sdb/CommandType.hpp>
29 #include <com/sun/star/sdb/XDocumentDataSource.hpp>
30 #include <com/sun/star/lang/DisposedException.hpp>
31 #include <com/sun/star/lang/XEventListener.hpp>
32 #include <com/sun/star/uri/UriReferenceFactory.hpp>
33 #include <com/sun/star/uri/VndSunStarPkgUrlReferenceFactory.hpp>
34 #include <com/sun/star/util/NumberFormatter.hpp>
35 #include <com/sun/star/sdb/DatabaseContext.hpp>
36 #include <com/sun/star/sdb/TextConnectionSettings.hpp>
37 #include <com/sun/star/sdb/XCompletedConnection.hpp>
38 #include <com/sun/star/sdb/XCompletedExecution.hpp>
39 #include <com/sun/star/container/XChild.hpp>
40 #include <com/sun/star/text/MailMergeEvent.hpp>
41 #include <com/sun/star/frame/XStorable.hpp>
42 #include <com/sun/star/task/InteractionHandler.hpp>
43 #include <com/sun/star/ui/dialogs/TemplateDescription.hpp>
44 #include <com/sun/star/ui/dialogs/XFilePicker3.hpp>
45 #include <com/sun/star/ui/dialogs/XFilterManager.hpp>
46 #include <com/sun/star/beans/XPropertySet.hpp>
47 #include <vcl/errinf.hxx>
48 #include <sfx2/fcontnr.hxx>
49 #include <sfx2/filedlghelper.hxx>
50 #include <sfx2/viewfrm.hxx>
51 #include <dbconfig.hxx>
52 #include <pagedesc.hxx>
53 #include <vcl/lstbox.hxx>
54 #include <unotools/tempfile.hxx>
55 #include <unotools/pathoptions.hxx>
56 #include <svl/urihelper.hxx>
57 #include <svl/zforlist.hxx>
58 #include <svl/zformat.hxx>
59 #include <svl/stritem.hxx>
60 #include <svl/eitem.hxx>
61 #include <vcl/oldprintadaptor.hxx>
62 #include <sfx2/docfile.hxx>
63 #include <sfx2/docfilt.hxx>
64 #include <sfx2/progress.hxx>
65 #include <sfx2/dispatch.hxx>
66 #include <cmdid.h>
67 #include <swmodule.hxx>
68 #include <view.hxx>
69 #include <docsh.hxx>
70 #include <edtwin.hxx>
71 #include <wrtsh.hxx>
72 #include <fldbas.hxx>
73 #include <initui.hxx>
74 #include <swundo.hxx>
75 #include <flddat.hxx>
76 #include <modcfg.hxx>
77 #include <shellio.hxx>
78 #include <dbui.hxx>
79 #include <dbmgr.hxx>
80 #include <doc.hxx>
85 #include <IDocumentUndoRedo.hxx>
86 #include <swwait.hxx>
87 #include <swunohelper.hxx>
88 #include <dbui.hrc>
89 #include <globals.hrc>
90 #include <strings.hrc>
91 #include <mmconfigitem.hxx>
92 #include <sfx2/request.hxx>
93 #include <hintids.hxx>
94 #include <com/sun/star/sdbc/XRowSet.hpp>
95 #include <com/sun/star/sdbcx/XTablesSupplier.hpp>
96 #include <com/sun/star/sdbcx/XColumnsSupplier.hpp>
97 #include <com/sun/star/sdb/XQueriesSupplier.hpp>
98 #include <com/sun/star/sdb/XColumn.hpp>
99 #include <com/sun/star/sdbc/DataType.hpp>
100 #include <com/sun/star/sdbc/ResultSetType.hpp>
101 #include <com/sun/star/sdbc/SQLException.hpp>
102 #include <com/sun/star/mail/MailAttachment.hpp>
104 #include <comphelper/property.hxx>
106 #include <comphelper/string.hxx>
107 #include <comphelper/types.hxx>
108 #include <mailmergehelper.hxx>
109 #include <maildispatcher.hxx>
110 #include <svtools/htmlcfg.hxx>
112 #include <com/sun/star/util/XNumberFormatTypes.hpp>
113 #include <editeng/langitem.hxx>
114 #include <svl/numuno.hxx>
115 #include <connectivity/dbtools.hxx>
117 #include <unotools/charclass.hxx>
118 #include <tools/diagnose_ex.h>
119 
120 #include <unomailmerge.hxx>
121 #include <sfx2/event.hxx>
123 #include <osl/mutex.hxx>
124 #include <rtl/textenc.h>
125 #include <rtl/tencinfo.h>
126 #include <cppuhelper/implbase.hxx>
127 #include <ndindex.hxx>
128 #include <pam.hxx>
129 #include <swcrsr.hxx>
130 #include <swevent.hxx>
131 #include <osl/file.hxx>
132 #include <sal/log.hxx>
133 #include <swabstdlg.hxx>
134 #include <fmthdft.hxx>
135 #include <vector>
136 #include <unomid.h>
137 #include <section.hxx>
138 #include <rootfrm.hxx>
139 #include <fmtpdsc.hxx>
140 #include <ndtxt.hxx>
141 #include <calc.hxx>
142 #include <dbfld.hxx>
143 #include <IDocumentState.hxx>
144 #include <imaildsplistener.hxx>
145 #include <iodetect.hxx>
146 #include <IDocumentDeviceAccess.hxx>
147 
148 #include <memory>
150 #include <officecfg/Office/Common.hxx>
151 
152 using namespace ::com::sun::star;
153 using namespace sw;
154 
155 #define DB_SEP_SPACE 0
156 #define DB_SEP_TAB 1
157 #define DB_SEP_RETURN 2
158 #define DB_SEP_NEWLINE 3
159 
160 namespace {
161 
162 void lcl_emitEvent(SfxEventHintId nEventId, sal_Int32 nStrId, SfxObjectShell* pDocShell)
163 {
164  SfxGetpApp()->NotifyEvent(SfxEventHint(nEventId,
165  SwDocShell::GetEventName(nStrId),
166  pDocShell));
167 }
168 
169 }
170 
171 std::vector<std::pair<SwDocShell*, OUString>> SwDBManager::m_aUncommittedRegistrations;
172 
173 enum class SwDBNextRecord { NEXT, FIRST };
174 static bool lcl_ToNextRecord( SwDSParam* pParam, const SwDBNextRecord action = SwDBNextRecord::NEXT );
175 
176 enum class WorkingDocType { SOURCE, TARGET, COPY };
178  const WorkingDocType aType, const SwWrtShell &rSourceWrtShell,
179  const vcl::Window *pSourceWindow,
180  SwDBManager** const ppDBManager,
181  SwView** const pView, SwWrtShell** const pWrtShell, SwDoc** const pDoc );
182 
183 static bool lcl_getCountFromResultSet( sal_Int32& rCount, const SwDSParam* pParam )
184 {
185  rCount = pParam->aSelection.getLength();
186  if ( rCount > 0 )
187  return true;
188 
189  uno::Reference<beans::XPropertySet> xPrSet(pParam->xResultSet, uno::UNO_QUERY);
190  if ( xPrSet.is() )
191  {
192  try
193  {
194  bool bFinal = false;
195  uno::Any aFinal = xPrSet->getPropertyValue("IsRowCountFinal");
196  aFinal >>= bFinal;
197  if(!bFinal)
198  {
199  pParam->xResultSet->last();
200  pParam->xResultSet->first();
201  }
202  uno::Any aCount = xPrSet->getPropertyValue("RowCount");
203  if( aCount >>= rCount )
204  return true;
205  }
206  catch(const uno::Exception&)
207  {
208  }
209  }
210  return false;
211 }
212 
214  : public cppu::WeakImplHelper< lang::XEventListener >
215 {
216 private:
218 
219  virtual void SAL_CALL disposing( const lang::EventObject& Source ) override;
220 
221 public:
223 
224  void Dispose() { m_pDBManager = nullptr; }
225 
226 };
227 
229 class SwDataSourceRemovedListener : public cppu::WeakImplHelper<sdb::XDatabaseRegistrationsListener>
230 {
231  uno::Reference<sdb::XDatabaseContext> m_xDatabaseContext;
233 
234 public:
235  explicit SwDataSourceRemovedListener(SwDBManager& rDBManager);
236  virtual ~SwDataSourceRemovedListener() override;
237  virtual void SAL_CALL registeredDatabaseLocation(const sdb::DatabaseRegistrationEvent& rEvent) override;
238  virtual void SAL_CALL revokedDatabaseLocation(const sdb::DatabaseRegistrationEvent& rEvent) override;
239  virtual void SAL_CALL changedDatabaseLocation(const sdb::DatabaseRegistrationEvent& rEvent) override;
240  virtual void SAL_CALL disposing(const lang::EventObject& rObject) override;
241  void Dispose();
242 };
243 
245  : m_pDBManager(&rDBManager)
246 {
247  uno::Reference<uno::XComponentContext> xComponentContext(comphelper::getProcessComponentContext());
248  m_xDatabaseContext = sdb::DatabaseContext::create(xComponentContext);
249  m_xDatabaseContext->addDatabaseRegistrationsListener(this);
250 }
251 
253 {
254  if (m_xDatabaseContext.is())
255  m_xDatabaseContext->removeDatabaseRegistrationsListener(this);
256 }
257 
258 void SAL_CALL SwDataSourceRemovedListener::registeredDatabaseLocation(const sdb::DatabaseRegistrationEvent& /*rEvent*/)
259 {
260 }
261 
262 void SAL_CALL SwDataSourceRemovedListener::revokedDatabaseLocation(const sdb::DatabaseRegistrationEvent& rEvent)
263 {
264  if (!m_pDBManager || m_pDBManager->getEmbeddedName().isEmpty())
265  return;
266 
267  SwDoc* pDoc = m_pDBManager->getDoc();
268  if (!pDoc)
269  return;
270 
271  SwDocShell* pDocShell = pDoc->GetDocShell();
272  if (!pDocShell)
273  return;
274 
276  OUString sTmpName = "vnd.sun.star.pkg://";
278  sTmpName += "/" + m_pDBManager->getEmbeddedName();
279 
280  if (sTmpName != rEvent.OldLocation)
281  return;
282 
283  // The revoked database location is inside this document, then remove the
284  // embedding, as otherwise it would be back on the next reload of the
285  // document.
286  pDocShell->GetStorage()->removeElement(m_pDBManager->getEmbeddedName());
287  m_pDBManager->setEmbeddedName(OUString(), *pDocShell);
288 }
289 
290 void SAL_CALL SwDataSourceRemovedListener::changedDatabaseLocation(const sdb::DatabaseRegistrationEvent& rEvent)
291 {
292  if (rEvent.OldLocation != rEvent.NewLocation)
293  revokedDatabaseLocation(rEvent);
294 }
295 
296 void SwDataSourceRemovedListener::disposing(const lang::EventObject& /*rObject*/)
297 {
298  m_xDatabaseContext.clear();
299 }
300 
302 {
303  m_pDBManager = nullptr;
304 }
305 
307 {
308  std::unique_ptr<SwDSParam> pMergeData;
313  uno::Reference< mail::XMailMessage> m_xLastMessage;
314 
315  explicit SwDBManager_Impl(SwDBManager& rDBManager)
316  : m_xDisposeListener(new ConnectionDisposedListener_Impl(rDBManager))
317  {}
318 
320  {
321  m_xDisposeListener->Dispose();
322  if (m_xDataSourceRemovedListener.is())
323  m_xDataSourceRemovedListener->Dispose();
324  }
325 };
326 
327 static void lcl_InitNumberFormatter(SwDSParam& rParam, uno::Reference<sdbc::XDataSource> const & xSource)
328 {
329  uno::Reference<uno::XComponentContext> xContext = ::comphelper::getProcessComponentContext();
330  rParam.xFormatter = util::NumberFormatter::create(xContext);
331  uno::Reference<beans::XPropertySet> xSourceProps(
332  (xSource.is()
333  ? xSource
335  rParam.xConnection, rParam.sDataSource)),
336  uno::UNO_QUERY);
337  if(xSourceProps.is())
338  {
339  uno::Any aFormats = xSourceProps->getPropertyValue("NumberFormatsSupplier");
340  if(aFormats.hasValue())
341  {
342  uno::Reference<util::XNumberFormatsSupplier> xSuppl;
343  aFormats >>= xSuppl;
344  if(xSuppl.is())
345  {
346  uno::Reference< beans::XPropertySet > xSettings = xSuppl->getNumberFormatSettings();
347  uno::Any aNull = xSettings->getPropertyValue("NullDate");
348  aNull >>= rParam.aNullDate;
349  if(rParam.xFormatter.is())
350  rParam.xFormatter->attachNumberFormatsSupplier(xSuppl);
351  }
352  }
353  }
354 }
355 
356 static bool lcl_MoveAbsolute(SwDSParam* pParam, long nAbsPos)
357 {
358  bool bRet = false;
359  try
360  {
361  if(pParam->aSelection.hasElements())
362  {
363  if(pParam->aSelection.getLength() <= nAbsPos)
364  {
365  pParam->bEndOfDB = true;
366  bRet = false;
367  }
368  else
369  {
370  pParam->nSelectionIndex = nAbsPos;
371  sal_Int32 nPos = 0;
372  pParam->aSelection.getConstArray()[ pParam->nSelectionIndex ] >>= nPos;
373  pParam->bEndOfDB = !pParam->xResultSet->absolute( nPos );
374  bRet = !pParam->bEndOfDB;
375  }
376  }
377  else if(pParam->bScrollable)
378  {
379  bRet = pParam->xResultSet->absolute( nAbsPos );
380  }
381  else
382  {
383  OSL_FAIL("no absolute positioning available");
384  }
385  }
386  catch(const uno::Exception&)
387  {
388  }
389  return bRet;
390 }
391 
392 static void lcl_GetColumnCnt(SwDSParam *pParam,
393  const uno::Reference< beans::XPropertySet > &rColumnProps,
394  LanguageType nLanguage, OUString &rResult, double* pNumber)
395 {
396  SwDBFormatData aFormatData;
397  if(!pParam->xFormatter.is())
398  {
399  uno::Reference<sdbc::XDataSource> xSource = SwDBManager::getDataSourceAsParent(
400  pParam->xConnection,pParam->sDataSource);
401  lcl_InitNumberFormatter(*pParam, xSource );
402  }
403  aFormatData.aNullDate = pParam->aNullDate;
404  aFormatData.xFormatter = pParam->xFormatter;
405 
406  aFormatData.aLocale = LanguageTag( nLanguage ).getLocale();
407 
408  rResult = SwDBManager::GetDBField( rColumnProps, aFormatData, pNumber);
409 }
410 
411 static bool lcl_GetColumnCnt(SwDSParam* pParam, const OUString& rColumnName,
412  LanguageType nLanguage, OUString& rResult, double* pNumber)
413 {
414  uno::Reference< sdbcx::XColumnsSupplier > xColsSupp( pParam->xResultSet, uno::UNO_QUERY );
415  uno::Reference<container::XNameAccess> xCols;
416  try
417  {
418  xCols = xColsSupp->getColumns();
419  }
420  catch(const lang::DisposedException&)
421  {
422  }
423  if(!xCols.is() || !xCols->hasByName(rColumnName))
424  return false;
425  uno::Any aCol = xCols->getByName(rColumnName);
426  uno::Reference< beans::XPropertySet > xColumnProps;
427  aCol >>= xColumnProps;
428  lcl_GetColumnCnt( pParam, xColumnProps, nLanguage, rResult, pNumber );
429  return true;
430 };
431 
432 // import data
433 bool SwDBManager::Merge( const SwMergeDescriptor& rMergeDesc )
434 {
435  assert( !m_bInMerge && !m_pImpl->pMergeData && "merge already activated!" );
436 
437  SfxObjectShellLock xWorkObjSh;
438  SwWrtShell *pWorkShell = nullptr;
439  SwDoc *pWorkDoc = nullptr;
440  SwDBManager *pWorkDocOrigDBManager = nullptr;
441 
442  switch( rMergeDesc.nMergeType )
443  {
444  case DBMGR_MERGE_PRINTER:
445  case DBMGR_MERGE_EMAIL:
446  case DBMGR_MERGE_FILE:
447  case DBMGR_MERGE_SHELL:
448  {
449  SwDocShell *pSourceDocSh = rMergeDesc.rSh.GetView().GetDocShell();
450  if( pSourceDocSh->IsModified() )
451  {
452  pWorkDocOrigDBManager = this;
453  xWorkObjSh = lcl_CreateWorkingDocument(
454  WorkingDocType::SOURCE, rMergeDesc.rSh, nullptr,
455  &pWorkDocOrigDBManager, nullptr, &pWorkShell, &pWorkDoc );
456  }
457  [[fallthrough]];
458  }
459 
460  default:
461  if( !xWorkObjSh.Is() )
462  pWorkShell = &rMergeDesc.rSh;
463  break;
464  }
465 
466  SwDBData aData;
467  aData.nCommandType = sdb::CommandType::TABLE;
468  uno::Reference<sdbc::XResultSet> xResSet;
469  uno::Sequence<uno::Any> aSelection;
470  uno::Reference< sdbc::XConnection> xConnection;
471 
472  aData.sDataSource = rMergeDesc.rDescriptor.getDataSource();
475 
482 
483  if(aData.sDataSource.isEmpty() || aData.sCommand.isEmpty() || !xResSet.is())
484  {
485  return false;
486  }
487 
488  m_pImpl->pMergeData.reset(new SwDSParam(aData, xResSet, aSelection));
489  SwDSParam* pTemp = FindDSData(aData, false);
490  if(pTemp)
491  *pTemp = *m_pImpl->pMergeData;
492  else
493  {
494  // calls from the calculator may have added a connection with an invalid commandtype
495  //"real" data base connections added here have to re-use the already available
496  //DSData and set the correct CommandType
497  SwDBData aTempData(aData);
498  aData.nCommandType = -1;
499  pTemp = FindDSData(aData, false);
500  if(pTemp)
501  *pTemp = *m_pImpl->pMergeData;
502  else
503  {
504  m_DataSourceParams.push_back(std::make_unique<SwDSParam>(*m_pImpl->pMergeData));
505  try
506  {
507  uno::Reference<lang::XComponent> xComponent(m_DataSourceParams.back()->xConnection, uno::UNO_QUERY);
508  if(xComponent.is())
509  xComponent->addEventListener(m_pImpl->m_xDisposeListener.get());
510  }
511  catch(const uno::Exception&)
512  {
513  }
514  }
515  }
516  if(!m_pImpl->pMergeData->xConnection.is())
517  m_pImpl->pMergeData->xConnection = xConnection;
518  // add an XEventListener
519 
520  lcl_ToNextRecord(m_pImpl->pMergeData.get(), SwDBNextRecord::FIRST);
521 
522  uno::Reference<sdbc::XDataSource> xSource = SwDBManager::getDataSourceAsParent(xConnection,aData.sDataSource);
523 
524  lcl_InitNumberFormatter(*m_pImpl->pMergeData, xSource);
525 
526  pWorkShell->ChgDBData(aData);
527  m_bInMerge = true;
528 
529  if (IsInitDBFields())
530  {
531  // with database fields without DB-Name, use DB-Name from Doc
532  std::vector<OUString> aDBNames;
533  aDBNames.emplace_back();
534  SwDBData aInsertData = pWorkShell->GetDBData();
535  OUString sDBName = aInsertData.sDataSource
536  + OUStringLiteral1(DB_DELIM) + aInsertData.sCommand
537  + OUStringLiteral1(DB_DELIM)
538  + OUString::number(aInsertData.nCommandType);
539  pWorkShell->ChangeDBFields( aDBNames, sDBName);
540  SetInitDBFields(false);
541  }
542 
543  bool bRet = true;
544  switch(rMergeDesc.nMergeType)
545  {
546  case DBMGR_MERGE:
547  pWorkShell->StartAllAction();
548  pWorkShell->SwViewShell::UpdateFields( true );
549  pWorkShell->SetModified();
550  pWorkShell->EndAllAction();
551  break;
552 
553  case DBMGR_MERGE_PRINTER:
554  case DBMGR_MERGE_EMAIL:
555  case DBMGR_MERGE_FILE:
556  case DBMGR_MERGE_SHELL:
557  // save files and send them as e-Mail if required
558  bRet = MergeMailFiles(pWorkShell, rMergeDesc);
559  break;
560 
561  default:
562  // insert selected entries
563  // (was: InsertRecord)
564  ImportFromConnection(pWorkShell);
565  break;
566  }
567 
568  m_pImpl->pMergeData.reset();
569 
570  if( xWorkObjSh.Is() )
571  {
572  pWorkDoc->SetDBManager( pWorkDocOrigDBManager );
573  xWorkObjSh->DoClose();
574  }
575 
576  m_bInMerge = false;
577 
578  return bRet;
579 }
580 
582 {
583  if(m_pImpl->pMergeData && !m_pImpl->pMergeData->bEndOfDB)
584  {
585  pSh->StartAllAction();
586  pSh->StartUndo();
587  bool bGroupUndo(pSh->DoesGroupUndo());
588  pSh->DoGroupUndo(false);
589 
590  if( pSh->HasSelection() )
591  pSh->DelRight();
592 
593  std::unique_ptr<SwWait> pWait;
594 
595  {
596  sal_uLong i = 0;
597  do {
598 
599  ImportDBEntry(pSh);
600  if( 10 == ++i )
601  pWait.reset(new SwWait( *pSh->GetView().GetDocShell(), true));
602 
603  } while(ToNextMergeRecord());
604  }
605 
606  pSh->DoGroupUndo(bGroupUndo);
607  pSh->EndUndo();
608  pSh->EndAllAction();
609  }
610 }
611 
612 static OUString lcl_FindColumn(const OUString& sFormatStr,sal_uInt16 &nUsedPos, sal_uInt8 &nSeparator)
613 {
614  OUStringBuffer sReturn;
615  sal_uInt16 nLen = sFormatStr.getLength();
616  nSeparator = 0xff;
617  while(nUsedPos < nLen && nSeparator == 0xff)
618  {
619  sal_Unicode cCurrent = sFormatStr[nUsedPos];
620  switch(cCurrent)
621  {
622  case ',':
623  nSeparator = DB_SEP_SPACE;
624  break;
625  case ';':
626  nSeparator = DB_SEP_RETURN;
627  break;
628  case ':':
629  nSeparator = DB_SEP_TAB;
630  break;
631  case '#':
632  nSeparator = DB_SEP_NEWLINE;
633  break;
634  default:
635  sReturn.append(cCurrent);
636  }
637  nUsedPos++;
638 
639  }
640  return sReturn.makeStringAndClear();
641 }
642 
644 {
645  if(m_pImpl->pMergeData && !m_pImpl->pMergeData->bEndOfDB)
646  {
647  uno::Reference< sdbcx::XColumnsSupplier > xColsSupp( m_pImpl->pMergeData->xResultSet, uno::UNO_QUERY );
648  uno::Reference<container::XNameAccess> xCols = xColsSupp->getColumns();
649  OUString sFormatStr;
650  sal_uInt16 nFormatLen = sFormatStr.getLength();
651  if( nFormatLen )
652  {
653  const char cSpace = ' ';
654  const char cTab = '\t';
655  sal_uInt16 nUsedPos = 0;
656  sal_uInt8 nSeparator;
657  OUString sColumn = lcl_FindColumn(sFormatStr, nUsedPos, nSeparator);
658  while( !sColumn.isEmpty() )
659  {
660  if(!xCols->hasByName(sColumn))
661  return;
662  uno::Any aCol = xCols->getByName(sColumn);
663  uno::Reference< beans::XPropertySet > xColumnProp;
664  aCol >>= xColumnProp;
665  if(xColumnProp.is())
666  {
667  SwDBFormatData aDBFormat;
668  OUString sInsert = GetDBField( xColumnProp, aDBFormat);
669  if( DB_SEP_SPACE == nSeparator )
670  sInsert += OUStringLiteral1(cSpace);
671  else if( DB_SEP_TAB == nSeparator)
672  sInsert += OUStringLiteral1(cTab);
673  pSh->Insert(sInsert);
674  if( DB_SEP_RETURN == nSeparator)
675  pSh->SplitNode();
676  else if(DB_SEP_NEWLINE == nSeparator)
677  pSh->InsertLineBreak();
678  }
679  else
680  {
681  // column not found -> show error
682  OUStringBuffer sInsert;
683  sInsert.append('?').append(sColumn).append('?');
684  pSh->Insert(sInsert.makeStringAndClear());
685  }
686  sColumn = lcl_FindColumn(sFormatStr, nUsedPos, nSeparator);
687  }
688  pSh->SplitNode();
689  }
690  else
691  {
692  OUStringBuffer sStr;
693  uno::Sequence<OUString> aColNames = xCols->getElementNames();
694  const OUString* pColNames = aColNames.getConstArray();
695  long nLength = aColNames.getLength();
696  for(long i = 0; i < nLength; i++)
697  {
698  uno::Any aCol = xCols->getByName(pColNames[i]);
699  uno::Reference< beans::XPropertySet > xColumnProp;
700  aCol >>= xColumnProp;
701  SwDBFormatData aDBFormat;
702  sStr.append(GetDBField( xColumnProp, aDBFormat));
703  if (i < nLength - 1)
704  sStr.append("\t");
705  }
706  pSh->SwEditShell::Insert2(sStr.makeStringAndClear());
707  pSh->SwFEShell::SplitNode(); // line feed
708  }
709  }
710 }
711 
712 bool SwDBManager::GetTableNames(weld::ComboBox& rBox, const OUString& rDBName)
713 {
714  bool bRet = false;
715  OUString sOldTableName(rBox.get_active_text());
716  rBox.clear();
717  SwDSParam* pParam = FindDSConnection(rDBName, false);
718  uno::Reference< sdbc::XConnection> xConnection;
719  if (pParam && pParam->xConnection.is())
720  xConnection = pParam->xConnection;
721  else
722  {
723  if ( !rDBName.isEmpty() )
724  xConnection = RegisterConnection( rDBName );
725  }
726  if (xConnection.is())
727  {
728  uno::Reference<sdbcx::XTablesSupplier> xTSupplier(xConnection, uno::UNO_QUERY);
729  if(xTSupplier.is())
730  {
731  uno::Reference<container::XNameAccess> xTables = xTSupplier->getTables();
732  const uno::Sequence<OUString> aTables = xTables->getElementNames();
733  for (const OUString& rTable : aTables)
734  rBox.append("0", rTable);
735  }
736  uno::Reference<sdb::XQueriesSupplier> xQSupplier(xConnection, uno::UNO_QUERY);
737  if(xQSupplier.is())
738  {
739  uno::Reference<container::XNameAccess> xQueries = xQSupplier->getQueries();
740  const uno::Sequence<OUString> aQueries = xQueries->getElementNames();
741  for (const OUString& rQuery : aQueries)
742  rBox.append("1", rQuery);
743  }
744  if (!sOldTableName.isEmpty())
745  rBox.set_active_text(sOldTableName);
746  bRet = true;
747  }
748  return bRet;
749 }
750 
751 // fill Listbox with column names of a database
753  const OUString& rDBName, const OUString& rTableName)
754 {
755  SwDBData aData;
756  aData.sDataSource = rDBName;
757  aData.sCommand = rTableName;
758  aData.nCommandType = -1;
759  SwDSParam* pParam = FindDSData(aData, false);
760  uno::Reference< sdbc::XConnection> xConnection;
761  if(pParam && pParam->xConnection.is())
762  xConnection = pParam->xConnection;
763  else
764  {
765  xConnection = RegisterConnection( rDBName );
766  }
767  GetColumnNames(pListBox, xConnection, rTableName);
768 }
769 
771  const OUString& rDBName, const OUString& rTableName)
772 {
773  SwDBData aData;
774  aData.sDataSource = rDBName;
775  aData.sCommand = rTableName;
776  aData.nCommandType = -1;
777  SwDSParam* pParam = FindDSData(aData, false);
778  uno::Reference< sdbc::XConnection> xConnection;
779  if(pParam && pParam->xConnection.is())
780  xConnection = pParam->xConnection;
781  else
782  {
783  xConnection = RegisterConnection( rDBName );
784  }
785  GetColumnNames(rBox, xConnection, rTableName);
786 }
787 
788 void SwDBManager::GetColumnNames(ListBox* pListBox,
789  uno::Reference< sdbc::XConnection> const & xConnection,
790  const OUString& rTableName)
791 {
792  pListBox->Clear();
793  uno::Reference< sdbcx::XColumnsSupplier> xColsSupp = SwDBManager::GetColumnSupplier(xConnection, rTableName);
794  if(xColsSupp.is())
795  {
796  uno::Reference<container::XNameAccess> xCols = xColsSupp->getColumns();
797  const uno::Sequence<OUString> aColNames = xCols->getElementNames();
798  for (const OUString& rColName : aColNames)
799  {
800  pListBox->InsertEntry(rColName);
801  }
802  ::comphelper::disposeComponent( xColsSupp );
803  }
804 }
805 
807  uno::Reference< sdbc::XConnection> const & xConnection,
808  const OUString& rTableName)
809 {
810  rBox.clear();
811  uno::Reference< sdbcx::XColumnsSupplier> xColsSupp = SwDBManager::GetColumnSupplier(xConnection, rTableName);
812  if(xColsSupp.is())
813  {
814  uno::Reference<container::XNameAccess> xCols = xColsSupp->getColumns();
815  const uno::Sequence<OUString> aColNames = xCols->getElementNames();
816  for (const OUString& rColName : aColNames)
817  {
818  rBox.append_text(rColName);
819  }
820  ::comphelper::disposeComponent( xColsSupp );
821  }
822 }
823 
825  : m_aMergeStatus( MergeStatus::Ok )
826  , m_bInitDBFields(false)
827  , m_bInMerge(false)
828  , m_bMergeSilent(false)
829  , m_pImpl(new SwDBManager_Impl(*this))
830  , m_pMergeEvtSrc(nullptr)
831  , m_pDoc(pDoc)
832 {
833 }
834 
835 SwDBManager::~SwDBManager() COVERITY_NOEXCEPT_FALSE
836 {
838 
839  // copy required, m_DataSourceParams can be modified while disposing components
840  std::vector<uno::Reference<sdbc::XConnection>> aCopiedConnections;
841  for (const auto & pParam : m_DataSourceParams)
842  {
843  if(pParam->xConnection.is())
844  {
845  aCopiedConnections.push_back(pParam->xConnection);
846  }
847  }
848  for (const auto & xConnection : aCopiedConnections)
849  {
850  try
851  {
852  uno::Reference<lang::XComponent> xComp(xConnection, uno::UNO_QUERY);
853  if(xComp.is())
854  xComp->dispose();
855  }
856  catch(const uno::RuntimeException&)
857  {
858  //may be disposed already since multiple entries may have used the same connection
859  }
860  }
861 }
862 
863 static void lcl_RemoveSectionLinks( SwWrtShell& rWorkShell )
864 {
865  //reset all links of the sections of synchronized labels
866  size_t nSections = rWorkShell.GetSectionFormatCount();
867  for (size_t nSection = 0; nSection < nSections; ++nSection)
868  {
869  SwSectionData aSectionData( *rWorkShell.GetSectionFormat( nSection ).GetSection() );
870  if( aSectionData.GetType() == FILE_LINK_SECTION )
871  {
872  aSectionData.SetType( CONTENT_SECTION );
873  aSectionData.SetLinkFileName( OUString() );
874  rWorkShell.UpdateSection( nSection, aSectionData );
875  }
876  }
877  rWorkShell.SetLabelDoc( false );
878 }
879 
880 static void lcl_SaveDebugDoc( SfxObjectShell *xTargetDocShell,
881  const char *name, int no = 0 )
882 {
883  static OUString sTempDirURL;
884  if( sTempDirURL.isEmpty() )
885  {
886  SvtPathOptions aPathOpt;
887  utl::TempFile aTempDir( &aPathOpt.GetTempPath(), true );
888  if( aTempDir.IsValid() )
889  {
890  INetURLObject aTempDirURL( aTempDir.GetURL() );
891  sTempDirURL = aTempDirURL.GetMainURL( INetURLObject::DecodeMechanism::NONE );
892  SAL_INFO( "sw.mailmerge", "Dump directory: " << sTempDirURL );
893  }
894  }
895  if( sTempDirURL.isEmpty() )
896  return;
897 
898  const OUString sExt( ".odt" );
899  OUString basename = OUString::createFromAscii( name );
900  if (no > 0)
901  basename += OUString::number(no) + "-";
902  // aTempFile is not deleted, but that seems to be intentional
903  utl::TempFile aTempFile( basename, true, &sExt, &sTempDirURL );
904  INetURLObject aTempFileURL( aTempFile.GetURL() );
905  auto pDstMed = std::make_unique<SfxMedium>(
906  aTempFileURL.GetMainURL( INetURLObject::DecodeMechanism::NONE ),
907  StreamMode::STD_READWRITE );
908  bool bAnyError = !xTargetDocShell->DoSaveAs( *pDstMed );
909  // xObjectShell->DoSaveCompleted crashes the mail merge unit tests, so skip it
910  bAnyError |= (ERRCODE_NONE != xTargetDocShell->GetError());
911  if( bAnyError )
912  SAL_WARN( "sw.mailmerge", "Error saving: " << aTempFile.GetURL() );
913  else
914  SAL_INFO( "sw.mailmerge", "Saved doc as: " << aTempFile.GetURL() );
915 }
916 
917 static bool lcl_SaveDoc(
918  const INetURLObject* pFileURL,
919  const std::shared_ptr<const SfxFilter>& pStoreToFilter,
920  const OUString* pStoreToFilterOptions,
921  const uno::Sequence< beans::PropertyValue >* pSaveToFilterData,
922  const bool bIsPDFexport,
923  SfxObjectShell* xObjectShell,
924  SwWrtShell& rWorkShell,
925  OUString * const decodedURL = nullptr )
926 {
927  OUString url = pFileURL->GetMainURL( INetURLObject::DecodeMechanism::NONE );
928  if( decodedURL )
929  (*decodedURL) = url;
930 
931  SfxMedium* pDstMed = new SfxMedium( url, StreamMode::STD_READWRITE );
932  pDstMed->SetFilter( pStoreToFilter );
933  if( pDstMed->GetItemSet() )
934  {
935  if( pStoreToFilterOptions )
936  pDstMed->GetItemSet()->Put( SfxStringItem(SID_FILE_FILTEROPTIONS,
937  *pStoreToFilterOptions));
938  if( pSaveToFilterData->hasElements() )
939  pDstMed->GetItemSet()->Put( SfxUnoAnyItem(SID_FILTER_DATA,
940  uno::makeAny(*pSaveToFilterData)));
941  }
942 
943  // convert fields to text if we are exporting to PDF.
944  // this prevents a second merge while updating the fields
945  // in SwXTextDocument::getRendererCount()
946  if( bIsPDFexport )
947  rWorkShell.ConvertFieldsToText();
948 
949  bool bAnyError = !xObjectShell->DoSaveAs(*pDstMed);
950  // Actually this should be a bool... so in case of email and individual
951  // files, where this is set, we skip the recently used handling
952  bAnyError |= !xObjectShell->DoSaveCompleted( pDstMed, !decodedURL );
953  bAnyError |= (ERRCODE_NONE != xObjectShell->GetError());
954  if( bAnyError )
955  {
956  // error message ??
957  ErrorHandler::HandleError( xObjectShell->GetError() );
958  }
959  return !bAnyError;
960 }
961 
963  const uno::Sequence< beans::PropertyValue >& rInPrintOptions,
964  uno::Sequence< beans::PropertyValue >& rOutPrintOptions)
965 {
966  // printing should be done synchronously otherwise the document
967  // might already become invalid during the process
968 
969  const sal_Int32 nOffset = 1;
970  rOutPrintOptions.realloc( nOffset );
971  rOutPrintOptions[ 0 ].Name = "Wait";
972  rOutPrintOptions[ 0 ].Value <<= true;
973 
974  // copy print options
975  sal_Int32 nIndex = nOffset;
976  for( const beans::PropertyValue& rOption : rInPrintOptions)
977  {
978  if( rOption.Name == "CopyCount" || rOption.Name == "FileName"
979  || rOption.Name == "Collate" || rOption.Name == "Pages"
980  || rOption.Name == "Wait" || rOption.Name == "PrinterName" )
981  {
982  // add an option
983  rOutPrintOptions.realloc( nIndex + 1 );
984  rOutPrintOptions[ nIndex ].Name = rOption.Name;
985  rOutPrintOptions[ nIndex++ ].Value = rOption.Value ;
986  }
987  }
988 }
989 
991  // input
992  const WorkingDocType aType, const SwWrtShell &rSourceWrtShell,
993  // optional input
994  const vcl::Window *pSourceWindow,
995  // optional in and output to swap the DB manager
996  SwDBManager** const ppDBManager,
997  // optional output
998  SwView** const pView, SwWrtShell** const pWrtShell, SwDoc** const pDoc )
999 {
1000  const SwDoc *pSourceDoc = rSourceWrtShell.GetDoc();
1001  SfxObjectShellRef xWorkObjectShell = pSourceDoc->CreateCopy( true, (aType == WorkingDocType::TARGET) );
1002  SfxViewFrame* pWorkFrame = SfxViewFrame::LoadHiddenDocument( *xWorkObjectShell, SFX_INTERFACE_NONE );
1003 
1004  if( pSourceWindow )
1005  {
1006  // the created window has to be located at the same position as the source window
1007  vcl::Window& rTargetWindow = pWorkFrame->GetFrame().GetWindow();
1008  rTargetWindow.SetPosPixel( pSourceWindow->GetPosPixel() );
1009  }
1010 
1011  SwView* pWorkView = static_cast< SwView* >( pWorkFrame->GetViewShell() );
1012  SwWrtShell* pWorkWrtShell = pWorkView->GetWrtShellPtr();
1013  pWorkWrtShell->GetViewOptions()->SetIdle( false );
1014  pWorkView->AttrChangedNotify( pWorkWrtShell );// in order for SelectShell to be called
1015  SwDoc* pWorkDoc = pWorkWrtShell->GetDoc();
1016  pWorkDoc->GetIDocumentUndoRedo().DoUndo( false );
1017  pWorkDoc->ReplaceDocumentProperties( *pSourceDoc );
1018 
1019  // import print settings
1020  const SwPrintData &rPrintData = pSourceDoc->getIDocumentDeviceAccess().getPrintData();
1021  pWorkDoc->getIDocumentDeviceAccess().setPrintData(rPrintData);
1022 
1023  if( aType == WorkingDocType::TARGET )
1024  {
1025  assert( !ppDBManager );
1026  pWorkDoc->SetInMailMerge( true );
1027  pWorkWrtShell->SetLabelDoc( false );
1028  }
1029  else
1030  {
1031  // We have to swap the DBmanager of the new doc, so we also need input
1032  assert(ppDBManager && *ppDBManager);
1033  SwDBManager *pWorkDBManager = pWorkDoc->GetDBManager();
1034  pWorkDoc->SetDBManager( *ppDBManager );
1035  *ppDBManager = pWorkDBManager;
1036 
1037  if( aType == WorkingDocType::SOURCE )
1038  {
1039  // the GetDBData call constructs the data, if it's missing - kind of const...
1040  pWorkWrtShell->ChgDBData( const_cast<SwDoc*>(pSourceDoc)->GetDBData() );
1041  // some DocumentSettings are currently not copied by SwDoc::CreateCopy
1042  pWorkWrtShell->SetLabelDoc( rSourceWrtShell.IsLabelDoc() );
1043  pWorkDoc->getIDocumentState().ResetModified();
1044  }
1045  else
1047  }
1048 
1049  if( pView ) *pView = pWorkView;
1050  if( pWrtShell ) *pWrtShell = pWorkWrtShell;
1051  if( pDoc ) *pDoc = pWorkDoc;
1052 
1053  return xWorkObjectShell.get();
1054 }
1055 
1057  const SwMergeDescriptor &rMergeDescriptor,
1058  const OUString &sFileURL, const OUString &sMailRecipient,
1059  const OUString &sMailBodyMimeType, rtl_TextEncoding sMailEncoding,
1060  const OUString &sAttachmentMimeType )
1061 {
1062  SwMailMessage* pMessage = new SwMailMessage;
1063  if( rMergeDescriptor.pMailMergeConfigItem->IsMailReplyTo() )
1064  pMessage->setReplyToAddress(rMergeDescriptor.pMailMergeConfigItem->GetMailReplyTo());
1065  pMessage->addRecipient( sMailRecipient );
1066  pMessage->SetSenderAddress( rMergeDescriptor.pMailMergeConfigItem->GetMailAddress() );
1067 
1068  OUStringBuffer sBody;
1069  if( rMergeDescriptor.bSendAsAttachment )
1070  {
1071  sBody = rMergeDescriptor.sMailBody;
1072  mail::MailAttachment aAttach;
1073  aAttach.Data = new SwMailTransferable( sFileURL,
1074  rMergeDescriptor.sAttachmentName, sAttachmentMimeType );
1075  aAttach.ReadableName = rMergeDescriptor.sAttachmentName;
1076  pMessage->addAttachment( aAttach );
1077  }
1078  else
1079  {
1080  //read in the temporary file and use it as mail body
1081  SfxMedium aMedium( sFileURL, StreamMode::READ );
1082  SvStream* pInStream = aMedium.GetInStream();
1083  assert( pInStream && "no output file created?" );
1084  if( !pInStream )
1085  return pMessage;
1086 
1087  pInStream->SetStreamCharSet( sMailEncoding );
1088  OString sLine;
1089  while ( pInStream->ReadLine( sLine ) )
1090  {
1091  sBody.append(OStringToOUString( sLine, sMailEncoding ));
1092  sBody.append("\n");
1093  }
1094  }
1095  pMessage->setSubject( rMergeDescriptor.sSubject );
1096  uno::Reference< datatransfer::XTransferable> xBody =
1097  new SwMailTransferable( sBody.makeStringAndClear(), sMailBodyMimeType );
1098  pMessage->setBody( xBody );
1099 
1100  for( const OUString& sCcRecipient : rMergeDescriptor.aCopiesTo )
1101  pMessage->addCcRecipient( sCcRecipient );
1102  for( const OUString& sBccRecipient : rMergeDescriptor.aBlindCopiesTo )
1103  pMessage->addBccRecipient( sBccRecipient );
1104 
1105  return pMessage;
1106 }
1107 
1109 {
1111 
1112 public:
1114  : m_rDBManager( rDBManager ) {}
1115 
1116  virtual void started( ::rtl::Reference<MailDispatcher> ) override {};
1117  virtual void stopped( ::rtl::Reference<MailDispatcher> ) override {};
1118  virtual void idle( ::rtl::Reference<MailDispatcher> ) override {};
1119 
1121  uno::Reference< mail::XMailMessage> xMessage ) override
1122  {
1123  osl::MutexGuard aGuard( m_rDBManager.m_pImpl->m_aAllEmailSendMutex );
1124  if ( m_rDBManager.m_pImpl->m_xLastMessage == xMessage )
1125  m_rDBManager.m_pImpl->m_xLastMessage.clear();
1126  }
1127 
1128  virtual void mailDeliveryError( ::rtl::Reference<MailDispatcher> xMailDispatcher,
1129  uno::Reference< mail::XMailMessage>, const OUString& ) override
1130  {
1131  osl::MutexGuard aGuard( m_rDBManager.m_pImpl->m_aAllEmailSendMutex );
1132  m_rDBManager.m_aMergeStatus = MergeStatus::Error;
1133  m_rDBManager.m_pImpl->m_xLastMessage.clear();
1134  xMailDispatcher->stop();
1135  }
1136 };
1137 
1143  const SwMergeDescriptor& rMergeDescriptor)
1144 {
1145  // deconstruct mail merge type for better readability.
1146  // uppercase naming is intentional!
1147  const bool bMT_EMAIL = rMergeDescriptor.nMergeType == DBMGR_MERGE_EMAIL;
1148  const bool bMT_SHELL = rMergeDescriptor.nMergeType == DBMGR_MERGE_SHELL;
1149  const bool bMT_PRINTER = rMergeDescriptor.nMergeType == DBMGR_MERGE_PRINTER;
1150  const bool bMT_FILE = rMergeDescriptor.nMergeType == DBMGR_MERGE_FILE;
1151 
1152  //check if the doc is synchronized and contains at least one linked section
1153  const bool bSynchronizedDoc = pSourceShell->IsLabelDoc() && pSourceShell->GetSectionFormatCount() > 1;
1154  const bool bNeedsTempFiles = ( bMT_EMAIL || bMT_FILE );
1155  const bool bIsMergeSilent = IsMergeSilent();
1156 
1157  bool bCheckSingleFile_ = rMergeDescriptor.bCreateSingleFile;
1158  OUString sPrefix_ = rMergeDescriptor.sPrefix;
1159  if( bMT_EMAIL )
1160  {
1161  assert( !rMergeDescriptor.bPrefixIsFilename );
1162  assert(!bCheckSingleFile_);
1163  bCheckSingleFile_ = false;
1164  }
1165  else if( bMT_SHELL || bMT_PRINTER )
1166  {
1167  assert(bCheckSingleFile_);
1168  bCheckSingleFile_ = true;
1169  assert(sPrefix_.isEmpty());
1170  sPrefix_.clear();
1171  }
1172  const bool bCreateSingleFile = bCheckSingleFile_;
1173  const OUString sDescriptorPrefix = sPrefix_;
1174 
1175  // Setup for dumping debugging documents
1176  static const sal_Int32 nMaxDumpDocs = []() {
1177  if (const char* sEnv = getenv("SW_DEBUG_MAILMERGE_DOCS"))
1178  return OUString(sEnv, strlen(sEnv), osl_getThreadTextEncoding()).toInt32();
1179  else
1180  return sal_Int32(0);
1181  }();
1182 
1183  ::rtl::Reference< MailDispatcher > xMailDispatcher;
1185  OUString sMailBodyMimeType;
1186  rtl_TextEncoding sMailEncoding = ::osl_getThreadTextEncoding();
1187 
1188  uno::Reference< beans::XPropertySet > xColumnProp;
1189 
1190  // Check for (mandatory) email or (optional) filename column
1191  SwDBFormatData aColumnDBFormat;
1192  bool bColumnName = !rMergeDescriptor.sDBcolumn.isEmpty();
1193  if( ! bColumnName )
1194  {
1195  if( bMT_EMAIL )
1196  return false;
1197  }
1198  else
1199  {
1200  uno::Reference< sdbcx::XColumnsSupplier > xColsSupp( m_pImpl->pMergeData->xResultSet, uno::UNO_QUERY );
1201  uno::Reference<container::XNameAccess> xCols = xColsSupp->getColumns();
1202  if( !xCols->hasByName( rMergeDescriptor.sDBcolumn ) )
1203  return false;
1204  uno::Any aCol = xCols->getByName( rMergeDescriptor.sDBcolumn );
1205  aCol >>= xColumnProp;
1206 
1207  aColumnDBFormat.xFormatter = m_pImpl->pMergeData->xFormatter;
1208  aColumnDBFormat.aNullDate = m_pImpl->pMergeData->aNullDate;
1209 
1210  if( bMT_EMAIL )
1211  {
1212  // Reset internal mail accounting data
1213  m_pImpl->m_xLastMessage.clear();
1214 
1215  xMailDispatcher.set( new MailDispatcher(rMergeDescriptor.xSmtpServer) );
1216  xMailListener = new MailDispatcherListener_Impl( *this );
1217  xMailDispatcher->addListener( xMailListener );
1218  if(!rMergeDescriptor.bSendAsAttachment && rMergeDescriptor.bSendAsHTML)
1219  {
1220  sMailBodyMimeType = "text/html; charset=";
1221  sMailBodyMimeType += OUString::createFromAscii(
1222  rtl_getBestMimeCharsetFromTextEncoding( sMailEncoding ));
1223  SvxHtmlOptions& rHtmlOptions = SvxHtmlOptions::Get();
1224  sMailEncoding = rHtmlOptions.GetTextEncoding();
1225  }
1226  else
1227  sMailBodyMimeType = "text/plain; charset=UTF-8; format=flowed";
1228  }
1229  }
1230 
1231  SwDocShell *pSourceDocSh = pSourceShell->GetView().GetDocShell();
1232 
1233  // setup the output format
1234  std::shared_ptr<const SfxFilter> pStoreToFilter = SwIoSystem::GetFileFilter(
1236  SfxFilterContainer* pFilterContainer = SwDocShell::Factory().GetFilterContainer();
1237  const OUString* pStoreToFilterOptions = nullptr;
1238 
1239  // if a save_to filter is set then use it - otherwise use the default
1240  if( bMT_EMAIL && !rMergeDescriptor.bSendAsAttachment )
1241  {
1242  OUString sExtension = rMergeDescriptor.bSendAsHTML ? OUString("html") : OUString("txt");
1243  pStoreToFilter = pFilterContainer->GetFilter4Extension(sExtension, SfxFilterFlags::EXPORT);
1244  }
1245  else if( !rMergeDescriptor.sSaveToFilter.isEmpty())
1246  {
1247  std::shared_ptr<const SfxFilter> pFilter =
1248  pFilterContainer->GetFilter4FilterName( rMergeDescriptor.sSaveToFilter );
1249  if(pFilter)
1250  {
1251  pStoreToFilter = pFilter;
1252  if(!rMergeDescriptor.sSaveToFilterOptions.isEmpty())
1253  pStoreToFilterOptions = &rMergeDescriptor.sSaveToFilterOptions;
1254  }
1255  }
1256  const bool bIsPDFexport = pStoreToFilter && pStoreToFilter->GetFilterName() == "writer_pdf_Export";
1257 
1259 
1260  // in case of creating a single resulting file this has to be created here
1261  SwView* pTargetView = rMergeDescriptor.pMailMergeConfigItem ?
1262  rMergeDescriptor.pMailMergeConfigItem->GetTargetView() : nullptr;
1263  SwWrtShell* pTargetShell = nullptr;
1264  SwDoc* pTargetDoc = nullptr;
1265  SfxObjectShellRef xTargetDocShell;
1266 
1267  std::unique_ptr< utl::TempFile > aTempFile;
1268  sal_uInt16 nStartingPageNo = 0;
1269 
1270  vcl::Window *pSourceWindow = nullptr;
1271  std::shared_ptr<weld::GenericDialogController> xProgressDlg;
1272 
1273  try
1274  {
1275  if( !bIsMergeSilent )
1276  {
1277  // construct the process dialog
1278  pSourceWindow = &pSourceShell->GetView().GetEditWin();
1279  if (!bMT_PRINTER)
1280  xProgressDlg.reset(new CreateMonitor(pSourceWindow->GetFrameWeld()));
1281  else
1282  {
1283  xProgressDlg.reset(new PrintMonitor(pSourceWindow->GetFrameWeld()));
1284  static_cast<PrintMonitor*>(xProgressDlg.get())->set_title(
1285  pSourceDocSh->GetTitle(22));
1286  }
1287  weld::DialogController::runAsync(xProgressDlg, [this, &xProgressDlg](sal_Int32 nResult){
1288  if (nResult == RET_CANCEL)
1289  MergeCancel();
1290  xProgressDlg.reset();
1291  });
1292 
1293  Application::Reschedule( true );
1294  }
1295 
1296  if( bCreateSingleFile && !pTargetView )
1297  {
1298  // create a target docshell to put the merged document into
1300  *pSourceShell, bMT_SHELL ? pSourceWindow : nullptr,
1301  nullptr, &pTargetView, &pTargetShell, &pTargetDoc );
1302 
1303  if (nMaxDumpDocs)
1304  lcl_SaveDebugDoc( xTargetDocShell.get(), "MergeDoc" );
1305  }
1306  else if( pTargetView )
1307  {
1308  pTargetShell = pTargetView->GetWrtShellPtr();
1309  pTargetDoc = pTargetShell->GetDoc();
1310  xTargetDocShell = pTargetView->GetDocShell();
1311  }
1312 
1313  if( bCreateSingleFile )
1314  {
1315  // determine the page style and number used at the start of the source document
1316  pSourceShell->SttEndDoc(true);
1317  nStartingPageNo = pSourceShell->GetVirtPageNum();
1318  }
1319 
1320  // Progress, to prohibit KeyInputs
1321  SfxProgress aProgress(pSourceDocSh, OUString(), 1);
1322 
1323  // lock all dispatchers
1324  SfxViewFrame* pViewFrame = SfxViewFrame::GetFirst(pSourceDocSh);
1325  while (pViewFrame)
1326  {
1327  pViewFrame->GetDispatcher()->Lock(true);
1328  pViewFrame = SfxViewFrame::GetNext(*pViewFrame, pSourceDocSh);
1329  }
1330 
1331  sal_Int32 nDocNo = 1;
1332 
1333  // For single file mode, the number of pages in the target document so far, which is used
1334  // by AppendDoc() to adjust position of page-bound objects. Getting this information directly
1335  // from the target doc would require repeated layouts of the doc, which is expensive, but
1336  // it can be manually computed from the source documents (for which we do layouts, so the page
1337  // count is known, and there is a blank page between each of them in the target document).
1338  int targetDocPageCount = 0;
1339 
1340  if( !bIsMergeSilent && !bMT_PRINTER )
1341  {
1342  sal_Int32 nRecordCount = 1;
1343  lcl_getCountFromResultSet( nRecordCount, m_pImpl->pMergeData.get() );
1344 
1345  // Synchronized docs don't auto-advance the record set, but there is a
1346  // "security" check, which will always advance the record set, if there
1347  // is no "next record" field in a synchronized doc => nRecordPerDoc > 0
1348  sal_Int32 nRecordPerDoc = pSourceShell->GetDoc()
1350  if ( bSynchronizedDoc && (nRecordPerDoc > 1) )
1351  --nRecordPerDoc;
1352  assert( nRecordPerDoc > 0 );
1353 
1354  sal_Int32 nMaxDocs = nRecordCount / nRecordPerDoc;
1355  if ( 0 != nRecordCount % nRecordPerDoc )
1356  nMaxDocs += 1;
1357  static_cast<CreateMonitor*>(xProgressDlg.get())->SetTotalCount(nMaxDocs);
1358  }
1359 
1360  long nStartRow, nEndRow;
1361  bool bFreezedLayouts = false;
1362  // to collect temporary email files
1363  std::vector< OUString> aFilesToRemove;
1364 
1365  // The SfxObjectShell will be closed explicitly later but
1366  // it is more safe to use SfxObjectShellLock here
1367  SfxObjectShellLock xWorkDocSh;
1368  SwView* pWorkView = nullptr;
1369  SwDoc* pWorkDoc = nullptr;
1370  SwDBManager* pWorkDocOrigDBManager = nullptr;
1371  SwWrtShell* pWorkShell = nullptr;
1372  bool bWorkDocInitialized = false;
1373 
1374  do
1375  {
1376  nStartRow = m_pImpl->pMergeData ? m_pImpl->pMergeData->xResultSet->getRow() : 0;
1377 
1378  OUString sColumnData;
1379 
1380  // Read the indicated data column, which should contain a valid mail
1381  // address or an optional file name
1382  if( bMT_EMAIL || bColumnName )
1383  {
1384  sColumnData = GetDBField( xColumnProp, aColumnDBFormat );
1385  }
1386 
1387  // create a new temporary file name - only done once in case of bCreateSingleFile
1388  if( bNeedsTempFiles && ( !bWorkDocInitialized || !bCreateSingleFile ))
1389  {
1390  OUString sPrefix = sDescriptorPrefix;
1391  OUString sLeading;
1392 
1393  //#i97667# if the name is from a database field then it will be used _as is_
1394  if( bColumnName && !bMT_EMAIL )
1395  {
1396  if (!sColumnData.isEmpty())
1397  sLeading = sColumnData;
1398  else
1399  sLeading = "_";
1400  }
1401  else
1402  {
1403  INetURLObject aEntry( sPrefix );
1404  sLeading = aEntry.GetBase();
1405  aEntry.removeSegment();
1407  }
1408 
1409  OUString sExt(comphelper::string::stripStart(pStoreToFilter->GetDefaultExtension(), '*'));
1410  aTempFile.reset( new utl::TempFile(sLeading, sColumnData.isEmpty(), &sExt, &sPrefix, true) );
1411  if( !aTempFile->IsValid() )
1412  {
1415  }
1416  }
1417 
1418  if( IsMergeOk() )
1419  {
1420  std::unique_ptr< INetURLObject > aTempFileURL;
1421  if( bNeedsTempFiles )
1422  aTempFileURL.reset( new INetURLObject(aTempFile->GetURL()));
1423  if( !bIsMergeSilent ) {
1424  if( !bMT_PRINTER )
1425  static_cast<CreateMonitor*>(xProgressDlg.get())->SetCurrentPosition(nDocNo);
1426  else {
1427  PrintMonitor *pPrintMonDlg = static_cast<PrintMonitor*>(xProgressDlg.get());
1428  pPrintMonDlg->m_xPrinter->set_label(bNeedsTempFiles
1429  ? aTempFileURL->GetBase() : pSourceDocSh->GetTitle( 2));
1430  OUString sStat( SwResId(STR_STATSTR_LETTER) );
1431  sStat += " " + OUString::number( nDocNo );
1432  pPrintMonDlg->m_xPrintInfo->set_label(sStat);
1433  }
1434  //TODO xProgressDlg->queue_draw();
1435  }
1436 
1437  Application::Reschedule( true );
1438 
1439  // Create a copy of the source document and work with that one instead of the source.
1440  // If we're not in the single file mode (which requires modifying the document for the merging),
1441  // it is enough to do this just once. Currently PDF also has to be treated special.
1442  if( !bWorkDocInitialized || bCreateSingleFile || bIsPDFexport )
1443  {
1444  assert( !xWorkDocSh.Is());
1445  pWorkDocOrigDBManager = this;
1447  *pSourceShell, nullptr, &pWorkDocOrigDBManager,
1448  &pWorkView, &pWorkShell, &pWorkDoc );
1449  if ( (nMaxDumpDocs < 0) || (nDocNo <= nMaxDumpDocs) )
1450  lcl_SaveDebugDoc( xWorkDocSh, "WorkDoc", nDocNo );
1451 
1452  // #i69458# lock fields to prevent access to the result set while calculating layout
1453  // tdf#92324: and do not unlock: keep document locked during printing to avoid
1454  // ExpFields update during printing, generation of preview, etc.
1455  pWorkShell->LockExpFields();
1456  pWorkShell->CalcLayout();
1457  // tdf#121168: Now force correct page descriptions applied to page frames. Without
1458  // this, e.g., page frames starting with sections could have page descriptions set
1459  // wrong. This would lead to wrong page styles applied in SwDoc::AppendDoc below.
1460  pWorkShell->GetViewOptions()->SetIdle(true);
1461  for (auto aLayout : pWorkShell->GetDoc()->GetAllLayouts())
1462  {
1463  aLayout->FreezeLayout(false);
1464  aLayout->AllCheckPageDescs();
1465  }
1466  }
1467 
1468  lcl_emitEvent(SfxEventHintId::SwEventFieldMerge, STR_SW_EVENT_FIELD_MERGE, xWorkDocSh);
1469 
1470  // tdf#92324: Allow ExpFields update only by explicit instruction to avoid
1471  // database cursor movement on any other fields update, for example during
1472  // print preview and other operations
1473  if ( pWorkShell->IsExpFieldsLocked() )
1474  pWorkShell->UnlockExpFields();
1475  pWorkShell->SwViewShell::UpdateFields();
1476  pWorkShell->LockExpFields();
1477 
1478  lcl_emitEvent(SfxEventHintId::SwEventFieldMergeFinished, STR_SW_EVENT_FIELD_MERGE_FINISHED, xWorkDocSh);
1479 
1480  // also emit MailMergeEvent on XInterface if possible
1481  const SwXMailMerge *pEvtSrc = GetMailMergeEvtSrc();
1482  if(pEvtSrc)
1483  {
1484  uno::Reference< uno::XInterface > xRef(
1485  static_cast<text::XMailMergeBroadcaster*>(const_cast<SwXMailMerge*>(pEvtSrc)) );
1486  text::MailMergeEvent aEvt( xRef, xWorkDocSh->GetModel() );
1487  pEvtSrc->LaunchMailMergeEvent( aEvt );
1488  }
1489 
1490  // working copy is merged - prepare final steps depending on merge options
1491 
1492  if( bCreateSingleFile )
1493  {
1494  assert( pTargetShell && "no target shell available!" );
1495 
1496  // prepare working copy and target to append
1497 
1498  pWorkDoc->RemoveInvisibleContent();
1499  // remove of invisible content has influence on page count and so on fields for page count,
1500  // therefore layout has to be updated before fields are converted to text
1501  pWorkShell->CalcLayout();
1502  pWorkShell->ConvertFieldsToText();
1503  pWorkShell->SetNumberingRestart();
1504  if( bSynchronizedDoc )
1505  {
1506  lcl_RemoveSectionLinks( *pWorkShell );
1507  }
1508 
1509  if ( (nMaxDumpDocs < 0) || (nDocNo <= nMaxDumpDocs) )
1510  lcl_SaveDebugDoc( xWorkDocSh, "WorkDoc", nDocNo );
1511 
1512  // append the working document to the target document
1513  if( targetDocPageCount % 2 == 1 )
1514  ++targetDocPageCount; // Docs always start on odd pages (so offset must be even).
1515  SwNodeIndex appendedDocStart = pTargetDoc->AppendDoc( *pWorkDoc,
1516  nStartingPageNo, !bWorkDocInitialized, targetDocPageCount, nDocNo);
1517  targetDocPageCount += pWorkShell->GetPageCnt();
1518 
1519  if ( (nMaxDumpDocs < 0) || (nDocNo <= nMaxDumpDocs) )
1520  lcl_SaveDebugDoc( xTargetDocShell.get(), "MergeDoc" );
1521 
1522  if (bMT_SHELL)
1523  {
1524  SwDocMergeInfo aMergeInfo;
1525  // Name of the mark is actually irrelevant, UNO bookmarks have internals names.
1526  aMergeInfo.startPageInTarget = pTargetDoc->getIDocumentMarkAccess()->makeMark(
1527  appendedDocStart, "", IDocumentMarkAccess::MarkType::UNO_BOOKMARK,
1529  aMergeInfo.nDBRow = nStartRow;
1530  rMergeDescriptor.pMailMergeConfigItem->AddMergedDocument( aMergeInfo );
1531  }
1532  }
1533  else
1534  {
1535  assert( bNeedsTempFiles );
1536  assert( pWorkShell->IsExpFieldsLocked() );
1537 
1538  // fields are locked, so it's fine to
1539  // restore the old / empty DB manager for save
1540  pWorkDoc->SetDBManager( pWorkDocOrigDBManager );
1541 
1542  // save merged document
1543  OUString sFileURL;
1544  if( !lcl_SaveDoc( aTempFileURL.get(), pStoreToFilter, pStoreToFilterOptions,
1545  &rMergeDescriptor.aSaveToFilterData, bIsPDFexport,
1546  xWorkDocSh, *pWorkShell, &sFileURL ) )
1547  {
1549  }
1550 
1551  // back to the MM DB manager
1552  pWorkDoc->SetDBManager( this );
1553 
1554  if( bMT_EMAIL && !IsMergeError() )
1555  {
1556  // schedule file for later removal
1557  aFilesToRemove.push_back( sFileURL );
1558 
1559  if( !SwMailMergeHelper::CheckMailAddress( sColumnData ) )
1560  {
1561  OSL_FAIL("invalid e-Mail address in database column");
1562  }
1563  else
1564  {
1565  uno::Reference< mail::XMailMessage > xMessage = lcl_CreateMailFromDoc(
1566  rMergeDescriptor, sFileURL, sColumnData, sMailBodyMimeType,
1567  sMailEncoding, pStoreToFilter->GetMimeType() );
1568  if( xMessage.is() )
1569  {
1570  osl::MutexGuard aGuard( m_pImpl->m_aAllEmailSendMutex );
1571  m_pImpl->m_xLastMessage.set( xMessage );
1572  xMailDispatcher->enqueueMailMessage( xMessage );
1573  if( !xMailDispatcher->isStarted() )
1574  xMailDispatcher->start();
1575  }
1576  }
1577  }
1578  }
1579  if( bCreateSingleFile || bIsPDFexport )
1580  {
1581  pWorkDoc->SetDBManager( pWorkDocOrigDBManager );
1582  xWorkDocSh->DoClose();
1583  xWorkDocSh = nullptr;
1584  }
1585  }
1586 
1587  bWorkDocInitialized = true;
1588  nDocNo++;
1589  nEndRow = m_pImpl->pMergeData ? m_pImpl->pMergeData->xResultSet->getRow() : 0;
1590 
1591  // Freeze the layouts of the target document after the first inserted
1592  // sub-document, to get the correct PageDesc.
1593  if(!bFreezedLayouts && bCreateSingleFile)
1594  {
1595  for ( auto aLayout : pTargetShell->GetDoc()->GetAllLayouts() )
1596  aLayout->FreezeLayout(true);
1597  bFreezedLayouts = true;
1598  }
1599  } while( IsMergeOk() &&
1600  ((bSynchronizedDoc && (nStartRow != nEndRow)) ? IsValidMergeRecord() : ToNextMergeRecord()));
1601 
1602  if ( xWorkDocSh.Is() && pWorkView->GetWrtShell().IsExpFieldsLocked() )
1603  {
1604  // Unlock document fields after merge complete
1605  pWorkView->GetWrtShell().UnlockExpFields();
1606  }
1607 
1608  if( !bCreateSingleFile )
1609  {
1610  if( bMT_PRINTER )
1612  if( !bIsPDFexport )
1613  {
1614  pWorkDoc->SetDBManager( pWorkDocOrigDBManager );
1615  xWorkDocSh->DoClose();
1616  }
1617  }
1618  else if( IsMergeOk() ) // && bCreateSingleFile
1619  {
1620  Application::Reschedule( true );
1621 
1622  // sw::DocumentLayoutManager::CopyLayoutFormat() did not generate
1623  // unique fly names, do it here once.
1624  pTargetDoc->SetInMailMerge(false);
1625  pTargetDoc->SetAllUniqueFlyNames();
1626 
1627  // Unfreeze target document layouts and correct all PageDescs.
1628  SAL_INFO( "sw.pageframe", "(MergeMailFiles pTargetShell->CalcLayout in" );
1629  pTargetShell->CalcLayout();
1630  SAL_INFO( "sw.pageframe", "MergeMailFiles pTargetShell->CalcLayout out)" );
1631  pTargetShell->GetViewOptions()->SetIdle( true );
1632  pTargetDoc->GetIDocumentUndoRedo().DoUndo( true );
1633  for ( auto aLayout : pTargetShell->GetDoc()->GetAllLayouts() )
1634  {
1635  aLayout->FreezeLayout(false);
1636  aLayout->AllCheckPageDescs();
1637  }
1638 
1639  Application::Reschedule( true );
1640 
1641  if( IsMergeOk() && bMT_FILE )
1642  {
1643  // save merged document
1644  assert( aTempFile.get() );
1645  INetURLObject aTempFileURL;
1646  if (sDescriptorPrefix.isEmpty() || !rMergeDescriptor.bPrefixIsFilename)
1647  aTempFileURL.SetURL( aTempFile->GetURL() );
1648  else
1649  {
1650  aTempFileURL.SetURL(sDescriptorPrefix);
1651  // remove the unneeded temporary file
1652  aTempFile->EnableKillingFile();
1653  }
1654  if( !lcl_SaveDoc( &aTempFileURL, pStoreToFilter,
1655  pStoreToFilterOptions, &rMergeDescriptor.aSaveToFilterData,
1656  bIsPDFexport, xTargetDocShell.get(), *pTargetShell ) )
1657  {
1659  }
1660  }
1661  else if( IsMergeOk() && bMT_PRINTER )
1662  {
1663  // print the target document
1664  uno::Sequence< beans::PropertyValue > aOptions( rMergeDescriptor.aPrintOptions );
1665  lcl_PreparePrinterOptions( rMergeDescriptor.aPrintOptions, aOptions );
1666  pTargetView->ExecPrint( aOptions, bIsMergeSilent, false/*bPrintAsync*/ );
1667  }
1668  }
1669 
1670  // we also show canceled documents, as long as there was no error
1671  if( !IsMergeError() && bMT_SHELL )
1672  // leave docshell available for caller (e.g. MM wizard)
1673  rMergeDescriptor.pMailMergeConfigItem->SetTargetView( pTargetView );
1674  else if( xTargetDocShell.is() )
1675  xTargetDocShell->DoClose();
1676 
1677  Application::Reschedule( true );
1678 
1679  if (xProgressDlg)
1680  {
1681  xProgressDlg->response(RET_OK);
1682  }
1683 
1684  // unlock all dispatchers
1685  pViewFrame = SfxViewFrame::GetFirst(pSourceDocSh);
1686  while (pViewFrame)
1687  {
1688  pViewFrame->GetDispatcher()->Lock(false);
1689  pViewFrame = SfxViewFrame::GetNext(*pViewFrame, pSourceDocSh);
1690  }
1691 
1692  SW_MOD()->SetView(&pSourceShell->GetView());
1693 
1694  if( xMailDispatcher.is() )
1695  {
1696  if( IsMergeOk() )
1697  {
1698  // TODO: Instead of polling via an AutoTimer, post an Idle event,
1699  // if the main loop has been made thread-safe.
1700  AutoTimer aEmailDispatcherPollTimer;
1701  aEmailDispatcherPollTimer.SetDebugName(
1702  "sw::SwDBManager aEmailDispatcherPollTimer" );
1703  aEmailDispatcherPollTimer.SetTimeout( 500 );
1704  aEmailDispatcherPollTimer.Start();
1705  while( IsMergeOk() && m_pImpl->m_xLastMessage.is() )
1707  aEmailDispatcherPollTimer.Stop();
1708  }
1709  xMailDispatcher->stop();
1710  xMailDispatcher->shutdown();
1711  }
1712 
1713  // remove the temporary files
1714  // has to be done after xMailDispatcher is finished, as mails may be
1715  // delivered as message attachments!
1716  for( const OUString &sFileURL : aFilesToRemove )
1717  SWUnoHelper::UCB_DeleteFile( sFileURL );
1718  }
1719  catch (const uno::Exception&)
1720  {
1721  if (xProgressDlg)
1722  {
1723  xProgressDlg->response(RET_CANCEL);
1724  }
1725  }
1726 
1727  return !IsMergeError();
1728 }
1729 
1731 {
1734 }
1735 
1736 // determine the column's Numberformat and transfer to the forwarded Formatter,
1737 // if applicable.
1738 sal_uLong SwDBManager::GetColumnFormat( const OUString& rDBName,
1739  const OUString& rTableName,
1740  const OUString& rColNm,
1741  SvNumberFormatter* pNFormatr,
1742  LanguageType nLanguage )
1743 {
1744  sal_uLong nRet = 0;
1745  if(pNFormatr)
1746  {
1747  uno::Reference< sdbc::XDataSource> xSource;
1748  uno::Reference< sdbc::XConnection> xConnection;
1749  bool bUseMergeData = false;
1750  uno::Reference< sdbcx::XColumnsSupplier> xColsSupp;
1751  bool bDisposeConnection = false;
1752  if(m_pImpl->pMergeData &&
1753  ((m_pImpl->pMergeData->sDataSource == rDBName && m_pImpl->pMergeData->sCommand == rTableName) ||
1754  (rDBName.isEmpty() && rTableName.isEmpty())))
1755  {
1756  xConnection = m_pImpl->pMergeData->xConnection;
1757  xSource = SwDBManager::getDataSourceAsParent(xConnection,rDBName);
1758  bUseMergeData = true;
1759  xColsSupp.set(m_pImpl->pMergeData->xResultSet, css::uno::UNO_QUERY);
1760  }
1761  if(!xConnection.is())
1762  {
1763  SwDBData aData;
1764  aData.sDataSource = rDBName;
1765  aData.sCommand = rTableName;
1766  aData.nCommandType = -1;
1767  SwDSParam* pParam = FindDSData(aData, false);
1768  if(pParam && pParam->xConnection.is())
1769  {
1770  xConnection = pParam->xConnection;
1771  xColsSupp.set(pParam->xResultSet, css::uno::UNO_QUERY);
1772  }
1773  else
1774  {
1775  xConnection = RegisterConnection( rDBName );
1776  bDisposeConnection = true;
1777  }
1778  if(bUseMergeData)
1779  m_pImpl->pMergeData->xConnection = xConnection;
1780  }
1781  bool bDispose = !xColsSupp.is();
1782  if(bDispose)
1783  {
1784  xColsSupp = SwDBManager::GetColumnSupplier(xConnection, rTableName);
1785  }
1786  if(xColsSupp.is())
1787  {
1788  uno::Reference<container::XNameAccess> xCols;
1789  try
1790  {
1791  xCols = xColsSupp->getColumns();
1792  }
1793  catch (const uno::Exception&)
1794  {
1795  TOOLS_WARN_EXCEPTION("sw.mailmerge", "Exception in getColumns()");
1796  }
1797  if(!xCols.is() || !xCols->hasByName(rColNm))
1798  return nRet;
1799  uno::Any aCol = xCols->getByName(rColNm);
1800  uno::Reference< beans::XPropertySet > xColumn;
1801  aCol >>= xColumn;
1802  nRet = GetColumnFormat(xSource, xConnection, xColumn, pNFormatr, nLanguage);
1803  if(bDispose)
1804  {
1805  ::comphelper::disposeComponent( xColsSupp );
1806  }
1807  if(bDisposeConnection)
1808  {
1809  ::comphelper::disposeComponent( xConnection );
1810  }
1811  }
1812  else
1813  nRet = pNFormatr->GetFormatIndex( NF_NUMBER_STANDARD, LANGUAGE_SYSTEM );
1814  }
1815  return nRet;
1816 }
1817 
1818 sal_uLong SwDBManager::GetColumnFormat( uno::Reference< sdbc::XDataSource> const & xSource_in,
1819  uno::Reference< sdbc::XConnection> const & xConnection,
1820  uno::Reference< beans::XPropertySet> const & xColumn,
1821  SvNumberFormatter* pNFormatr,
1822  LanguageType nLanguage )
1823 {
1824  auto xSource = xSource_in;
1825 
1826  // set the NumberFormat in the doc if applicable
1827  sal_uLong nRet = 0;
1828 
1829  if(!xSource.is())
1830  {
1831  uno::Reference<container::XChild> xChild(xConnection, uno::UNO_QUERY);
1832  if ( xChild.is() )
1833  xSource.set(xChild->getParent(), uno::UNO_QUERY);
1834  }
1835  if(xSource.is() && xConnection.is() && xColumn.is() && pNFormatr)
1836  {
1837  SvNumberFormatsSupplierObj* pNumFormat = new SvNumberFormatsSupplierObj( pNFormatr );
1838  uno::Reference< util::XNumberFormatsSupplier > xDocNumFormatsSupplier = pNumFormat;
1839  uno::Reference< util::XNumberFormats > xDocNumberFormats = xDocNumFormatsSupplier->getNumberFormats();
1840  uno::Reference< util::XNumberFormatTypes > xDocNumberFormatTypes(xDocNumberFormats, uno::UNO_QUERY);
1841 
1842  css::lang::Locale aLocale( LanguageTag( nLanguage ).getLocale());
1843 
1844  //get the number formatter of the data source
1845  uno::Reference<beans::XPropertySet> xSourceProps(xSource, uno::UNO_QUERY);
1846  uno::Reference< util::XNumberFormats > xNumberFormats;
1847  if(xSourceProps.is())
1848  {
1849  uno::Any aFormats = xSourceProps->getPropertyValue("NumberFormatsSupplier");
1850  if(aFormats.hasValue())
1851  {
1852  uno::Reference<util::XNumberFormatsSupplier> xSuppl;
1853  aFormats >>= xSuppl;
1854  if(xSuppl.is())
1855  {
1856  xNumberFormats = xSuppl->getNumberFormats();
1857  }
1858  }
1859  }
1860  bool bUseDefault = true;
1861  try
1862  {
1863  uno::Any aFormatKey = xColumn->getPropertyValue("FormatKey");
1864  if(aFormatKey.hasValue())
1865  {
1866  sal_Int32 nFormat = 0;
1867  aFormatKey >>= nFormat;
1868  if(xNumberFormats.is())
1869  {
1870  try
1871  {
1872  uno::Reference<beans::XPropertySet> xNumProps = xNumberFormats->getByKey( nFormat );
1873  uno::Any aFormatString = xNumProps->getPropertyValue("FormatString");
1874  uno::Any aLocaleVal = xNumProps->getPropertyValue("Locale");
1875  OUString sFormat;
1876  aFormatString >>= sFormat;
1877  lang::Locale aLoc;
1878  aLocaleVal >>= aLoc;
1879  nFormat = xDocNumberFormats->queryKey( sFormat, aLoc, false );
1880  if(NUMBERFORMAT_ENTRY_NOT_FOUND == sal::static_int_cast< sal_uInt32, sal_Int32>(nFormat))
1881  nFormat = xDocNumberFormats->addNew( sFormat, aLoc );
1882  nRet = nFormat;
1883  bUseDefault = false;
1884  }
1885  catch (const uno::Exception&)
1886  {
1887  TOOLS_WARN_EXCEPTION("sw.mailmerge", "illegal number format key");
1888  }
1889  }
1890  }
1891  }
1892  catch(const uno::Exception&)
1893  {
1894  SAL_WARN("sw.mailmerge", "no FormatKey property found");
1895  }
1896  if(bUseDefault)
1897  nRet = dbtools::getDefaultNumberFormat(xColumn, xDocNumberFormatTypes, aLocale);
1898  }
1899  return nRet;
1900 }
1901 
1902 sal_Int32 SwDBManager::GetColumnType( const OUString& rDBName,
1903  const OUString& rTableName,
1904  const OUString& rColNm )
1905 {
1906  sal_Int32 nRet = sdbc::DataType::SQLNULL;
1907  SwDBData aData;
1908  aData.sDataSource = rDBName;
1909  aData.sCommand = rTableName;
1910  aData.nCommandType = -1;
1911  SwDSParam* pParam = FindDSData(aData, false);
1912  uno::Reference< sdbc::XConnection> xConnection;
1913  uno::Reference< sdbcx::XColumnsSupplier > xColsSupp;
1914  bool bDispose = false;
1915  if(pParam && pParam->xConnection.is())
1916  {
1917  xConnection = pParam->xConnection;
1918  xColsSupp.set( pParam->xResultSet, uno::UNO_QUERY );
1919  }
1920  else
1921  {
1922  xConnection = RegisterConnection( rDBName );
1923  }
1924  if( !xColsSupp.is() )
1925  {
1926  xColsSupp = SwDBManager::GetColumnSupplier(xConnection, rTableName);
1927  bDispose = true;
1928  }
1929  if(xColsSupp.is())
1930  {
1931  uno::Reference<container::XNameAccess> xCols = xColsSupp->getColumns();
1932  if(xCols->hasByName(rColNm))
1933  {
1934  uno::Any aCol = xCols->getByName(rColNm);
1935  uno::Reference<beans::XPropertySet> xCol;
1936  aCol >>= xCol;
1937  uno::Any aType = xCol->getPropertyValue("Type");
1938  aType >>= nRet;
1939  }
1940  if(bDispose)
1941  ::comphelper::disposeComponent( xColsSupp );
1942  }
1943  return nRet;
1944 }
1945 
1946 uno::Reference< sdbc::XConnection> SwDBManager::GetConnection(const OUString& rDataSource,
1947  uno::Reference<sdbc::XDataSource>& rxSource, const SwView *pView)
1948 {
1949  uno::Reference< sdbc::XConnection> xConnection;
1950  uno::Reference< uno::XComponentContext > xContext( ::comphelper::getProcessComponentContext() );
1951  try
1952  {
1953  uno::Reference<sdb::XCompletedConnection> xComplConnection(dbtools::getDataSource(rDataSource, xContext), uno::UNO_QUERY);
1954  if ( xComplConnection.is() )
1955  {
1956  rxSource.set(xComplConnection, uno::UNO_QUERY);
1957  weld::Window* pWindow = pView ? pView->GetFrameWeld() : nullptr;
1958  uno::Reference< task::XInteractionHandler > xHandler( task::InteractionHandler::createWithParent(xContext, pWindow ? pWindow->GetXWindow() : nullptr), uno::UNO_QUERY_THROW );
1959  xConnection = xComplConnection->connectWithCompletion( xHandler );
1960  }
1961  }
1962  catch(const uno::Exception&)
1963  {
1964  }
1965 
1966  return xConnection;
1967 }
1968 
1969 uno::Reference< sdbcx::XColumnsSupplier> SwDBManager::GetColumnSupplier(uno::Reference<sdbc::XConnection> const & xConnection,
1970  const OUString& rTableOrQuery,
1971  SwDBSelect eTableOrQuery)
1972 {
1973  uno::Reference< sdbcx::XColumnsSupplier> xRet;
1974  try
1975  {
1976  if(eTableOrQuery == SwDBSelect::UNKNOWN)
1977  {
1978  //search for a table with the given command name
1979  uno::Reference<sdbcx::XTablesSupplier> xTSupplier(xConnection, uno::UNO_QUERY);
1980  if(xTSupplier.is())
1981  {
1982  uno::Reference<container::XNameAccess> xTables = xTSupplier->getTables();
1983  eTableOrQuery = xTables->hasByName(rTableOrQuery) ?
1985  }
1986  }
1987  sal_Int32 nCommandType = SwDBSelect::TABLE == eTableOrQuery ?
1988  sdb::CommandType::TABLE : sdb::CommandType::QUERY;
1989  uno::Reference< lang::XMultiServiceFactory > xMgr( ::comphelper::getProcessServiceFactory() );
1990  uno::Reference<sdbc::XRowSet> xRowSet(xMgr->createInstance("com.sun.star.sdb.RowSet"), uno::UNO_QUERY);
1991 
1992  OUString sDataSource;
1993  uno::Reference<sdbc::XDataSource> xSource = SwDBManager::getDataSourceAsParent(xConnection, sDataSource);
1994  uno::Reference<beans::XPropertySet> xSourceProperties(xSource, uno::UNO_QUERY);
1995  if(xSourceProperties.is())
1996  {
1997  xSourceProperties->getPropertyValue("Name") >>= sDataSource;
1998  }
1999 
2000  uno::Reference<beans::XPropertySet> xRowProperties(xRowSet, uno::UNO_QUERY);
2001  xRowProperties->setPropertyValue("DataSourceName", uno::makeAny(sDataSource));
2002  xRowProperties->setPropertyValue("Command", uno::makeAny(rTableOrQuery));
2003  xRowProperties->setPropertyValue("CommandType", uno::makeAny(nCommandType));
2004  xRowProperties->setPropertyValue("FetchSize", uno::makeAny(sal_Int32(10)));
2005  xRowProperties->setPropertyValue("ActiveConnection", uno::makeAny(xConnection));
2006  xRowSet->execute();
2007  xRet.set( xRowSet, uno::UNO_QUERY );
2008  }
2009  catch (const uno::Exception&)
2010  {
2011  TOOLS_WARN_EXCEPTION("sw.mailmerge", "Exception in SwDBManager::GetColumnSupplier");
2012  }
2013 
2014  return xRet;
2015 }
2016 
2017 OUString SwDBManager::GetDBField(uno::Reference<beans::XPropertySet> const & xColumnProps,
2018  const SwDBFormatData& rDBFormatData,
2019  double* pNumber)
2020 {
2021  uno::Reference< sdb::XColumn > xColumn(xColumnProps, uno::UNO_QUERY);
2022  OUString sRet;
2023  assert( xColumn.is() && "SwDBManager::::ImportDBField: illegal arguments" );
2024  if(!xColumn.is())
2025  return sRet;
2026 
2027  uno::Any aType = xColumnProps->getPropertyValue("Type");
2028  sal_Int32 eDataType = sdbc::DataType::SQLNULL;
2029  aType >>= eDataType;
2030  switch(eDataType)
2031  {
2032  case sdbc::DataType::CHAR:
2033  case sdbc::DataType::VARCHAR:
2034  case sdbc::DataType::LONGVARCHAR:
2035  try
2036  {
2037  sRet = xColumn->getString();
2038  sRet = sRet.replace( '\xb', '\n' ); // MSWord uses \xb as a newline
2039  }
2040  catch(const sdbc::SQLException&)
2041  {
2042  }
2043  break;
2044  case sdbc::DataType::BIT:
2045  case sdbc::DataType::BOOLEAN:
2046  case sdbc::DataType::TINYINT:
2047  case sdbc::DataType::SMALLINT:
2048  case sdbc::DataType::INTEGER:
2049  case sdbc::DataType::BIGINT:
2050  case sdbc::DataType::FLOAT:
2051  case sdbc::DataType::REAL:
2052  case sdbc::DataType::DOUBLE:
2053  case sdbc::DataType::NUMERIC:
2054  case sdbc::DataType::DECIMAL:
2055  case sdbc::DataType::DATE:
2056  case sdbc::DataType::TIME:
2057  case sdbc::DataType::TIMESTAMP:
2058  {
2059 
2060  try
2061  {
2063  xColumnProps,
2064  rDBFormatData.xFormatter,
2065  rDBFormatData.aLocale,
2066  rDBFormatData.aNullDate);
2067  if (pNumber)
2068  {
2069  double fVal = xColumn->getDouble();
2070  if(!xColumn->wasNull())
2071  {
2072  *pNumber = fVal;
2073  }
2074  }
2075  }
2076  catch (const uno::Exception&)
2077  {
2078  TOOLS_WARN_EXCEPTION("sw.mailmerge", "");
2079  }
2080 
2081  }
2082  break;
2083  }
2084 
2085  return sRet;
2086 }
2087 
2088 // checks if a desired data source table or query is open
2089 bool SwDBManager::IsDataSourceOpen(const OUString& rDataSource,
2090  const OUString& rTableOrQuery, bool bMergeShell)
2091 {
2092  if(m_pImpl->pMergeData)
2093  {
2094  return ((rDataSource == m_pImpl->pMergeData->sDataSource
2095  && rTableOrQuery == m_pImpl->pMergeData->sCommand)
2096  || (rDataSource.isEmpty() && rTableOrQuery.isEmpty()))
2097  && m_pImpl->pMergeData->xResultSet.is();
2098  }
2099  else if(!bMergeShell)
2100  {
2101  SwDBData aData;
2102  aData.sDataSource = rDataSource;
2103  aData.sCommand = rTableOrQuery;
2104  aData.nCommandType = -1;
2105  SwDSParam* pFound = FindDSData(aData, false);
2106  return (pFound && pFound->xResultSet.is());
2107  }
2108  return false;
2109 }
2110 
2111 // read column data at a specified position
2112 bool SwDBManager::GetColumnCnt(const OUString& rSourceName, const OUString& rTableName,
2113  const OUString& rColumnName, sal_uInt32 nAbsRecordId,
2114  LanguageType nLanguage,
2115  OUString& rResult, double* pNumber)
2116 {
2117  bool bRet = false;
2118  SwDSParam* pFound = nullptr;
2119  //check if it's the merge data source
2120  if(m_pImpl->pMergeData &&
2121  rSourceName == m_pImpl->pMergeData->sDataSource &&
2122  rTableName == m_pImpl->pMergeData->sCommand)
2123  {
2124  pFound = m_pImpl->pMergeData.get();
2125  }
2126  else
2127  {
2128  SwDBData aData;
2129  aData.sDataSource = rSourceName;
2130  aData.sCommand = rTableName;
2131  aData.nCommandType = -1;
2132  pFound = FindDSData(aData, false);
2133  }
2134  if (!pFound)
2135  return false;
2136  //check validity of supplied record Id
2137  if(pFound->aSelection.hasElements())
2138  {
2139  //the destination has to be an element of the selection
2140  bool bFound = std::any_of(pFound->aSelection.begin(), pFound->aSelection.end(),
2141  [nAbsRecordId](const uno::Any& rSelection) {
2142  sal_Int32 nSelection = 0;
2143  rSelection >>= nSelection;
2144  return nSelection == static_cast<sal_Int32>(nAbsRecordId);
2145  });
2146  if(!bFound)
2147  return false;
2148  }
2149  if( pFound->HasValidRecord() )
2150  {
2151  sal_Int32 nOldRow = 0;
2152  try
2153  {
2154  nOldRow = pFound->xResultSet->getRow();
2155  }
2156  catch(const uno::Exception&)
2157  {
2158  return false;
2159  }
2160  //position to the desired index
2161  bool bMove = true;
2162  if ( nOldRow != static_cast<sal_Int32>(nAbsRecordId) )
2163  bMove = lcl_MoveAbsolute(pFound, nAbsRecordId);
2164  if(bMove)
2165  bRet = lcl_GetColumnCnt(pFound, rColumnName, nLanguage, rResult, pNumber);
2166  if ( nOldRow != static_cast<sal_Int32>(nAbsRecordId) )
2167  lcl_MoveAbsolute(pFound, nOldRow);
2168  }
2169  return bRet;
2170 }
2171 
2172 // reads the column data at the current position
2173 bool SwDBManager::GetMergeColumnCnt(const OUString& rColumnName, LanguageType nLanguage,
2174  OUString &rResult, double *pNumber)
2175 {
2176  if( !IsValidMergeRecord() )
2177  {
2178  rResult.clear();
2179  return false;
2180  }
2181 
2182  bool bRet = lcl_GetColumnCnt(m_pImpl->pMergeData.get(), rColumnName, nLanguage, rResult, pNumber);
2183  return bRet;
2184 }
2185 
2187 {
2188  assert( m_pImpl->pMergeData && m_pImpl->pMergeData->xResultSet.is() && "no data source in merge" );
2189  return lcl_ToNextRecord( m_pImpl->pMergeData.get() );
2190 }
2191 
2193  LanguageType nLanguage, SwCalc &rCalc )
2194 {
2195  if( !IsValidMergeRecord() )
2196  return false;
2197 
2198  uno::Reference< sdbcx::XColumnsSupplier > xColsSupp( m_pImpl->pMergeData->xResultSet, uno::UNO_QUERY );
2199  if( !xColsSupp.is() )
2200  return false;
2201 
2202  {
2203  uno::Reference<container::XNameAccess> xCols = xColsSupp->getColumns();
2204  const uno::Sequence<OUString> aColNames = xCols->getElementNames();
2205  OUString aString;
2206 
2207  // add the "record number" variable, as SwCalc::VarLook would.
2208  rCalc.VarChange( GetAppCharClass().lowercase(
2210 
2211  for( const OUString& rColName : aColNames )
2212  {
2213  // get the column type
2214  sal_Int32 nColumnType = sdbc::DataType::SQLNULL;
2215  uno::Any aCol = xCols->getByName( rColName );
2216  uno::Reference<beans::XPropertySet> xColumnProps;
2217  aCol >>= xColumnProps;
2218  uno::Any aType = xColumnProps->getPropertyValue( "Type" );
2219  aType >>= nColumnType;
2220  double aNumber = DBL_MAX;
2221 
2222  lcl_GetColumnCnt( m_pImpl->pMergeData.get(), xColumnProps, nLanguage, aString, &aNumber );
2223 
2224  sal_uInt32 nFormat = GetColumnFormat( m_pImpl->pMergeData->sDataSource,
2225  m_pImpl->pMergeData->sCommand,
2226  rColName, pDocFormatter, nLanguage );
2227  // aNumber is overwritten by SwDBField::FormatValue, so store initial status
2228  bool colIsNumber = aNumber != DBL_MAX;
2229  bool bValidValue = SwDBField::FormatValue( pDocFormatter, aString, nFormat,
2230  aNumber, nColumnType );
2231  if( colIsNumber )
2232  {
2233  if( bValidValue )
2234  {
2235  SwSbxValue aValue;
2236  aValue.PutDouble( aNumber );
2237  aValue.SetDBvalue( true );
2238  SAL_INFO( "sw.ui", "'" << rColName << "': " << aNumber << " / " << aString );
2239  rCalc.VarChange( rColName, aValue );
2240  }
2241  }
2242  else
2243  {
2244  SwSbxValue aValue;
2245  aValue.PutString( aString );
2246  aValue.SetDBvalue( true );
2247  SAL_INFO( "sw.ui", "'" << rColName << "': " << aString );
2248  rCalc.VarChange( rColName, aValue );
2249  }
2250  }
2251  }
2252 
2253  return true;
2254 }
2255 
2257  const OUString& rDataSource, const OUString& rCommand)
2258 {
2259  SwDSParam* pFound = nullptr;
2260  if(m_pImpl->pMergeData &&
2261  rDataSource == m_pImpl->pMergeData->sDataSource &&
2262  rCommand == m_pImpl->pMergeData->sCommand)
2263  {
2264  pFound = m_pImpl->pMergeData.get();
2265  }
2266  else
2267  {
2268  SwDBData aData;
2269  aData.sDataSource = rDataSource;
2270  aData.sCommand = rCommand;
2271  aData.nCommandType = -1;
2272  pFound = FindDSData(aData, false);
2273  }
2274  lcl_ToNextRecord( pFound );
2275 }
2276 
2277 static bool lcl_ToNextRecord( SwDSParam* pParam, const SwDBNextRecord action )
2278 {
2279  bool bRet = true;
2280 
2281  assert( SwDBNextRecord::NEXT == action ||
2282  (SwDBNextRecord::FIRST == action && pParam) );
2283  if( nullptr == pParam )
2284  return false;
2285 
2286  if( action == SwDBNextRecord::FIRST )
2287  {
2288  pParam->nSelectionIndex = 0;
2289  pParam->bEndOfDB = false;
2290  }
2291 
2292  if( !pParam->HasValidRecord() )
2293  return false;
2294 
2295  try
2296  {
2297  if( pParam->aSelection.hasElements() )
2298  {
2299  if( pParam->nSelectionIndex >= pParam->aSelection.getLength() )
2300  pParam->bEndOfDB = true;
2301  else
2302  {
2303  sal_Int32 nPos = 0;
2304  pParam->aSelection.getConstArray()[ pParam->nSelectionIndex ] >>= nPos;
2305  pParam->bEndOfDB = !pParam->xResultSet->absolute( nPos );
2306  }
2307  }
2308  else if( action == SwDBNextRecord::FIRST )
2309  {
2310  pParam->bEndOfDB = !pParam->xResultSet->first();
2311  }
2312  else
2313  {
2314  sal_Int32 nBefore = pParam->xResultSet->getRow();
2315  pParam->bEndOfDB = !pParam->xResultSet->next();
2316  if( !pParam->bEndOfDB && nBefore == pParam->xResultSet->getRow() )
2317  {
2318  // next returned true but it didn't move
2319  ::dbtools::throwFunctionSequenceException( pParam->xResultSet );
2320  }
2321  }
2322 
2323  ++pParam->nSelectionIndex;
2324  bRet = !pParam->bEndOfDB;
2325  }
2326  catch( const uno::Exception & )
2327  {
2328  // we allow merging with empty databases, so don't warn on init
2330  "sw.mailmerge", "exception in ToNextRecord()");
2331  pParam->bEndOfDB = true;
2332  bRet = false;
2333  }
2334  return bRet;
2335 }
2336 
2337 // synchronized labels contain a next record field at their end
2338 // to assure that the next page can be created in mail merge
2339 // the cursor position must be validated
2341 {
2342  return( m_pImpl->pMergeData && m_pImpl->pMergeData->HasValidRecord() );
2343 }
2344 
2346 {
2347  sal_uInt32 nRet = 0;
2348  assert( m_pImpl->pMergeData &&
2349  m_pImpl->pMergeData->xResultSet.is() && "no data source in merge" );
2350  if(!m_pImpl->pMergeData || !m_pImpl->pMergeData->xResultSet.is())
2351  return 0;
2352  try
2353  {
2354  nRet = m_pImpl->pMergeData->xResultSet->getRow();
2355  }
2356  catch(const uno::Exception&)
2357  {
2358  }
2359  return nRet;
2360 }
2361 
2362 bool SwDBManager::ToRecordId(sal_Int32 nSet)
2363 {
2364  assert( m_pImpl->pMergeData &&
2365  m_pImpl->pMergeData->xResultSet.is() && "no data source in merge" );
2366  if(!m_pImpl->pMergeData || !m_pImpl->pMergeData->xResultSet.is()|| nSet < 0)
2367  return false;
2368  bool bRet = false;
2369  sal_Int32 nAbsPos = nSet;
2370  assert(nAbsPos >= 0);
2371  bRet = lcl_MoveAbsolute(m_pImpl->pMergeData.get(), nAbsPos);
2372  m_pImpl->pMergeData->bEndOfDB = !bRet;
2373  return bRet;
2374 }
2375 
2376 bool SwDBManager::OpenDataSource(const OUString& rDataSource, const OUString& rTableOrQuery)
2377 {
2378  SwDBData aData;
2379  aData.sDataSource = rDataSource;
2380  aData.sCommand = rTableOrQuery;
2381  aData.nCommandType = -1;
2382 
2383  SwDSParam* pFound = FindDSData(aData, true);
2384  if(pFound->xResultSet.is())
2385  return true;
2386  SwDSParam* pParam = FindDSConnection(rDataSource, false);
2387  if(pParam && pParam->xConnection.is())
2388  pFound->xConnection = pParam->xConnection;
2389  if(pFound->xConnection.is())
2390  {
2391  try
2392  {
2393  uno::Reference< sdbc::XDatabaseMetaData > xMetaData = pFound->xConnection->getMetaData();
2394  try
2395  {
2396  pFound->bScrollable = xMetaData
2397  ->supportsResultSetType(sal_Int32(sdbc::ResultSetType::SCROLL_INSENSITIVE));
2398  }
2399  catch(const uno::Exception&)
2400  {
2401  // DB driver may not be ODBC 3.0 compliant
2402  pFound->bScrollable = true;
2403  }
2404  pFound->xStatement = pFound->xConnection->createStatement();
2405  OUString aQuoteChar = xMetaData->getIdentifierQuoteString();
2406  OUString sStatement("SELECT * FROM ");
2407  sStatement = "SELECT * FROM ";
2408  sStatement += aQuoteChar;
2409  sStatement += rTableOrQuery;
2410  sStatement += aQuoteChar;
2411  pFound->xResultSet = pFound->xStatement->executeQuery( sStatement );
2412 
2413  //after executeQuery the cursor must be positioned
2414  pFound->bEndOfDB = !pFound->xResultSet->next();
2415  ++pFound->nSelectionIndex;
2416  }
2417  catch (const uno::Exception&)
2418  {
2419  pFound->xResultSet = nullptr;
2420  pFound->xStatement = nullptr;
2421  pFound->xConnection = nullptr;
2422  }
2423  }
2424  return pFound->xResultSet.is();
2425 }
2426 
2427 uno::Reference< sdbc::XConnection> const & SwDBManager::RegisterConnection(OUString const& rDataSource)
2428 {
2429  SwDSParam* pFound = SwDBManager::FindDSConnection(rDataSource, true);
2430  uno::Reference< sdbc::XDataSource> xSource;
2431  if(!pFound->xConnection.is())
2432  {
2433  SwView* pView = (m_pDoc && m_pDoc->GetDocShell()) ? m_pDoc->GetDocShell()->GetView() : nullptr;
2434  pFound->xConnection = SwDBManager::GetConnection(rDataSource, xSource, pView);
2435  try
2436  {
2437  uno::Reference<lang::XComponent> xComponent(pFound->xConnection, uno::UNO_QUERY);
2438  if(xComponent.is())
2439  xComponent->addEventListener(m_pImpl->m_xDisposeListener.get());
2440  }
2441  catch(const uno::Exception&)
2442  {
2443  }
2444  }
2445  return pFound->xConnection;
2446 }
2447 
2449  const OUString& rDataSource, const OUString& rTableOrQuery, sal_Int32 nCommandType)
2450 {
2451  sal_uInt32 nRet = 0xffffffff;
2452  //check for merge data source first
2453  if(m_pImpl->pMergeData &&
2454  ((rDataSource == m_pImpl->pMergeData->sDataSource &&
2455  rTableOrQuery == m_pImpl->pMergeData->sCommand) ||
2456  (rDataSource.isEmpty() && rTableOrQuery.isEmpty())) &&
2457  (nCommandType == -1 || nCommandType == m_pImpl->pMergeData->nCommandType) &&
2458  m_pImpl->pMergeData->xResultSet.is())
2459  {
2460  nRet = GetSelectedRecordId();
2461  }
2462  else
2463  {
2464  SwDBData aData;
2465  aData.sDataSource = rDataSource;
2466  aData.sCommand = rTableOrQuery;
2467  aData.nCommandType = nCommandType;
2468  SwDSParam* pFound = FindDSData(aData, false);
2469  if(pFound && pFound->xResultSet.is())
2470  {
2471  try
2472  { //if a selection array is set the current row at the result set may not be set yet
2473  if(pFound->aSelection.hasElements())
2474  {
2475  sal_Int32 nSelIndex = pFound->nSelectionIndex;
2476  if(nSelIndex >= pFound->aSelection.getLength())
2477  nSelIndex = pFound->aSelection.getLength() -1;
2478  pFound->aSelection.getConstArray()[nSelIndex] >>= nRet;
2479 
2480  }
2481  else
2482  nRet = pFound->xResultSet->getRow();
2483  }
2484  catch(const uno::Exception&)
2485  {
2486  }
2487  }
2488  }
2489  return nRet;
2490 }
2491 
2492 // close all data sources - after fields were updated
2493 void SwDBManager::CloseAll(bool bIncludingMerge)
2494 {
2495  //the only thing done here is to reset the selection index
2496  //all connections stay open
2497  for (auto & pParam : m_DataSourceParams)
2498  {
2499  if (bIncludingMerge || pParam.get() != m_pImpl->pMergeData.get())
2500  {
2501  pParam->nSelectionIndex = 0;
2502  pParam->bEndOfDB = false;
2503  try
2504  {
2505  if(!m_bInMerge && pParam->xResultSet.is())
2506  pParam->xResultSet->first();
2507  }
2508  catch(const uno::Exception&)
2509  {}
2510  }
2511  }
2512 }
2513 
2514 SwDSParam* SwDBManager::FindDSData(const SwDBData& rData, bool bCreate)
2515 {
2516  //prefer merge data if available
2517  if(m_pImpl->pMergeData &&
2518  ((rData.sDataSource == m_pImpl->pMergeData->sDataSource &&
2519  rData.sCommand == m_pImpl->pMergeData->sCommand) ||
2520  (rData.sDataSource.isEmpty() && rData.sCommand.isEmpty())) &&
2521  (rData.nCommandType == -1 || rData.nCommandType == m_pImpl->pMergeData->nCommandType ||
2522  (bCreate && m_pImpl->pMergeData->nCommandType == -1)))
2523  {
2524  return m_pImpl->pMergeData.get();
2525  }
2526 
2527  SwDSParam* pFound = nullptr;
2528  for (size_t nPos = m_DataSourceParams.size(); nPos; nPos--)
2529  {
2530  SwDSParam* pParam = m_DataSourceParams[nPos - 1].get();
2531  if(rData.sDataSource == pParam->sDataSource &&
2532  rData.sCommand == pParam->sCommand &&
2533  (rData.nCommandType == -1 || rData.nCommandType == pParam->nCommandType ||
2534  (bCreate && pParam->nCommandType == -1)))
2535  {
2536  // calls from the calculator may add a connection with an invalid commandtype
2537  //later added "real" data base connections have to re-use the already available
2538  //DSData and set the correct CommandType
2539  if(bCreate && pParam->nCommandType == -1)
2540  pParam->nCommandType = rData.nCommandType;
2541  pFound = pParam;
2542  break;
2543  }
2544  }
2545  if(bCreate && !pFound)
2546  {
2547  pFound = new SwDSParam(rData);
2548  m_DataSourceParams.push_back(std::unique_ptr<SwDSParam>(pFound));
2549  try
2550  {
2551  uno::Reference<lang::XComponent> xComponent(pFound->xConnection, uno::UNO_QUERY);
2552  if(xComponent.is())
2553  xComponent->addEventListener(m_pImpl->m_xDisposeListener.get());
2554  }
2555  catch(const uno::Exception&)
2556  {
2557  }
2558  }
2559  return pFound;
2560 }
2561 
2562 SwDSParam* SwDBManager::FindDSConnection(const OUString& rDataSource, bool bCreate)
2563 {
2564  //prefer merge data if available
2565  if(m_pImpl->pMergeData && rDataSource == m_pImpl->pMergeData->sDataSource )
2566  {
2567  SetAsUsed(rDataSource);
2568  return m_pImpl->pMergeData.get();
2569  }
2570  SwDSParam* pFound = nullptr;
2571  for (const auto & pParam : m_DataSourceParams)
2572  {
2573  if(rDataSource == pParam->sDataSource)
2574  {
2575  SetAsUsed(rDataSource);
2576  pFound = pParam.get();
2577  break;
2578  }
2579  }
2580  if(bCreate && !pFound)
2581  {
2582  SwDBData aData;
2583  aData.sDataSource = rDataSource;
2584  pFound = new SwDSParam(aData);
2585  SetAsUsed(rDataSource);
2586  m_DataSourceParams.push_back(std::unique_ptr<SwDSParam>(pFound));
2587  try
2588  {
2589  uno::Reference<lang::XComponent> xComponent(pFound->xConnection, uno::UNO_QUERY);
2590  if(xComponent.is())
2591  xComponent->addEventListener(m_pImpl->m_xDisposeListener.get());
2592  }
2593  catch(const uno::Exception&)
2594  {
2595  }
2596  }
2597  return pFound;
2598 }
2599 
2601 {
2602  return SW_MOD()->GetDBConfig()->GetAddressSource();
2603 }
2604 
2605 uno::Sequence<OUString> SwDBManager::GetExistingDatabaseNames()
2606 {
2607  uno::Reference<uno::XComponentContext> xContext( ::comphelper::getProcessComponentContext() );
2608  uno::Reference<sdb::XDatabaseContext> xDBContext = sdb::DatabaseContext::create(xContext);
2609  return xDBContext->getElementNames();
2610 }
2611 
2612 namespace sw
2613 {
2615 {
2616  OUString sExt(rURL.GetFileExtension());
2618 
2619  if (sExt == "odb")
2620  {
2621  type = DBConnURIType::ODB;
2622  }
2623  else if (sExt.equalsIgnoreAsciiCase("sxc")
2624  || sExt.equalsIgnoreAsciiCase("ods")
2625  || sExt.equalsIgnoreAsciiCase("xls")
2626  || sExt.equalsIgnoreAsciiCase("xlsx"))
2627  {
2628  type = DBConnURIType::CALC;
2629  }
2630  else if (sExt.equalsIgnoreAsciiCase("sxw") || sExt.equalsIgnoreAsciiCase("odt") || sExt.equalsIgnoreAsciiCase("doc") || sExt.equalsIgnoreAsciiCase("docx"))
2631  {
2632  type = DBConnURIType::WRITER;
2633  }
2634  else if (sExt.equalsIgnoreAsciiCase("dbf"))
2635  {
2636  type = DBConnURIType::DBASE;
2637  }
2638  else if (sExt.equalsIgnoreAsciiCase("csv") || sExt.equalsIgnoreAsciiCase("txt"))
2639  {
2640  type = DBConnURIType::FLAT;
2641  }
2642 #ifdef _WIN32
2643  else if (sExt.equalsIgnoreAsciiCase("mdb") || sExt.equalsIgnoreAsciiCase("mde"))
2644  {
2645  type = DBConnURIType::MSJET;
2646  }
2647  else if (sExt.equalsIgnoreAsciiCase("accdb") || sExt.equalsIgnoreAsciiCase("accde"))
2648  {
2649  type = DBConnURIType::MSACE;
2650  }
2651 #endif
2652  return type;
2653 }
2654 }
2655 
2656 namespace
2657 {
2658 uno::Any GetDBunoURI(const INetURLObject &rURL, DBConnURIType& rType)
2659 {
2660  uno::Any aURLAny;
2661 
2662  if (rType == DBConnURIType::UNKNOWN)
2663  rType = GetDBunoType(rURL);
2664 
2665  switch (rType) {
2666  case DBConnURIType::UNKNOWN:
2667  case DBConnURIType::ODB:
2668  break;
2669  case DBConnURIType::CALC:
2670  {
2671  OUString sDBURL("sdbc:calc:");
2673  aURLAny <<= sDBURL;
2674  }
2675  break;
2676  case DBConnURIType::WRITER:
2677  {
2678  OUString sDBURL("sdbc:writer:");
2680  aURLAny <<= sDBURL;
2681  }
2682  break;
2683  case DBConnURIType::DBASE:
2684  {
2685  INetURLObject aUrlTmp(rURL);
2686  aUrlTmp.removeSegment();
2687  aUrlTmp.removeFinalSlash();
2688  OUString sDBURL("sdbc:dbase:");
2689  sDBURL += aUrlTmp.GetMainURL(INetURLObject::DecodeMechanism::NONE);
2690  aURLAny <<= sDBURL;
2691  }
2692  break;
2693  case DBConnURIType::FLAT:
2694  {
2695  INetURLObject aUrlTmp(rURL);
2696  aUrlTmp.removeSegment();
2697  aUrlTmp.removeFinalSlash();
2698  OUString sDBURL("sdbc:flat:");
2699  //only the 'path' has to be added
2700  sDBURL += aUrlTmp.GetMainURL(INetURLObject::DecodeMechanism::NONE);
2701  aURLAny <<= sDBURL;
2702  }
2703  break;
2704  case DBConnURIType::MSJET:
2705 #ifdef _WIN32
2706  {
2707  OUString sDBURL("sdbc:ado:access:PROVIDER=Microsoft.Jet.OLEDB.4.0;DATA SOURCE=");
2708  sDBURL += rURL.PathToFileName();
2709  aURLAny <<= sDBURL;
2710  }
2711 #endif
2712  break;
2713  case DBConnURIType::MSACE:
2714 #ifdef _WIN32
2715  {
2716  OUString sDBURL("sdbc:ado:PROVIDER=Microsoft.ACE.OLEDB.12.0;DATA SOURCE=");
2717  sDBURL += rURL.PathToFileName();
2718  aURLAny <<= sDBURL;
2719  }
2720 #endif
2721  break;
2722  }
2723  return aURLAny;
2724 }
2725 
2727 OUString getOwnURL(SfxObjectShell const * pDocShell)
2728 {
2729  OUString aRet;
2730 
2731  if (!pDocShell)
2732  return aRet;
2733 
2734  const INetURLObject& rURLObject = pDocShell->GetMedium()->GetURLObject();
2736  return aRet;
2737 }
2738 
2745 OUString LoadAndRegisterDataSource_Impl(DBConnURIType type, const uno::Reference< beans::XPropertySet > *pSettings,
2746  const INetURLObject &rURL, const OUString *pDestDir, SfxObjectShell* pDocShell)
2747 {
2748  OUString sExt(rURL.GetFileExtension());
2749  uno::Any aTableFilterAny;
2750  uno::Any aSuppressVersionsAny;
2751  uno::Any aInfoAny;
2752  bool bStore = true;
2753  OUString sFind;
2754  uno::Sequence<OUString> aFilters(1);
2755 
2756  uno::Any aURLAny = GetDBunoURI(rURL, type);
2757  switch (type) {
2758  case DBConnURIType::UNKNOWN:
2759  case DBConnURIType::CALC:
2760  case DBConnURIType::WRITER:
2761  break;
2762  case DBConnURIType::ODB:
2763  bStore = false;
2764  break;
2765  case DBConnURIType::FLAT:
2766  case DBConnURIType::DBASE:
2767  //set the filter to the file name without extension
2768  aFilters[0] = rURL.getBase();
2769  aTableFilterAny <<= aFilters;
2770  break;
2771  case DBConnURIType::MSJET:
2772  case DBConnURIType::MSACE:
2773  aSuppressVersionsAny <<= true;
2774  break;
2775  }
2776 
2777  try
2778  {
2779  uno::Reference<uno::XComponentContext> xContext(::comphelper::getProcessComponentContext());
2780  uno::Reference<sdb::XDatabaseContext> xDBContext = sdb::DatabaseContext::create(xContext);
2781 
2782  OUString sNewName = rURL.getName(
2784  sal_Int32 nExtLen = sExt.getLength();
2785  sNewName = sNewName.replaceAt(sNewName.getLength() - nExtLen - 1, nExtLen + 1, "");
2786 
2787  //find a unique name if sNewName already exists
2788  sFind = sNewName;
2789  sal_Int32 nIndex = 0;
2790  while (xDBContext->hasByName(sFind))
2791  sFind = sNewName + OUString::number(++nIndex);
2792 
2793  uno::Reference<uno::XInterface> xNewInstance;
2794  if (!bStore)
2795  {
2796  //odb-file
2797  uno::Any aDataSource = xDBContext->getByName(rURL.GetMainURL(INetURLObject::DecodeMechanism::NONE));
2798  aDataSource >>= xNewInstance;
2799  }
2800  else
2801  {
2802  xNewInstance = xDBContext->createInstance();
2803  uno::Reference<beans::XPropertySet> xDataProperties(xNewInstance, uno::UNO_QUERY);
2804 
2805  if (aURLAny.hasValue())
2806  xDataProperties->setPropertyValue("URL", aURLAny);
2807  if (aTableFilterAny.hasValue())
2808  xDataProperties->setPropertyValue("TableFilter", aTableFilterAny);
2809  if (aSuppressVersionsAny.hasValue())
2810  xDataProperties->setPropertyValue("SuppressVersionColumns", aSuppressVersionsAny);
2811  if (aInfoAny.hasValue())
2812  xDataProperties->setPropertyValue("Info", aInfoAny);
2813 
2814  if (DBConnURIType::FLAT == type && pSettings)
2815  {
2816  uno::Any aSettings = xDataProperties->getPropertyValue("Settings");
2817  uno::Reference < beans::XPropertySet > xDSSettings;
2818  aSettings >>= xDSSettings;
2819  ::comphelper::copyProperties(*pSettings, xDSSettings);
2820  xDSSettings->setPropertyValue("Extension", uno::makeAny(sExt));
2821  }
2822 
2823  uno::Reference<sdb::XDocumentDataSource> xDS(xNewInstance, uno::UNO_QUERY_THROW);
2824  uno::Reference<frame::XStorable> xStore(xDS->getDatabaseDocument(), uno::UNO_QUERY_THROW);
2825  OUString aOwnURL = getOwnURL(pDocShell);
2826  if (aOwnURL.isEmpty())
2827  {
2828  // Cannot embed, as embedded data source would need the URL of the parent document.
2829  OUString const sOutputExt = ".odb";
2830  OUString sHomePath(SvtPathOptions().GetWorkPath());
2831  utl::TempFile aTempFile(sNewName, true, &sOutputExt, pDestDir ? pDestDir : &sHomePath);
2832  const OUString& sTmpName = aTempFile.GetURL();
2833  xStore->storeAsURL(sTmpName, uno::Sequence<beans::PropertyValue>());
2834  }
2835  else
2836  {
2837  // Embed.
2838  OUString aStreamRelPath = "EmbeddedDatabase";
2839  uno::Reference<embed::XStorage> xStorage = pDocShell->GetStorage();
2840 
2841  // Refer to the sub-storage name in the document settings, so
2842  // we can load it again next time the file is imported.
2843  uno::Reference<lang::XMultiServiceFactory> xFactory(pDocShell->GetModel(), uno::UNO_QUERY);
2844  uno::Reference<beans::XPropertySet> xPropertySet(xFactory->createInstance("com.sun.star.document.Settings"), uno::UNO_QUERY);
2845  xPropertySet->setPropertyValue("EmbeddedDatabaseName", uno::makeAny(aStreamRelPath));
2846 
2847  // Store it only after setting the above property, so that only one data source gets registered.
2848  SwDBManager::StoreEmbeddedDataSource(xStore, xStorage, aStreamRelPath, aOwnURL);
2849  }
2850  }
2851  xDBContext->registerObject(sFind, xNewInstance);
2852  }
2853  catch (const uno::Exception&)
2854  {
2855  sFind.clear();
2856  }
2857  return sFind;
2858 }
2859 
2860 // Construct vnd.sun.star.pkg:// URL
2861 OUString ConstructVndSunStarPkgUrl(const OUString& rMainURL, const OUString& rStreamRelPath)
2862 {
2863  auto xContext(comphelper::getProcessComponentContext());
2864  auto xUri = css::uri::UriReferenceFactory::create(xContext)->parse(rMainURL);
2865  assert(xUri.is());
2866  xUri = css::uri::VndSunStarPkgUrlReferenceFactory::create(xContext)
2867  ->createVndSunStarPkgUrlReference(xUri);
2868  assert(xUri.is());
2869  return xUri->getUriReference() + "/"
2871  rStreamRelPath, INetURLObject::PART_FPATH,
2873 }
2874 }
2875 
2877 {
2878  sfx2::FileDialogHelper aDlgHelper(ui::dialogs::TemplateDescription::FILEOPEN_SIMPLE, FileDialogFlags::NONE, pParent);
2879  uno::Reference < ui::dialogs::XFilePicker3 > xFP = aDlgHelper.GetFilePicker();
2880 
2881  OUString sHomePath(SvtPathOptions().GetWorkPath());
2882  aDlgHelper.SetDisplayDirectory( sHomePath );
2883 
2884  OUString sFilterAll(SwResId(STR_FILTER_ALL));
2885  OUString sFilterAllData(SwResId(STR_FILTER_ALL_DATA));
2886  OUString sFilterSXB(SwResId(STR_FILTER_SXB));
2887  OUString sFilterSXC(SwResId(STR_FILTER_SXC));
2888  OUString sFilterSXW(SwResId(STR_FILTER_SXW));
2889  OUString sFilterDBF(SwResId(STR_FILTER_DBF));
2890  OUString sFilterXLS(SwResId(STR_FILTER_XLS));
2891  OUString sFilterDOC(SwResId(STR_FILTER_DOC));
2892  OUString sFilterTXT(SwResId(STR_FILTER_TXT));
2893  OUString sFilterCSV(SwResId(STR_FILTER_CSV));
2894 #ifdef _WIN32
2895  OUString sFilterMDB(SwResId(STR_FILTER_MDB));
2896  OUString sFilterACCDB(SwResId(STR_FILTER_ACCDB));
2897 #endif
2898  xFP->appendFilter( sFilterAll, "*" );
2899  xFP->appendFilter( sFilterAllData, "*.ods;*.sxc;*.odt;*.sxw;*.dbf;*.xls;*.xlsx;*.doc;*.docx;*.txt;*.csv");
2900 
2901  xFP->appendFilter( sFilterSXB, "*.odb" );
2902  xFP->appendFilter( sFilterSXC, "*.ods;*.sxc" );
2903  xFP->appendFilter( sFilterSXW, "*.odt;*.sxw" );
2904  xFP->appendFilter( sFilterDBF, "*.dbf" );
2905  xFP->appendFilter( sFilterXLS, "*.xls;*.xlsx" );
2906  xFP->appendFilter( sFilterDOC, "*.doc;*.docx" );
2907  xFP->appendFilter( sFilterTXT, "*.txt" );
2908  xFP->appendFilter( sFilterCSV, "*.csv" );
2909 #ifdef _WIN32
2910  xFP->appendFilter(sFilterMDB, "*.mdb;*.mde");
2911  xFP->appendFilter(sFilterACCDB, "*.accdb;*.accde");
2912 #endif
2913 
2914  xFP->setCurrentFilter( sFilterAll ) ;
2915  OUString sFind;
2916  if( ERRCODE_NONE == aDlgHelper.Execute() )
2917  {
2918  uno::Reference< beans::XPropertySet > aSettings;
2919  const INetURLObject aURL( xFP->getSelectedFiles().getConstArray()[0] );
2920  const DBConnURIType type = GetDBunoType( aURL );
2921 
2922  if( DBConnURIType::FLAT == type )
2923  {
2924  uno::Reference<uno::XComponentContext> xContext( ::comphelper::getProcessComponentContext() );
2925  uno::Reference < sdb::XTextConnectionSettings > xSettingsDlg = sdb::TextConnectionSettings::create(xContext);
2926  if( xSettingsDlg->execute() )
2927  aSettings.set( uno::Reference < beans::XPropertySet >( xSettingsDlg, uno::UNO_QUERY_THROW ) );
2928  }
2929  sFind = LoadAndRegisterDataSource_Impl( type, DBConnURIType::FLAT == type ? &aSettings : nullptr, aURL, nullptr, pDocShell );
2930 
2931  m_aUncommittedRegistrations.push_back(std::pair<SwDocShell*, OUString>(pDocShell, sFind));
2932  }
2933  return sFind;
2934 }
2935 
2936 void SwDBManager::StoreEmbeddedDataSource(const uno::Reference<frame::XStorable>& xStorable,
2937  const uno::Reference<embed::XStorage>& xStorage,
2938  const OUString& rStreamRelPath,
2939  const OUString& rOwnURL, bool bCopyTo)
2940 {
2941  // Construct vnd.sun.star.pkg:// URL for later loading, and TargetStorage/StreamRelPath for storing.
2942  OUString const sTmpName = ConstructVndSunStarPkgUrl(rOwnURL, rStreamRelPath);
2943 
2944  uno::Sequence<beans::PropertyValue> aSequence = comphelper::InitPropertySequence(
2945  {
2946  {"TargetStorage", uno::makeAny(xStorage)},
2947  {"StreamRelPath", uno::makeAny(rStreamRelPath)},
2948  {"BaseURI", uno::makeAny(rOwnURL)}
2949  });
2950  if (bCopyTo)
2951  xStorable->storeToURL(sTmpName, aSequence);
2952  else
2953  xStorable->storeAsURL(sTmpName, aSequence);
2954 }
2955 
2956 OUString SwDBManager::LoadAndRegisterDataSource(const OUString &rURI, const OUString *pDestDir)
2957 {
2958  return LoadAndRegisterDataSource_Impl( DBConnURIType::UNKNOWN, nullptr, INetURLObject(rURI), pDestDir, nullptr );
2959 }
2960 
2961 namespace
2962 {
2963  // tdf#117824 switch the embedded database away from using its current storage and point it to temporary storage
2964  // which allows the original storage to be deleted
2965  void switchEmbeddedDatabaseStorage(const uno::Reference<sdb::XDatabaseContext>& rDatabaseContext, const OUString& rName)
2966  {
2967  uno::Reference<sdb::XDocumentDataSource> xDS(rDatabaseContext->getByName(rName), uno::UNO_QUERY);
2968  if (!xDS)
2969  return;
2970  uno::Reference<document::XStorageBasedDocument> xStorageDoc(xDS->getDatabaseDocument(), uno::UNO_QUERY);
2971  if (!xStorageDoc)
2972  return;
2973  xStorageDoc->switchToStorage(comphelper::OStorageHelper::GetTemporaryStorage());
2974  }
2975 }
2976 
2977 void SwDBManager::RevokeDataSource(const OUString& rName)
2978 {
2979  uno::Reference<sdb::XDatabaseContext> xDatabaseContext = sdb::DatabaseContext::create(comphelper::getProcessComponentContext());
2980  if (xDatabaseContext->hasByName(rName))
2981  {
2982  switchEmbeddedDatabaseStorage(xDatabaseContext, rName);
2983  xDatabaseContext->revokeObject(rName);
2984  }
2985 }
2986 
2988 {
2989  uno::Reference<sdb::XDatabaseContext> xDatabaseContext = sdb::DatabaseContext::create(comphelper::getProcessComponentContext());
2990 
2991  OUString sDataSource = rData.sDataSource;
2992 
2993  // Fallback, just in case the document would contain an embedded data source, but no DB fields.
2994  if (sDataSource.isEmpty())
2995  sDataSource = "EmbeddedDatabase";
2996 
2997  SwDBManager::RevokeDataSource( sDataSource );
2998 
2999  // Encode the stream name and the real path into a single URL.
3000  const INetURLObject& rURLObject = rDocShell.GetMedium()->GetURLObject();
3001  OUString const aURL = ConstructVndSunStarPkgUrl(
3003  m_sEmbeddedName);
3004 
3005  uno::Reference<uno::XInterface> xDataSource(xDatabaseContext->getByName(aURL), uno::UNO_QUERY);
3006  xDatabaseContext->registerObject( sDataSource, xDataSource );
3007 
3008  // temp file - don't remember connection
3009  if (rData.sDataSource.isEmpty())
3010  m_aUncommittedRegistrations.push_back(std::pair<SwDocShell*, OUString>(nullptr, sDataSource));
3011 }
3012 
3014  const uno::Sequence<beans::PropertyValue>& rProperties)
3015 {
3016  //prevent second call
3017  if(m_pImpl->pMergeDialog)
3018  return ;
3019  OUString sDataSource, sDataTableOrQuery;
3020  uno::Sequence<uno::Any> aSelection;
3021 
3022  sal_Int32 nCmdType = sdb::CommandType::TABLE;
3023  uno::Reference< sdbc::XConnection> xConnection;
3024 
3025  svx::ODataAccessDescriptor aDescriptor(rProperties);
3026  sDataSource = aDescriptor.getDataSource();
3027  OSL_VERIFY(aDescriptor[svx::DataAccessDescriptorProperty::Command] >>= sDataTableOrQuery);
3028  OSL_VERIFY(aDescriptor[svx::DataAccessDescriptorProperty::CommandType] >>= nCmdType);
3029 
3031  aDescriptor[svx::DataAccessDescriptorProperty::Selection] >>= aSelection;
3033  aDescriptor[svx::DataAccessDescriptorProperty::Connection] >>= xConnection;
3034 
3035  if(sDataSource.isEmpty() || sDataTableOrQuery.isEmpty())
3036  {
3037  OSL_FAIL("PropertyValues missing or unset");
3038  return;
3039  }
3040 
3041  //always create a connection for the dialog and dispose it after the dialog has been closed
3042  SwDSParam* pFound = nullptr;
3043  if(!xConnection.is())
3044  {
3045  xConnection = SwDBManager::RegisterConnection(sDataSource);
3046  pFound = FindDSConnection(sDataSource, true);
3047  }
3049  m_pImpl->pMergeDialog = pFact->CreateMailMergeDlg( &rSh.GetView().GetViewFrame()->GetWindow(), rSh,
3050  sDataSource,
3051  sDataTableOrQuery,
3052  nCmdType,
3053  xConnection);
3054  if(m_pImpl->pMergeDialog->Execute() == RET_OK)
3055  {
3056  aDescriptor[svx::DataAccessDescriptorProperty::Selection] <<= m_pImpl->pMergeDialog->GetSelection();
3057 
3058  uno::Reference<sdbc::XResultSet> xResSet = m_pImpl->pMergeDialog->GetResultSet();
3059  if(xResSet.is())
3060  aDescriptor[svx::DataAccessDescriptorProperty::Cursor] <<= xResSet;
3061 
3062  // SfxObjectShellRef is ok, since there should be no control over the document lifetime here
3063  SfxObjectShellRef xDocShell = rSh.GetView().GetViewFrame()->GetObjectShell();
3064 
3065  lcl_emitEvent(SfxEventHintId::SwMailMerge, STR_SW_EVENT_MAIL_MERGE, xDocShell.get());
3066 
3067  // prepare mail merge descriptor
3068  SwMergeDescriptor aMergeDesc( m_pImpl->pMergeDialog->GetMergeType(), rSh, aDescriptor );
3069  aMergeDesc.sSaveToFilter = m_pImpl->pMergeDialog->GetSaveFilter();
3070  aMergeDesc.bCreateSingleFile = m_pImpl->pMergeDialog->IsSaveSingleDoc();
3071  aMergeDesc.bPrefixIsFilename = aMergeDesc.bCreateSingleFile;
3072  aMergeDesc.sPrefix = m_pImpl->pMergeDialog->GetTargetURL();
3073  if( !aMergeDesc.bCreateSingleFile && m_pImpl->pMergeDialog->IsGenerateFromDataBase() )
3074  {
3075  aMergeDesc.sDBcolumn = m_pImpl->pMergeDialog->GetColumnName();
3076  }
3077 
3078  Merge( aMergeDesc );
3079 
3080  lcl_emitEvent(SfxEventHintId::SwMailMergeEnd, STR_SW_EVENT_MAIL_MERGE_END, xDocShell.get());
3081 
3082  // reset the cursor inside
3083  xResSet = nullptr;
3084  aDescriptor[svx::DataAccessDescriptorProperty::Cursor] <<= xResSet;
3085  }
3086  if(pFound)
3087  {
3088  for (const auto & pParam : m_DataSourceParams)
3089  {
3090  if (pParam.get() == pFound)
3091  {
3092  try
3093  {
3094  uno::Reference<lang::XComponent> xComp(pParam->xConnection, uno::UNO_QUERY);
3095  if(xComp.is())
3096  xComp->dispose();
3097  }
3098  catch(const uno::RuntimeException&)
3099  {
3100  //may be disposed already since multiple entries may have used the same connection
3101  }
3102  break;
3103  }
3104  //pFound doesn't need to be removed/deleted -
3105  //this has been done by the SwConnectionDisposedListener_Impl already
3106  }
3107  }
3108  m_pImpl->pMergeDialog.disposeAndClear();
3109 }
3110 
3112  const uno::Sequence< beans::PropertyValue>& rProperties)
3113 {
3114  OUString sDataSource, sDataTableOrQuery;
3115  uno::Reference<sdbc::XResultSet> xResSet;
3116  uno::Sequence<uno::Any> aSelection;
3117  sal_Int16 nCmdType = sdb::CommandType::TABLE;
3118  uno::Reference< sdbc::XConnection> xConnection;
3119  for(const beans::PropertyValue& rValue : rProperties)
3120  {
3121  if ( rValue.Name == "DataSourceName" )
3122  rValue.Value >>= sDataSource;
3123  else if ( rValue.Name == "Command" )
3124  rValue.Value >>= sDataTableOrQuery;
3125  else if ( rValue.Name == "Cursor" )
3126  rValue.Value >>= xResSet;
3127  else if ( rValue.Name == "Selection" )
3128  rValue.Value >>= aSelection;
3129  else if ( rValue.Name == "CommandType" )
3130  rValue.Value >>= nCmdType;
3131  else if ( rValue.Name == "ActiveConnection" )
3132  rValue.Value >>= xConnection;
3133  }
3134  if(sDataSource.isEmpty() || sDataTableOrQuery.isEmpty() || !xResSet.is())
3135  {
3136  OSL_FAIL("PropertyValues missing or unset");
3137  return;
3138  }
3139  uno::Reference< uno::XComponentContext > xContext( ::comphelper::getProcessComponentContext() );
3140  uno::Reference<sdbc::XDataSource> xSource;
3141  uno::Reference<container::XChild> xChild(xConnection, uno::UNO_QUERY);
3142  if(xChild.is())
3143  xSource.set(xChild->getParent(), uno::UNO_QUERY);
3144  if(!xSource.is())
3145  xSource = dbtools::getDataSource(sDataSource, xContext);
3146  uno::Reference< sdbcx::XColumnsSupplier > xColSupp( xResSet, uno::UNO_QUERY );
3147  SwDBData aDBData;
3148  aDBData.sDataSource = sDataSource;
3149  aDBData.sCommand = sDataTableOrQuery;
3150  aDBData.nCommandType = nCmdType;
3151 
3154  xSource,
3155  xColSupp,
3156  aDBData ));
3157  if( RET_OK == pDlg->Execute() )
3158  {
3159  OUString sDummy;
3160  if(!xConnection.is())
3161  xConnection = xSource->getConnection(sDummy, sDummy);
3162  try
3163  {
3164  pDlg->DataToDoc( aSelection , xSource, xConnection, xResSet);
3165  }
3166  catch (const uno::Exception&)
3167  {
3168  TOOLS_WARN_EXCEPTION("sw.mailmerge", "");
3169  }
3170  }
3171 }
3172 
3173 uno::Reference<sdbc::XDataSource> SwDBManager::getDataSourceAsParent(const uno::Reference< sdbc::XConnection>& _xConnection,const OUString& _sDataSourceName)
3174 {
3175  uno::Reference<sdbc::XDataSource> xSource;
3176  try
3177  {
3178  uno::Reference<container::XChild> xChild(_xConnection, uno::UNO_QUERY);
3179  if ( xChild.is() )
3180  xSource.set(xChild->getParent(), uno::UNO_QUERY);
3181  if ( !xSource.is() )
3182  xSource = dbtools::getDataSource(_sDataSourceName, ::comphelper::getProcessComponentContext());
3183  }
3184  catch (const uno::Exception&)
3185  {
3186  TOOLS_WARN_EXCEPTION("sw.mailmerge", "getDataSourceAsParent()");
3187  }
3188  return xSource;
3189 }
3190 
3191 uno::Reference<sdbc::XResultSet> SwDBManager::createCursor(const OUString& _sDataSourceName,
3192  const OUString& _sCommand,
3193  sal_Int32 _nCommandType,
3194  const uno::Reference<sdbc::XConnection>& _xConnection,
3195  const SwView* pView)
3196 {
3197  uno::Reference<sdbc::XResultSet> xResultSet;
3198  try
3199  {
3200  uno::Reference< lang::XMultiServiceFactory > xMgr( ::comphelper::getProcessServiceFactory() );
3201  if( xMgr.is() )
3202  {
3203  uno::Reference<uno::XInterface> xInstance = xMgr->createInstance("com.sun.star.sdb.RowSet");
3204  uno::Reference<beans::XPropertySet> xRowSetPropSet(xInstance, uno::UNO_QUERY);
3205  if(xRowSetPropSet.is())
3206  {
3207  xRowSetPropSet->setPropertyValue("DataSourceName", uno::makeAny(_sDataSourceName));
3208  xRowSetPropSet->setPropertyValue("ActiveConnection", uno::makeAny(_xConnection));
3209  xRowSetPropSet->setPropertyValue("Command", uno::makeAny(_sCommand));
3210  xRowSetPropSet->setPropertyValue("CommandType", uno::makeAny(_nCommandType));
3211 
3212  uno::Reference< sdb::XCompletedExecution > xRowSet(xInstance, uno::UNO_QUERY);
3213 
3214  if ( xRowSet.is() )
3215  {
3216  weld::Window* pWindow = pView ? pView->GetFrameWeld() : nullptr;
3217  uno::Reference< task::XInteractionHandler > xHandler( task::InteractionHandler::createWithParent(comphelper::getComponentContext(xMgr), pWindow ? pWindow->GetXWindow() : nullptr), uno::UNO_QUERY_THROW );
3218  xRowSet->executeWithCompletion(xHandler);
3219  }
3220  xResultSet.set(xRowSet, uno::UNO_QUERY);
3221  }
3222  }
3223  }
3224  catch (const uno::Exception&)
3225  {
3226  TOOLS_WARN_EXCEPTION("sw.mailmerge", "Caught exception while creating a new RowSet");
3227  }
3228  return xResultSet;
3229 }
3230 
3231 void SwDBManager::setEmbeddedName(const OUString& rEmbeddedName, SwDocShell& rDocShell)
3232 {
3233  bool bLoad = m_sEmbeddedName != rEmbeddedName && !rEmbeddedName.isEmpty();
3234  bool bRegisterListener = m_sEmbeddedName.isEmpty() && !rEmbeddedName.isEmpty();
3235 
3236  m_sEmbeddedName = rEmbeddedName;
3237 
3238  if (bLoad)
3239  {
3240  uno::Reference<embed::XStorage> xStorage = rDocShell.GetStorage();
3241  // It's OK that we don't have the named sub-storage yet, in case
3242  // we're in the process of creating it.
3243  if (xStorage->hasByName(rEmbeddedName))
3244  LoadAndRegisterEmbeddedDataSource(rDocShell.GetDoc()->GetDBData(), rDocShell);
3245  }
3246 
3247  if (bRegisterListener)
3248  // Register a remove listener, so we know when the embedded data source is removed.
3249  m_pImpl->m_xDataSourceRemovedListener = new SwDataSourceRemovedListener(*this);
3250 }
3251 
3252 const OUString& SwDBManager::getEmbeddedName() const
3253 {
3254  return m_sEmbeddedName;
3255 }
3256 
3258 {
3259  return m_pDoc;
3260 }
3261 
3263 {
3264  if (m_pImpl->m_xDataSourceRemovedListener.is())
3265  {
3266  m_pImpl->m_xDataSourceRemovedListener->Dispose();
3267  m_pImpl->m_xDataSourceRemovedListener.clear();
3268  }
3269 }
3270 
3272  : m_pDBManager(&rManager)
3273 {
3274 }
3275 
3276 void SwDBManager::ConnectionDisposedListener_Impl::disposing( const lang::EventObject& rSource )
3277 {
3278  ::SolarMutexGuard aGuard;
3279 
3280  if (!m_pDBManager) return; // we're disposed too!
3281 
3282  uno::Reference<sdbc::XConnection> xSource(rSource.Source, uno::UNO_QUERY);
3283  for (size_t nPos = m_pDBManager->m_DataSourceParams.size(); nPos; nPos--)
3284  {
3285  SwDSParam* pParam = m_pDBManager->m_DataSourceParams[nPos - 1].get();
3286  if(pParam->xConnection.is() &&
3287  (xSource == pParam->xConnection))
3288  {
3289  m_pDBManager->m_DataSourceParams.erase(
3290  m_pDBManager->m_DataSourceParams.begin() + nPos - 1);
3291  }
3292  }
3293 }
3294 
3295 std::shared_ptr<SwMailMergeConfigItem> SwDBManager::PerformMailMerge(SwView const * pView)
3296 {
3297  std::shared_ptr<SwMailMergeConfigItem> xConfigItem = pView->GetMailMergeConfigItem();
3298  if (!xConfigItem)
3299  return xConfigItem;
3300 
3301  svx::ODataAccessDescriptor aDescriptor;
3302  aDescriptor.setDataSource(xConfigItem->GetCurrentDBData().sDataSource);
3303  aDescriptor[ svx::DataAccessDescriptorProperty::Connection ] <<= xConfigItem->GetConnection().getTyped();
3304  aDescriptor[ svx::DataAccessDescriptorProperty::Cursor ] <<= xConfigItem->GetResultSet();
3305  aDescriptor[ svx::DataAccessDescriptorProperty::Command ] <<= xConfigItem->GetCurrentDBData().sCommand;
3306  aDescriptor[ svx::DataAccessDescriptorProperty::CommandType ] <<= xConfigItem->GetCurrentDBData().nCommandType;
3307  aDescriptor[ svx::DataAccessDescriptorProperty::Selection ] <<= xConfigItem->GetSelection();
3308 
3309  SwWrtShell& rSh = pView->GetWrtShell();
3310  xConfigItem->SetTargetView(nullptr);
3311 
3312  SwMergeDescriptor aMergeDesc(DBMGR_MERGE_SHELL, rSh, aDescriptor);
3313  aMergeDesc.pMailMergeConfigItem = xConfigItem.get();
3314  aMergeDesc.bCreateSingleFile = true;
3315  rSh.GetDBManager()->Merge(aMergeDesc);
3316 
3317  return xConfigItem;
3318 }
3319 
3321 {
3322  if (!m_aUncommittedRegistrations.empty())
3323  {
3324  SwView* pView = ( m_pDoc && m_pDoc->GetDocShell() ) ? m_pDoc->GetDocShell()->GetView() : nullptr;
3325  if (pView)
3326  {
3327  const std::shared_ptr<SwMailMergeConfigItem>& xConfigItem = pView->GetMailMergeConfigItem();
3328  if (xConfigItem)
3329  {
3330  xConfigItem->DisposeResultSet();
3331  xConfigItem->DocumentReloaded();
3332  }
3333  }
3334 
3335  for (auto it = m_aUncommittedRegistrations.begin(); it != m_aUncommittedRegistrations.end();)
3336  {
3337  if ((m_pDoc && it->first == m_pDoc->GetDocShell()) || it->first == nullptr)
3338  {
3339  RevokeDataSource(it->second);
3340  it = m_aUncommittedRegistrations.erase(it);
3341  }
3342  else
3343  ++it;
3344  }
3345  }
3346 }
3347 
3349 {
3350  for (auto aIt = m_aUncommittedRegistrations.begin(); aIt != m_aUncommittedRegistrations.end();)
3351  {
3352  if (aIt->first == m_pDoc->GetDocShell() || aIt->first == nullptr)
3353  {
3354  m_aNotUsedConnections.push_back(aIt->second);
3355  aIt = m_aUncommittedRegistrations.erase(aIt);
3356  }
3357  else
3358  aIt++;
3359  }
3360 }
3361 
3362 void SwDBManager::SetAsUsed(const OUString& rName)
3363 {
3364  auto aFound = std::find(m_aNotUsedConnections.begin(), m_aNotUsedConnections.end(), rName);
3365  if (aFound != m_aNotUsedConnections.end())
3366  m_aNotUsedConnections.erase(aFound);
3367 }
3368 
3370 {
3371  for (auto aIt = m_aNotUsedConnections.begin(); aIt != m_aNotUsedConnections.end();)
3372  {
3373  RevokeDataSource(*aIt);
3374  aIt = m_aNotUsedConnections.erase(aIt);
3375  }
3376 }
3377 
3378 /* vim:set shiftwidth=4 softtabstop=4 expandtab: */
void InsertLineBreak()
Definition: wrtsh1.cxx:921
virtual Point GetPosPixel() const
static bool lcl_ToNextRecord(SwDSParam *pParam, const SwDBNextRecord action=SwDBNextRecord::NEXT)
Definition: dbmgr.cxx:2277
SfxViewFrame * GetViewFrame() const
void GetColumnNames(ListBox *pListBox, const OUString &rDBName, const OUString &rTableName)
Fill listbox with all column names of a database table.
Definition: dbmgr.cxx:752
css::uno::Reference< css::sdbc::XResultSet > xResultSet
Definition: dbmgr.hxx:107
bool is() const
virtual void mailDelivered(::rtl::Reference< MailDispatcher >, uno::Reference< mail::XMailMessage > xMessage) override
Definition: dbmgr.cxx:1120
SwNodeIndex AppendDoc(const SwDoc &rSource, sal_uInt16 nStartPageNumber, bool bDeletePrevious, int physicalPageOffset, const sal_uLong nDocNo)
Definition: docnew.cxx:985
bool bCreateSingleFile
Create a single or multiple results.
Definition: dbmgr.hxx:149
Definition: calc.hxx:184
SAL_DLLPRIVATE void ImportDBEntry(SwWrtShell *pSh)
Insert a single data record as text into document.
Definition: dbmgr.cxx:643
void RevokeLastRegistrations()
Revoke not committed registrations in case of mail merge cancel.
Definition: dbmgr.cxx:3320
virtual void SAL_CALL setBody(const css::uno::Reference< css::datatransfer::XTransferable > &_body) override
const SwXMailMerge * GetMailMergeEvtSrc() const
MailMergeEvent source.
Definition: dbmgr.hxx:292
osl::Mutex m_aAllEmailSendMutex
Definition: dbmgr.cxx:312
bool hasValue()
sal_Int32 nCommandType
Definition: swdbdata.hxx:32
void MergeCancel()
Definition: dbmgr.cxx:1730
void SplitNode(bool bAutoFormat=false)
Definition: wrtsh1.cxx:997
virtual css::uno::Reference< css::awt::XWindow > GetXWindow()=0
const OUString & GetTempPath() const
void SetType(SectionType const eNew)
Definition: section.hxx:96
virtual void idle(::rtl::Reference< MailDispatcher >) override
Called when there are no more mail messages to deliver.
Definition: dbmgr.cxx:1118
virtual bool DoSaveCompleted(SfxMedium *pNewStor=nullptr, bool bRegisterRecent=true)
css::util::Date aNullDate
Definition: dbmgr.hxx:65
static bool FormatValue(SvNumberFormatter const *pDocFormatter, OUString const &aString, sal_uInt32 nFormat, double &aNumber, sal_Int32 nColumnType, SwDBField *pField=nullptr)
Definition: dbfld.cxx:269
OUString GetTitle(sal_uInt16 nMaxLen=0) const
SwDSParams_t m_DataSourceParams
Definition: dbmgr.hxx:250
SwMailMergeConfigItem * pMailMergeConfigItem
Definition: dbmgr.hxx:214
css::uno::Reference< css::sdbc::XConnection > const & RegisterConnection(OUString const &rSource)
create and store or find an already stored connection to a data source for use in SwFieldMgr and SwDB...
Definition: dbmgr.cxx:2427
void setDataSource(const OUString &_sDataSourceNameOrLocation)
static css::uno::Reference< css::sdbcx::XColumnsSupplier > GetColumnSupplier(css::uno::Reference< css::sdbc::XConnection > const &xConnection, const OUString &rTableOrQuery, SwDBSelect eTableOrQuery=SwDBSelect::UNKNOWN)
Definition: dbmgr.cxx:1969
bool SttEndDoc(bool bStt)
Definition: crsrsh.cxx:562
OUString const & GetMailAddress() const
bool bEndOfDB
Definition: dbmgr.hxx:110
SwDocShell * GetDocShell()
Definition: doc.hxx:1341
std::shared_ptr< SwMailMergeConfigItem > const & GetMailMergeConfigItem() const
Definition: view0.cxx:139
bool GetTableNames(weld::ComboBox &rBox, const OUString &rDBName)
Fill listbox with all table names of a database.
Definition: dbmgr.cxx:712
IDocumentDeviceAccess const & getIDocumentDeviceAccess() const
Definition: doc.cxx:270
Listens to removed data sources, and if it's one that's embedded into this document, triggers embedding removal.
Definition: dbmgr.cxx:229
sal_uInt32 GetFormatIndex(NfIndexTableOffset, LanguageType eLnge=LANGUAGE_DONTKNOW)
SAL_DLLPRIVATE bool ToNextMergeRecord()
Definition: dbmgr.cxx:2186
static const SwDBData & GetAddressDBName()
Definition: dbmgr.cxx:2600
bool Is() const
OUString getBase(sal_Int32 nIndex=LAST_SEGMENT, bool bIgnoreFinalSlash=true, DecodeMechanism eMechanism=DecodeMechanism::ToIUri, rtl_TextEncoding eCharset=RTL_TEXTENCODING_UTF8) const
static bool lcl_SaveDoc(const INetURLObject *pFileURL, const std::shared_ptr< const SfxFilter > &pStoreToFilter, const OUString *pStoreToFilterOptions, const uno::Sequence< beans::PropertyValue > *pSaveToFilterData, const bool bIsPDFexport, SfxObjectShell *xObjectShell, SwWrtShell &rWorkShell, OUString *const decodedURL=nullptr)
Definition: dbmgr.cxx:917
SfxDispatcher * GetDispatcher()
bool OpenDataSource(const OUString &rDataSource, const OUString &rTableOrQuery)
open the source while fields are updated - for the calculator only!
Definition: dbmgr.cxx:2376
sal_uIntPtr sal_uLong
#define DB_SEP_NEWLINE
Definition: dbmgr.cxx:158
OUString sDataSource
Definition: swdbdata.hxx:30
sal_Int32 toInt32(OUString const &rStr)
css::uno::Reference< css::mail::XSmtpService > xSmtpServer
Definition: dbmgr.hxx:192
SwDataSourceRemovedListener(SwDBManager &rDBManager)
Definition: dbmgr.cxx:244
MailDispatcher listener interface.
Definition: doc.hxx:185
SAL_DLLPRIVATE bool IsValidMergeRecord() const
Definition: dbmgr.cxx:2340
bool HasValidRecord() const
Definition: dbmgr.hxx:131
IDocumentLinksAdministration const & getIDocumentLinksAdministration() const
Definition: doc.cxx:292
sal_uInt32 GetSelectedRecordId()
Definition: dbmgr.cxx:2345
css::util::Date aNullDate
Definition: dbmgr.hxx:102
SwDBManager * m_pDBManager
Definition: dbmgr.cxx:232
bool bSendAsAttachment
Definition: dbmgr.hxx:194
SwUndoId EndUndo(SwUndoId eUndoId=SwUndoId::EMPTY, const SwRewriter *pRewriter=nullptr)
Closes parenthesis of nUndoId, not used by UI.
Definition: edws.cxx:233
void SetTargetView(SwView *pView)
uno::Reference< mail::XMailMessage > m_xLastMessage
Definition: dbmgr.cxx:313
virtual ::sw::mark::IMark * makeMark(const SwPaM &rPaM, const OUString &rProposedName, MarkType eMark,::sw::mark::InsertMode eMode)=0
Generates a new mark in the document for a certain selection.
SwEditWin & GetEditWin()
Definition: view.hxx:403
static void StoreEmbeddedDataSource(const css::uno::Reference< css::frame::XStorable > &xStorable, const css::uno::Reference< css::embed::XStorage > &xStorage, const OUString &rStreamRelPath, const OUString &rOwnURL, bool bCopyTo=false)
Definition: dbmgr.cxx:2936
Data records in fields.
Definition: dbmgr.hxx:87
static std::vector< std::pair< SwDocShell *, OUString > > m_aUncommittedRegistrations
Store last registrations to revoke or commit.
Definition: dbmgr.hxx:257
IDocumentMarkAccess * getIDocumentMarkAccess()
Definition: docbm.cxx:1552
Dialog to specify the properties of date form field.
Definition: accfrmobj.cxx:38
IDocumentUndoRedo & GetIDocumentUndoRedo()
Definition: doc.cxx:176
void Clear()
css::uno::Reference< css::frame::XModel > GetModel() const
rtl::Reference< SwDataSourceRemovedListener > m_xDataSourceRemovedListener
Definition: dbmgr.cxx:311
void SetModified()
Definition: edws.cxx:69
bool UCB_DeleteFile(const OUString &rURL)
Definition: swunohelper.cxx:59
bool m_bInMerge
merge process active
Definition: dbmgr.hxx:248
css::uno::Reference< css::sdbc::XConnection > xConnection
Definition: dbmgr.hxx:105
void SetLabelDoc(bool bFlag)
Labels: Synchronize ranges.
Definition: edfld.cxx:380
void SetDisplayDirectory(const OUString &rPath)
virtual short Execute()=0
virtual SfxObjectShell * GetObjectShell() override
void EndAllAction()
Definition: edws.cxx:96
static void FinishPrintJob(const std::shared_ptr< vcl::PrinterController > &i_pController)
RET_CANCEL
css::uno::Sequence< css::beans::PropertyValue > aSaveToFilterData
Definition: dbmgr.hxx:157
virtual void SAL_CALL disposing(const lang::EventObject &Source) override
Definition: dbmgr.cxx:3276
const css::lang::Locale & getLocale(bool bResolveSystem=true) const
SwDBSelect
Definition: dbmgr.hxx:95
bool DelRight()
Definition: delete.cxx:282
virtual void SAL_CALL registeredDatabaseLocation(const sdb::DatabaseRegistrationEvent &rEvent) override
Definition: dbmgr.cxx:258
SwWrtShell & GetWrtShell() const
Definition: view.hxx:400
OUString m_sEmbeddedName
Name of the embedded database that's included in the current document.
Definition: dbmgr.hxx:254
SfxApplication * SfxGetpApp()
OOO_DLLPUBLIC_DBTOOLS OUString getFormattedValue(const css::uno::Reference< css::beans::XPropertySet > &_xColumn, const css::uno::Reference< css::util::XNumberFormatter > &xFormatter, const css::lang::Locale &_rLocale, const css::util::Date &rNullDate)
OUString PathToFileName() const
void UpdateSection(size_t const nSect, SwSectionData &, SfxItemSet const *const =nullptr)
Definition: edsect.cxx:156
css::uno::Reference< css::embed::XStorage > const & GetStorage()
OUString GetBase() const
Used by the UI to modify the document model.
Definition: wrtsh.hxx:88
static css::uno::Sequence< OUString > GetExistingDatabaseNames()
Definition: dbmgr.cxx:2605
std::unique_ptr< SwDSParam > pMergeData
Definition: dbmgr.cxx:308
IDocumentFieldsAccess const & getIDocumentFieldsAccess() const
Definition: doc.cxx:389
sal_uInt16 GetVirtPageNum()
Definition: fews.cxx:344
virtual void mailDeliveryError(::rtl::Reference< MailDispatcher > xMailDispatcher, uno::Reference< mail::XMailMessage >, const OUString &) override
Definition: dbmgr.cxx:1128
virtual void SAL_CALL disposing(const lang::EventObject &rObject) override
Definition: dbmgr.cxx:296
static bool runAsync(const std::shared_ptr< DialogController > &rController, const std::function< void(sal_Int32)> &)
weld::Window * GetFrameWeld() const
NF_NUMBER_STANDARD
sal_uInt16 sal_Unicode
sw::mark::IMark * startPageInTarget
vcl::Window & GetWindow() const
bool IsMergeOk()
Definition: dbmgr.hxx:302
constexpr auto SFX_INTERFACE_NONE
const SwView & GetView() const
Definition: wrtsh.hxx:426
bool ConvertFieldsToText()
Replace fields by text - mailmerge support.
Definition: editsh.cxx:755
bool IsInitDBFields() const
Initialize data fields that lack name of database.
Definition: dbmgr.hxx:308
virtual void SAL_CALL revokedDatabaseLocation(const sdb::DatabaseRegistrationEvent &rEvent) override
Definition: dbmgr.cxx:262
void VarChange(const OUString &rStr, const SwSbxValue &rValue)
Definition: calc.cxx:575
static void Yield()
bool IsMergeError()
Definition: dbmgr.hxx:303
#define STR_SW_EVENT_FIELD_MERGE
Definition: swevent.hxx:30
virtual VclPtr< AbstractMailMergeDlg > CreateMailMergeDlg(vcl::Window *pParent, SwWrtShell &rSh, const OUString &rSourceName, const OUString &rTableName, sal_Int32 nCommandType, const css::uno::Reference< css::sdbc::XConnection > &xConnection)=0
Print mail merge.
Definition: dbmgr.hxx:88
bool ReadLine(OString &rStr, sal_Int32 nMaxBytesToRead=0xFFFE)
SfxFrame & GetFrame() const
SAL_DLLPRIVATE SwDSParam * FindDSConnection(const OUString &rSource, bool bCreate)
Definition: dbmgr.cxx:2562
void setEmbeddedName(const OUString &rEmbeddedName, SwDocShell &rDocShell)
Definition: dbmgr.cxx:3231
virtual void DoUndo(bool const bDoUndo)=0
Enable/Disable Undo.
Send mail merge as email.
Definition: dbmgr.hxx:89
static void lcl_SaveDebugDoc(SfxObjectShell *xTargetDocShell, const char *name, int no=0)
Definition: dbmgr.cxx:880
OUString sSaveToFilter
Definition: dbmgr.hxx:155
void CommitLastRegistrations()
Accept not committed registrations.
Definition: dbmgr.cxx:3348
SwDoc * GetDoc() const
Definition: viewsh.hxx:284
bool IsLabelDoc() const
Definition: edfld.cxx:385
ConnectionDisposedListener_Impl(SwDBManager &rMgr)
Definition: dbmgr.cxx:3271
void DoGroupUndo(bool bUn)
Definition: edws.cxx:205
sal_Int32 GetColumnType(const OUString &rDBName, const OUString &rTableName, const OUString &rColNm)
Definition: dbmgr.cxx:1902
css::lang::Locale aLocale
Definition: dbmgr.hxx:67
css::uno::Sequence< css::beans::PropertyValue > InitPropertySequence(::std::initializer_list< ::std::pair< OUString, css::uno::Any > > vInit)
Create merge doc and keep the doc shell.
Definition: dbmgr.hxx:91
SAL_DLLPRIVATE SwDSParam * FindDSData(const SwDBData &rData, bool bCreate)
Definition: dbmgr.cxx:2514
void Insert(SwField const &, SwPaM *pAnnotationRange=nullptr)
Definition: wrtsh2.cxx:71
const SwSectionFormat & GetSectionFormat(size_t nFormat) const
Definition: edsect.cxx:142
if(nullptr==pCandidateA||nullptr==pCandidateB)
OUString sMailBody
Definition: dbmgr.hxx:188
static css::uno::Reference< css::sdbc::XResultSet > createCursor(const OUString &_sDataSourceName, const OUString &_sCommand, sal_Int32 _nCommandType, const css::uno::Reference< css::sdbc::XConnection > &_xConnection, const SwView *pView)
creates a RowSet, which must be disposed after use.
Definition: dbmgr.cxx:3191
void AddMergedDocument(SwDocMergeInfo const &rInfo)
css::uno::Reference< css::lang::XComponent > xComponent
SwWrtShell & rSh
Definition: dbmgr.hxx:140
static OUString lcl_FindColumn(const OUString &sFormatStr, sal_uInt16 &nUsedPos, sal_uInt8 &nSeparator)
Definition: dbmgr.cxx:612
static css::uno::Reference< css::sdbc::XDataSource > getDataSourceAsParent(const css::uno::Reference< css::sdbc::XConnection > &_xConnection, const OUString &_sDataSourceName)
try to get the data source from the given connection through the XChild interface.
Definition: dbmgr.cxx:3173
static void RevokeDataSource(const OUString &rName)
Unregister a data source.
Definition: dbmgr.cxx:2977
#define ERRCODE_IO_NOTSUPPORTED
const std::shared_ptr< vcl::PrinterController > & GetPrinterController() const
static SvxHtmlOptions & Get()
void SetDBvalue(bool bSet)
Definition: calc.hxx:120
bool Merge(const SwMergeDescriptor &rMergeDesc)
Merging of data records into fields.
Definition: dbmgr.cxx:433
SwDoc * m_pDoc
The document that owns this manager.
Definition: dbmgr.hxx:266
bool bPrefixIsFilename
Use the sPrefix as the target filename also overwriting an existing target file.
Definition: dbmgr.hxx:180
bool IsModified() const
SwDBManager * GetDBManager() const
For evaluation of DB fields (new DB-manager).
Definition: edfld.cxx:340
SwDoc * GetDoc()
returns Doc. But be careful!
Definition: docsh.hxx:203
OUString sPrefix
Basename incl.
Definition: dbmgr.hxx:172
virtual void started(::rtl::Reference< MailDispatcher >) override
Called when the MailDispatcher is started.
Definition: dbmgr.cxx:1116
uno::Reference< sdb::XDatabaseContext > m_xDatabaseContext
Definition: dbmgr.cxx:231
OUString sSaveToFilterOptions
Definition: dbmgr.hxx:156
T * get() const
static css::uno::Reference< css::embed::XStorage > GetTemporaryStorage(const css::uno::Reference< css::uno::XComponentContext > &rxContext=css::uno::Reference< css::uno::XComponentContext >())
#define STR_SW_EVENT_MAIL_MERGE_END
Definition: swevent.hxx:29
#define TOOLS_WARN_EXCEPTION(area, stream)
void LoadAndRegisterEmbeddedDataSource(const SwDBData &rData, const SwDocShell &rDocShell)
Load the embedded data source of the document and also register it.
Definition: dbmgr.cxx:2987
vcl::Window & GetWindow() const
bool HasSelection() const
Definition: wrtsh.hxx:139
#define SW_MOD()
Definition: swmodule.hxx:256
static bool Reschedule(bool bHandleAllCurrentEvents=false)
SwDBData const & GetDBData()
Definition: docfld.cxx:354
OUString sSubject
Definition: dbmgr.hxx:187
void SetDBManager(SwDBManager *pNewMgr)
Definition: doc.hxx:662
sal_uInt16 GetPageCnt()
Definition: crsrsh.cxx:1278
bool bScrollable
Definition: dbmgr.hxx:109
virtual const SwPrintData & getPrintData() const =0
Returns the PrintData.
OUString const & GetURL() const
void SetAsUsed(const OUString &rName)
Set connection as used.
Definition: dbmgr.cxx:3362
#define LANGUAGE_SYSTEM
bool GetMergeColumnCnt(const OUString &rColumnName, LanguageType nLanguage, OUString &rResult, double *pNumber)
Definition: dbmgr.cxx:2173
#define DB_SEP_SPACE
Definition: dbmgr.cxx:155
OUString getName(sal_Int32 nIndex=LAST_SEGMENT, bool bIgnoreFinalSlash=true, DecodeMechanism eMechanism=DecodeMechanism::ToIUri, rtl_TextEncoding eCharset=RTL_TEXTENCODING_UTF8) const
static DialogMask HandleError(ErrCode nId, weld::Window *pParent=nullptr, DialogMask nMask=DialogMask::MAX)
bool GetColumnCnt(const OUString &rSourceName, const OUString &rTableName, const OUString &rColumnName, sal_uInt32 nAbsRecordId, LanguageType nLanguage, OUString &rResult, double *pNumber)
Definition: dbmgr.cxx:2112
SwDBManager_Impl(SwDBManager &rDBManager)
Definition: dbmgr.cxx:315
SfxObjectShell * CreateCopy(bool bCallInitNew, bool bEmpty) const
Definition: docnew.cxx:881
int i
void ExecPrint(const css::uno::Sequence< css::beans::PropertyValue > &, bool, bool)
OUString sAttachmentName
Definition: dbmgr.hxx:189
static void lcl_GetColumnCnt(SwDSParam *pParam, const uno::Reference< beans::XPropertySet > &rColumnProps, LanguageType nLanguage, OUString &rResult, double *pNumber)
Definition: dbmgr.cxx:392
static css::uno::Reference< css::sdbc::XConnection > GetConnection(const OUString &rDataSource, css::uno::Reference< css::sdbc::XDataSource > &rxSource, const SwView *pView)
Definition: dbmgr.cxx:1946
bool DoesGroupUndo() const
Definition: edws.cxx:208
static SfxViewFrame * GetNext(const SfxViewFrame &rPrev, const SfxObjectShell *pDoc=nullptr, bool bOnlyVisible=true)
SwUndoId StartUndo(SwUndoId eUndoId=SwUndoId::EMPTY, const SwRewriter *pRewriter=nullptr)
Undo: set up Undo parenthesis, return nUndoId of this parenthesis.
Definition: edws.cxx:222
OString stripStart(const OString &rIn, sal_Char c)
virtual void SAL_CALL addCcRecipient(const OUString &sRecipientAddress) override
static void InsertText(SwWrtShell &rSh, const css::uno::Sequence< css::beans::PropertyValue > &rProperties)
Definition: dbmgr.cxx:3111
void NotifyEvent(const SfxEventHint &rEvent, bool bSynchron=true)
std::unique_ptr< SwDBManager_Impl > m_pImpl
Definition: dbmgr.hxx:251
void CloseAll(bool bIncludingMerge=true)
close all data sources - after fields were updated
Definition: dbmgr.cxx:2493
SwDBData const & GetDBData() const
Database information.
Definition: edfld.cxx:298
virtual sal_Int32 GetRecordsPerDocument() const =0
virtual void Start() override
IDocumentState const & getIDocumentState() const
Definition: doc.cxx:426
sal_Int32 InsertEntry(const OUString &rStr, sal_Int32 nPos=LISTBOX_APPEND)
void LaunchMailMergeEvent(const css::text::MailMergeEvent &rData) const
std::set< SwRootFrame * > GetAllLayouts()
Definition: doclay.cxx:1673
void RevokeNotUsedConnections()
Remove not used connections.
Definition: dbmgr.cxx:3369
VclPtr< AbstractMailMergeDlg > pMergeDialog
Definition: dbmgr.cxx:309
SfxItemSet * GetItemSet() const
static SwAbstractDialogFactory * Create()
Definition: swabstdlg.cxx:36
OUString const & GetMailReplyTo() const
Marks a node in the document model.
Definition: ndindex.hxx:31
static sal_uLong GetColumnFormat(css::uno::Reference< css::sdbc::XDataSource > const &xSource, css::uno::Reference< css::sdbc::XConnection > const &xConnection, css::uno::Reference< css::beans::XPropertySet > const &xColumn, SvNumberFormatter *pNFormatr, LanguageType nLanguage)
void Lock(bool bLock)
GUIDCNamePair const aData
OUString SwResId(const char *pId)
Definition: swmodule.cxx:191
virtual void clear()=0
SAL_DLLPRIVATE void ImportFromConnection(SwWrtShell *pSh)
Insert data record as text into document.
Definition: dbmgr.cxx:581
Reference< XComponentContext > getComponentContext(Reference< XMultiServiceFactory > const &factory)
virtual ~SwDataSourceRemovedListener() override
Definition: dbmgr.cxx:252
void UnlockExpFields()
Definition: edfld.cxx:360
void SetTimeout(sal_uInt64 nTimeoutMs)
static void lcl_RemoveSectionLinks(SwWrtShell &rWorkShell)
Definition: dbmgr.cxx:863
#define DB_DELIM
Definition: swtypes.hxx:141
SfxViewShell * GetViewShell() const
SwDocShell * GetDocShell()
Definition: view.cxx:1127
virtual void SAL_CALL addRecipient(const OUString &sRecipientAddress) override
static void lcl_PreparePrinterOptions(const uno::Sequence< beans::PropertyValue > &rInPrintOptions, uno::Sequence< beans::PropertyValue > &rOutPrintOptions)
Definition: dbmgr.cxx:962
bool ToRecordId(sal_Int32 nSet)
Definition: dbmgr.cxx:2362
WorkingDocType
Definition: dbmgr.cxx:176
std::vector< OUString > m_aNotUsedConnections
Not used connections.
Definition: dbmgr.hxx:260
OUString getDataSource() const
OUString GetMainURL(DecodeMechanism eMechanism, rtl_TextEncoding eCharset=RTL_TEXTENCODING_UTF8) const
sal_Int32 getDefaultNumberFormat(const Reference< XPropertySet > &_xColumn, const Reference< XNumberFormatTypes > &_xTypes, const Locale &_rLocale)
bool FillCalcWithMergeData(SvNumberFormatter *pDocFormatter, LanguageType nLanguage, SwCalc &aCalc)
Definition: dbmgr.cxx:2192
static std::shared_ptr< SwMailMergeConfigItem > PerformMailMerge(SwView const *pView)
Definition: dbmgr.cxx:3295
NEXT
std::unique_ptr< weld::Label > m_xPrinter
Definition: dbui.hxx:30
size_t GetSectionFormatCount() const
Definition: edsect.cxx:114
const SfxPoolItem * Put(const SfxPoolItem &rItem, sal_uInt16 nWhich)
const DBManagerOptions nMergeType
Definition: dbmgr.hxx:139
SvStream * GetInStream()
Reference< XMultiServiceFactory > getProcessServiceFactory()
css::uno::Sequence< OUString > aCopiesTo
Definition: dbmgr.hxx:190
SwWrtShell * GetWrtShellPtr() const
Definition: view.hxx:401
void releaseRevokeListener()
Stop reacting to removed database registrations.
Definition: dbmgr.cxx:3262
css::uno::Sequence< css::beans::PropertyValue > aPrintOptions
Definition: dbmgr.hxx:211
bool DoSaveAs(SfxMedium &rNewStor)
css::uno::Reference< css::util::XNumberFormatter > xFormatter
Definition: dbmgr.hxx:104
virtual bool EmbedAllLinks()=0
Embed all local links (ranges/graphics).
bool has(DataAccessDescriptorProperty _eWhich) const
void Stop()
weld::Window * GetFrameWeld() const
Save mail merge as files.
Definition: dbmgr.hxx:90
virtual void DataToDoc(const css::uno::Sequence< css::uno::Any > &rSelection, css::uno::Reference< css::sdbc::XDataSource > rxSource, css::uno::Reference< css::sdbc::XConnection > xConnection, css::uno::Reference< css::sdbc::XResultSet > xResultSet)=0
#define ERRCODE_NONE
static SfxViewFrame * LoadHiddenDocument(SfxObjectShell const &i_rDoc, SfxInterfaceId i_nViewId)
virtual void stopped(::rtl::Reference< MailDispatcher >) override
Called when the MailDispatcher is stopped.
Definition: dbmgr.cxx:1117
unsigned char sal_uInt8
const svx::ODataAccessDescriptor & rDescriptor
Definition: dbmgr.hxx:141
static OUString GetTypeStr(sal_uInt16 nTypeId)
Definition: fldbas.cxx:128
DBConnURIType GetDBunoType(const INetURLObject &rURL)
Definition: dbmgr.cxx:2614
#define STR_SW_EVENT_FIELD_MERGE_FINISHED
Definition: swevent.hxx:31
std::unique_ptr< weld::Label > m_xPrintInfo
Definition: dbui.hxx:31
const SwViewOption * GetViewOptions() const
Definition: viewsh.hxx:426
#define STR_SW_EVENT_MAIL_MERGE
Definition: swevent.hxx:28
static bool lcl_getCountFromResultSet(sal_Int32 &rCount, const SwDSParam *pParam)
Definition: dbmgr.cxx:183
~SwDBManager() COVERITY_NOEXCEPT_FALSE
Definition: dbmgr.cxx:835
rtl::Reference< SwDBManager::ConnectionDisposedListener_Impl > m_xDisposeListener
Definition: dbmgr.cxx:310
void SetIdle(bool b) const
Definition: viewopt.hxx:209
#define SAL_INFO(area, stream)
bool PutString(const OUString &)
SfxEventHintId
SwDoc * getDoc() const
Definition: dbmgr.cxx:3257
void SetInitDBFields(bool b)
Definition: dbmgr.hxx:309
virtual void SAL_CALL changedDatabaseLocation(const sdb::DatabaseRegistrationEvent &rEvent) override
Definition: dbmgr.cxx:290
virtual void SAL_CALL addBccRecipient(const OUString &sRecipientAddress) override
RET_OK
bool IsMergeSilent() const
Definition: dbmgr.hxx:295
static SfxObjectShell * lcl_CreateWorkingDocument(const WorkingDocType aType, const SwWrtShell &rSourceWrtShell, const vcl::Window *pSourceWindow, SwDBManager **const ppDBManager, SwView **const pView, SwWrtShell **const pWrtShell, SwDoc **const pDoc)
Definition: dbmgr.cxx:990
virtual void SAL_CALL setReplyToAddress(const OUString &_replytoaddress) override
bool PutDouble(double)
void SetStreamCharSet(rtl_TextEncoding eCharSet)
OUString GetFileExtension() const
virtual void setPrintData(const SwPrintData &rPrtData)=0
Sets the PrintData.
SAL_DLLPRIVATE bool MergeMailFiles(SwWrtShell *pSh, const SwMergeDescriptor &rMergeDescriptor)
Run the mail merge for defined modes, except DBMGR_MERGE.
Definition: dbmgr.cxx:1142
const INetURLObject & GetURLObject() const
#define DB_SEP_RETURN
Definition: dbmgr.cxx:157
css::uno::Sequence< OUString > aBlindCopiesTo
Definition: dbmgr.hxx:191
Reference< XComponentContext > getProcessComponentContext()
static OUString GetDBField(css::uno::Reference< css::beans::XPropertySet > const &xColumnProp, const SwDBFormatData &rDBFormatData, double *pNumber=nullptr)
Definition: dbmgr.cxx:2017
css::uno::Reference< css::util::XNumberFormatter > xFormatter
Definition: dbmgr.hxx:66
MailDispatcherListener_Impl(SwDBManager &rDBManager)
Definition: dbmgr.cxx:1113
bool RemoveInvisibleContent()
Remove the invisible content from the document e.g. hidden areas, hidden paragraphs.
Definition: doc.cxx:1394
OUString sDBcolumn
DB column to fetch EMail of Filename from.
Definition: dbmgr.hxx:203
virtual VclPtr< AbstractSwInsertDBColAutoPilot > CreateSwInsertDBColAutoPilot(SwView &rView, css::uno::Reference< css::sdbc::XDataSource > rxSource, css::uno::Reference< css::sdbcx::XColumnsSupplier > xColSupp, const SwDBData &rData)=0
static bool lcl_MoveAbsolute(SwDSParam *pParam, long nAbsPos)
Definition: dbmgr.cxx:356
SwDBNextRecord
Definition: dbmgr.cxx:173
DBConnURIType
Definition: dbmgr.hxx:479
static void lcl_InitNumberFormatter(SwDSParam &rParam, uno::Reference< sdbc::XDataSource > const &xSource)
Definition: dbmgr.cxx:327
static OUString GetEventName(sal_Int32 nId)
Definition: docsh.cxx:1348
Reference< XDataSource > getDataSource(const OUString &_rsTitleOrPath, const Reference< XComponentContext > &_rxContext)
virtual void CalcLayout() override
To enable set up of StartActions and EndActions.
Definition: edws.cxx:107
css::uno::Sequence< css::uno::Any > aSelection
Definition: dbmgr.hxx:108
ErrCode GetError() const
const short COPY
bool IsDataSourceOpen(const OUString &rDataSource, const OUString &rTableOrQuery, bool bMergeShell)
check if a data source is open
Definition: dbmgr.cxx:2089
virtual void SAL_CALL addAttachment(const css::mail::MailAttachment &aMailAttachment) override
static SfxViewFrame * GetFirst(const SfxObjectShell *pDoc=nullptr, bool bOnlyVisible=true)
static std::shared_ptr< const SfxFilter > GetFileFilter(const OUString &rFileName)
Detect for the given file which filter should be used.
Definition: iodetect.cxx:149
#define SAL_WARN(area, stream)
void ReplaceDocumentProperties(const SwDoc &rSource, bool mailMerge=false)
Replace document properties with those from rSource.
Definition: docglos.cxx:83
SwDBManager(SwDBManager const &)=delete
bool SetURL(OUString const &rTheAbsURIRef, EncodeMechanism eMechanism=EncodeMechanism::WasEncoded, rtl_TextEncoding eCharset=RTL_TEXTENCODING_UTF8)
bool CheckMailAddress(const OUString &rMailAddress)
void append_text(const OUString &rStr)
static OUString LoadAndRegisterDataSource(weld::Window *pParent, SwDocShell *pDocShell=nullptr)
Loads a data source from file and registers it.
Definition: dbmgr.cxx:2876
rtl_TextEncoding GetTextEncoding() const
#define TOOLS_WARN_EXCEPTION_IF(cond, area, stream)
const SwView * GetView() const
Definition: docsh.hxx:220
void Dispose(const T &xInterface)
css::uno::Reference< css::sdbc::XStatement > xStatement
Definition: dbmgr.hxx:106
void ChgDBData(const SwDBData &SwDBData)
Definition: wrtsh1.cxx:1757
A MailDispatcher should be used for sending a bunch a mail messages asynchronously.
static SwMailMessage * lcl_CreateMailFromDoc(const SwMergeDescriptor &rMergeDescriptor, const OUString &sFileURL, const OUString &sMailRecipient, const OUString &sMailBodyMimeType, rtl_TextEncoding sMailEncoding, const OUString &sAttachmentMimeType)
Definition: dbmgr.cxx:1056
MergeStatus m_aMergeStatus
current / last merge status
Definition: dbmgr.hxx:246
virtual void SAL_CALL setSubject(const OUString &_subject) override
void SetInMailMerge(bool bNew)
Definition: doc.hxx:953
sal_Int32 const nLength
SwSection * GetSection() const
Definition: section.cxx:675
void SetNumberingRestart()
Set all numbering start points to a fixed value - mailmerge support.
Definition: editsh.cxx:763
virtual css::uno::Reference< css::util::XNumberFormats > SAL_CALL getNumberFormats() override
void ChangeDBFields(const std::vector< OUString > &rOldNames, const OUString &rNewName)
Definition: edfld.cxx:319
void StartAllAction()
For all views of this document.
Definition: edws.cxx:85
const css::uno::Reference< css::ui::dialogs::XFilePicker3 > & GetFilePicker() const
bool IsExpFieldsLocked() const
Definition: edfld.cxx:365
bool IsMailReplyTo() const
sal_Int32 nPos
#define DB_SEP_TAB
Definition: dbmgr.cxx:156
void ExecuteFormLetter(SwWrtShell &rSh, const css::uno::Sequence< css::beans::PropertyValue > &rProperties)
Definition: dbmgr.cxx:3013
CharClass & GetAppCharClass()
Definition: init.cxx:745
OUString sCommand
Definition: swdbdata.hxx:31
virtual void SetPosPixel(const Point &rNewPos)
void SetFilter(const std::shared_ptr< const SfxFilter > &pFilter)
void SetAllUniqueFlyNames()
Definition: doclay.cxx:1450
SwDBManager * GetDBManager() const
Definition: doc.hxx:663
void LockExpFields()
Definition: edfld.cxx:355
Definition: view.hxx:146
void SetSenderAddress(const OUString &rSenderAddress)
static OUString encode(OUString const &rText, Part ePart, EncodeMechanism eMechanism, rtl_TextEncoding eCharset=RTL_TEXTENCODING_UTF8)
long nSelectionIndex
Definition: dbmgr.hxx:111
virtual OUString get_active_text() const =0
void SetDebugName(const sal_Char *pDebugName)
bool removeSegment(sal_Int32 nIndex=LAST_SEGMENT, bool bIgnoreFinalSlash=true)
virtual void ResetModified()=0
const OUString & getEmbeddedName() const
Definition: dbmgr.cxx:3252
void ToNextRecord(const OUString &rDataSource, const OUString &rTableOrQuery)
Definition: dbmgr.cxx:2256
SfxMedium * GetMedium() const