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  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  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 (auto & pParam : m_DataSourceParams)
842  {
843  if(pParam->xConnection.is())
844  {
845  aCopiedConnections.push_back(pParam->xConnection);
846  }
847  }
848  for (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  if( aType == WorkingDocType::TARGET )
1020  {
1021  assert( !ppDBManager );
1022  pWorkDoc->SetInMailMerge( true );
1023  pWorkWrtShell->SetLabelDoc( false );
1024  }
1025  else
1026  {
1027  // We have to swap the DBmanager of the new doc, so we also need input
1028  assert(ppDBManager && *ppDBManager);
1029  SwDBManager *pWorkDBManager = pWorkDoc->GetDBManager();
1030  pWorkDoc->SetDBManager( *ppDBManager );
1031  *ppDBManager = pWorkDBManager;
1032 
1033  if( aType == WorkingDocType::SOURCE )
1034  {
1035  // the GetDBData call constructs the data, if it's missing - kind of const...
1036  pWorkWrtShell->ChgDBData( const_cast<SwDoc*>(pSourceDoc)->GetDBData() );
1037  // some DocumentSettings are currently not copied by SwDoc::CreateCopy
1038  pWorkWrtShell->SetLabelDoc( rSourceWrtShell.IsLabelDoc() );
1039  pWorkDoc->getIDocumentState().ResetModified();
1040  }
1041  else
1043  }
1044 
1045  if( pView ) *pView = pWorkView;
1046  if( pWrtShell ) *pWrtShell = pWorkWrtShell;
1047  if( pDoc ) *pDoc = pWorkDoc;
1048 
1049  return xWorkObjectShell.get();
1050 }
1051 
1053  const SwMergeDescriptor &rMergeDescriptor,
1054  const OUString &sFileURL, const OUString &sMailRecipient,
1055  const OUString &sMailBodyMimeType, rtl_TextEncoding sMailEncoding,
1056  const OUString &sAttachmentMimeType )
1057 {
1058  SwMailMessage* pMessage = new SwMailMessage;
1059  if( rMergeDescriptor.pMailMergeConfigItem->IsMailReplyTo() )
1060  pMessage->setReplyToAddress(rMergeDescriptor.pMailMergeConfigItem->GetMailReplyTo());
1061  pMessage->addRecipient( sMailRecipient );
1062  pMessage->SetSenderAddress( rMergeDescriptor.pMailMergeConfigItem->GetMailAddress() );
1063 
1064  OUStringBuffer sBody;
1065  if( rMergeDescriptor.bSendAsAttachment )
1066  {
1067  sBody = rMergeDescriptor.sMailBody;
1068  mail::MailAttachment aAttach;
1069  aAttach.Data = new SwMailTransferable( sFileURL,
1070  rMergeDescriptor.sAttachmentName, sAttachmentMimeType );
1071  aAttach.ReadableName = rMergeDescriptor.sAttachmentName;
1072  pMessage->addAttachment( aAttach );
1073  }
1074  else
1075  {
1076  //read in the temporary file and use it as mail body
1077  SfxMedium aMedium( sFileURL, StreamMode::READ );
1078  SvStream* pInStream = aMedium.GetInStream();
1079  assert( pInStream && "no output file created?" );
1080  if( !pInStream )
1081  return pMessage;
1082 
1083  pInStream->SetStreamCharSet( sMailEncoding );
1084  OString sLine;
1085  while ( pInStream->ReadLine( sLine ) )
1086  {
1087  sBody.append(OStringToOUString( sLine, sMailEncoding ));
1088  sBody.append("\n");
1089  }
1090  }
1091  pMessage->setSubject( rMergeDescriptor.sSubject );
1092  uno::Reference< datatransfer::XTransferable> xBody =
1093  new SwMailTransferable( sBody.makeStringAndClear(), sMailBodyMimeType );
1094  pMessage->setBody( xBody );
1095 
1096  for( const OUString& sCcRecipient : rMergeDescriptor.aCopiesTo )
1097  pMessage->addCcRecipient( sCcRecipient );
1098  for( const OUString& sBccRecipient : rMergeDescriptor.aBlindCopiesTo )
1099  pMessage->addBccRecipient( sBccRecipient );
1100 
1101  return pMessage;
1102 }
1103 
1105 {
1107 
1108 public:
1110  : m_rDBManager( rDBManager ) {}
1111 
1112  virtual void started( ::rtl::Reference<MailDispatcher> ) override {};
1113  virtual void stopped( ::rtl::Reference<MailDispatcher> ) override {};
1114  virtual void idle( ::rtl::Reference<MailDispatcher> ) override {};
1115 
1117  uno::Reference< mail::XMailMessage> xMessage ) override
1118  {
1119  osl::MutexGuard aGuard( m_rDBManager.m_pImpl->m_aAllEmailSendMutex );
1120  if ( m_rDBManager.m_pImpl->m_xLastMessage == xMessage )
1121  m_rDBManager.m_pImpl->m_xLastMessage.clear();
1122  }
1123 
1124  virtual void mailDeliveryError( ::rtl::Reference<MailDispatcher> xMailDispatcher,
1125  uno::Reference< mail::XMailMessage>, const OUString& ) override
1126  {
1127  osl::MutexGuard aGuard( m_rDBManager.m_pImpl->m_aAllEmailSendMutex );
1128  m_rDBManager.m_aMergeStatus = MergeStatus::Error;
1129  m_rDBManager.m_pImpl->m_xLastMessage.clear();
1130  xMailDispatcher->stop();
1131  }
1132 };
1133 
1139  const SwMergeDescriptor& rMergeDescriptor)
1140 {
1141  // deconstruct mail merge type for better readability.
1142  // uppercase naming is intentional!
1143  const bool bMT_EMAIL = rMergeDescriptor.nMergeType == DBMGR_MERGE_EMAIL;
1144  const bool bMT_SHELL = rMergeDescriptor.nMergeType == DBMGR_MERGE_SHELL;
1145  const bool bMT_PRINTER = rMergeDescriptor.nMergeType == DBMGR_MERGE_PRINTER;
1146  const bool bMT_FILE = rMergeDescriptor.nMergeType == DBMGR_MERGE_FILE;
1147 
1148  //check if the doc is synchronized and contains at least one linked section
1149  const bool bSynchronizedDoc = pSourceShell->IsLabelDoc() && pSourceShell->GetSectionFormatCount() > 1;
1150  const bool bNeedsTempFiles = ( bMT_EMAIL || bMT_FILE );
1151  const bool bIsMergeSilent = IsMergeSilent();
1152 
1153  bool bCheckSingleFile_ = rMergeDescriptor.bCreateSingleFile;
1154  OUString sPrefix_ = rMergeDescriptor.sPrefix;
1155  if( bMT_EMAIL )
1156  {
1157  assert( !rMergeDescriptor.bPrefixIsFilename );
1158  assert(!bCheckSingleFile_);
1159  bCheckSingleFile_ = false;
1160  }
1161  else if( bMT_SHELL || bMT_PRINTER )
1162  {
1163  assert(bCheckSingleFile_);
1164  bCheckSingleFile_ = true;
1165  assert(sPrefix_.isEmpty());
1166  sPrefix_.clear();
1167  }
1168  const bool bCreateSingleFile = bCheckSingleFile_;
1169  const OUString sDescriptorPrefix = sPrefix_;
1170 
1171  // Setup for dumping debugging documents
1172  static const sal_Int32 nMaxDumpDocs = []() {
1173  if (const char* sEnv = getenv("SW_DEBUG_MAILMERGE_DOCS"))
1174  return OUString(sEnv, strlen(sEnv), osl_getThreadTextEncoding()).toInt32();
1175  else
1176  return sal_Int32(0);
1177  }();
1178 
1179  ::rtl::Reference< MailDispatcher > xMailDispatcher;
1181  OUString sMailBodyMimeType;
1182  rtl_TextEncoding sMailEncoding = ::osl_getThreadTextEncoding();
1183 
1184  uno::Reference< beans::XPropertySet > xColumnProp;
1185 
1186  // Check for (mandatory) email or (optional) filename column
1187  SwDBFormatData aColumnDBFormat;
1188  bool bColumnName = !rMergeDescriptor.sDBcolumn.isEmpty();
1189  if( ! bColumnName )
1190  {
1191  if( bMT_EMAIL )
1192  return false;
1193  }
1194  else
1195  {
1196  uno::Reference< sdbcx::XColumnsSupplier > xColsSupp( m_pImpl->pMergeData->xResultSet, uno::UNO_QUERY );
1197  uno::Reference<container::XNameAccess> xCols = xColsSupp->getColumns();
1198  if( !xCols->hasByName( rMergeDescriptor.sDBcolumn ) )
1199  return false;
1200  uno::Any aCol = xCols->getByName( rMergeDescriptor.sDBcolumn );
1201  aCol >>= xColumnProp;
1202 
1203  aColumnDBFormat.xFormatter = m_pImpl->pMergeData->xFormatter;
1204  aColumnDBFormat.aNullDate = m_pImpl->pMergeData->aNullDate;
1205 
1206  if( bMT_EMAIL )
1207  {
1208  // Reset internal mail accounting data
1209  m_pImpl->m_xLastMessage.clear();
1210 
1211  xMailDispatcher.set( new MailDispatcher(rMergeDescriptor.xSmtpServer) );
1212  xMailListener = new MailDispatcherListener_Impl( *this );
1213  xMailDispatcher->addListener( xMailListener );
1214  if(!rMergeDescriptor.bSendAsAttachment && rMergeDescriptor.bSendAsHTML)
1215  {
1216  sMailBodyMimeType = "text/html; charset=";
1217  sMailBodyMimeType += OUString::createFromAscii(
1218  rtl_getBestMimeCharsetFromTextEncoding( sMailEncoding ));
1219  SvxHtmlOptions& rHtmlOptions = SvxHtmlOptions::Get();
1220  sMailEncoding = rHtmlOptions.GetTextEncoding();
1221  }
1222  else
1223  sMailBodyMimeType = "text/plain; charset=UTF-8; format=flowed";
1224  }
1225  }
1226 
1227  SwDocShell *pSourceDocSh = pSourceShell->GetView().GetDocShell();
1228 
1229  // setup the output format
1230  std::shared_ptr<const SfxFilter> pStoreToFilter = SwIoSystem::GetFileFilter(
1232  SfxFilterContainer* pFilterContainer = SwDocShell::Factory().GetFilterContainer();
1233  const OUString* pStoreToFilterOptions = nullptr;
1234 
1235  // if a save_to filter is set then use it - otherwise use the default
1236  if( bMT_EMAIL && !rMergeDescriptor.bSendAsAttachment )
1237  {
1238  OUString sExtension = rMergeDescriptor.bSendAsHTML ? OUString("html") : OUString("txt");
1239  pStoreToFilter = pFilterContainer->GetFilter4Extension(sExtension, SfxFilterFlags::EXPORT);
1240  }
1241  else if( !rMergeDescriptor.sSaveToFilter.isEmpty())
1242  {
1243  std::shared_ptr<const SfxFilter> pFilter =
1244  pFilterContainer->GetFilter4FilterName( rMergeDescriptor.sSaveToFilter );
1245  if(pFilter)
1246  {
1247  pStoreToFilter = pFilter;
1248  if(!rMergeDescriptor.sSaveToFilterOptions.isEmpty())
1249  pStoreToFilterOptions = &rMergeDescriptor.sSaveToFilterOptions;
1250  }
1251  }
1252  const bool bIsPDFexport = pStoreToFilter && pStoreToFilter->GetFilterName() == "writer_pdf_Export";
1253 
1255 
1256  // in case of creating a single resulting file this has to be created here
1257  SwView* pTargetView = rMergeDescriptor.pMailMergeConfigItem ?
1258  rMergeDescriptor.pMailMergeConfigItem->GetTargetView() : nullptr;
1259  SwWrtShell* pTargetShell = nullptr;
1260  SwDoc* pTargetDoc = nullptr;
1261  SfxObjectShellRef xTargetDocShell;
1262 
1263  std::unique_ptr< utl::TempFile > aTempFile;
1264  sal_uInt16 nStartingPageNo = 0;
1265 
1266  vcl::Window *pSourceWindow = nullptr;
1267  std::shared_ptr<weld::GenericDialogController> xProgressDlg;
1268 
1269  try
1270  {
1271  if( !bIsMergeSilent )
1272  {
1273  // construct the process dialog
1274  pSourceWindow = &pSourceShell->GetView().GetEditWin();
1275  if (!bMT_PRINTER)
1276  xProgressDlg.reset(new CreateMonitor(pSourceWindow->GetFrameWeld()));
1277  else
1278  {
1279  xProgressDlg.reset(new PrintMonitor(pSourceWindow->GetFrameWeld()));
1280  static_cast<PrintMonitor*>(xProgressDlg.get())->set_title(
1281  pSourceDocSh->GetTitle(22));
1282  }
1283  weld::DialogController::runAsync(xProgressDlg, [this, &xProgressDlg](sal_Int32 nResult){
1284  if (nResult == RET_CANCEL)
1285  MergeCancel();
1286  xProgressDlg.reset();
1287  });
1288 
1289  Application::Reschedule( true );
1290  }
1291 
1292  if( bCreateSingleFile && !pTargetView )
1293  {
1294  // create a target docshell to put the merged document into
1296  *pSourceShell, bMT_SHELL ? pSourceWindow : nullptr,
1297  nullptr, &pTargetView, &pTargetShell, &pTargetDoc );
1298 
1299  // import current print settings
1300  const SwPrintData &rPrintData = pSourceShell->getIDocumentDeviceAccess().getPrintData();
1301  pTargetDoc->getIDocumentDeviceAccess().setPrintData(rPrintData);
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  css::uno::Any ex( cppu::getCaughtException() );
2079  SAL_WARN("sw.mailmerge", "exception caught: " << exceptionToString(ex));
2080  }
2081 
2082  }
2083  break;
2084  }
2085 
2086  return sRet;
2087 }
2088 
2089 // checks if a desired data source table or query is open
2090 bool SwDBManager::IsDataSourceOpen(const OUString& rDataSource,
2091  const OUString& rTableOrQuery, bool bMergeShell)
2092 {
2093  if(m_pImpl->pMergeData)
2094  {
2095  return ((rDataSource == m_pImpl->pMergeData->sDataSource
2096  && rTableOrQuery == m_pImpl->pMergeData->sCommand)
2097  || (rDataSource.isEmpty() && rTableOrQuery.isEmpty()))
2098  && m_pImpl->pMergeData->xResultSet.is();
2099  }
2100  else if(!bMergeShell)
2101  {
2102  SwDBData aData;
2103  aData.sDataSource = rDataSource;
2104  aData.sCommand = rTableOrQuery;
2105  aData.nCommandType = -1;
2106  SwDSParam* pFound = FindDSData(aData, false);
2107  return (pFound && pFound->xResultSet.is());
2108  }
2109  return false;
2110 }
2111 
2112 // read column data at a specified position
2113 bool SwDBManager::GetColumnCnt(const OUString& rSourceName, const OUString& rTableName,
2114  const OUString& rColumnName, sal_uInt32 nAbsRecordId,
2115  LanguageType nLanguage,
2116  OUString& rResult, double* pNumber)
2117 {
2118  bool bRet = false;
2119  SwDSParam* pFound = nullptr;
2120  //check if it's the merge data source
2121  if(m_pImpl->pMergeData &&
2122  rSourceName == m_pImpl->pMergeData->sDataSource &&
2123  rTableName == m_pImpl->pMergeData->sCommand)
2124  {
2125  pFound = m_pImpl->pMergeData.get();
2126  }
2127  else
2128  {
2129  SwDBData aData;
2130  aData.sDataSource = rSourceName;
2131  aData.sCommand = rTableName;
2132  aData.nCommandType = -1;
2133  pFound = FindDSData(aData, false);
2134  }
2135  if (!pFound)
2136  return false;
2137  //check validity of supplied record Id
2138  if(pFound->aSelection.hasElements())
2139  {
2140  //the destination has to be an element of the selection
2141  bool bFound = std::any_of(pFound->aSelection.begin(), pFound->aSelection.end(),
2142  [nAbsRecordId](const uno::Any& rSelection) {
2143  sal_Int32 nSelection = 0;
2144  rSelection >>= nSelection;
2145  return nSelection == static_cast<sal_Int32>(nAbsRecordId);
2146  });
2147  if(!bFound)
2148  return false;
2149  }
2150  if( pFound->HasValidRecord() )
2151  {
2152  sal_Int32 nOldRow = 0;
2153  try
2154  {
2155  nOldRow = pFound->xResultSet->getRow();
2156  }
2157  catch(const uno::Exception&)
2158  {
2159  return false;
2160  }
2161  //position to the desired index
2162  bool bMove = true;
2163  if ( nOldRow != static_cast<sal_Int32>(nAbsRecordId) )
2164  bMove = lcl_MoveAbsolute(pFound, nAbsRecordId);
2165  if(bMove)
2166  bRet = lcl_GetColumnCnt(pFound, rColumnName, nLanguage, rResult, pNumber);
2167  if ( nOldRow != static_cast<sal_Int32>(nAbsRecordId) )
2168  lcl_MoveAbsolute(pFound, nOldRow);
2169  }
2170  return bRet;
2171 }
2172 
2173 // reads the column data at the current position
2174 bool SwDBManager::GetMergeColumnCnt(const OUString& rColumnName, LanguageType nLanguage,
2175  OUString &rResult, double *pNumber)
2176 {
2177  if( !IsValidMergeRecord() )
2178  {
2179  rResult.clear();
2180  return false;
2181  }
2182 
2183  bool bRet = lcl_GetColumnCnt(m_pImpl->pMergeData.get(), rColumnName, nLanguage, rResult, pNumber);
2184  return bRet;
2185 }
2186 
2188 {
2189  assert( m_pImpl->pMergeData && m_pImpl->pMergeData->xResultSet.is() && "no data source in merge" );
2190  return lcl_ToNextRecord( m_pImpl->pMergeData.get() );
2191 }
2192 
2194  LanguageType nLanguage, SwCalc &rCalc )
2195 {
2196  if( !IsValidMergeRecord() )
2197  return false;
2198 
2199  uno::Reference< sdbcx::XColumnsSupplier > xColsSupp( m_pImpl->pMergeData->xResultSet, uno::UNO_QUERY );
2200  if( !xColsSupp.is() )
2201  return false;
2202 
2203  {
2204  uno::Reference<container::XNameAccess> xCols = xColsSupp->getColumns();
2205  const uno::Sequence<OUString> aColNames = xCols->getElementNames();
2206  OUString aString;
2207 
2208  // add the "record number" variable, as SwCalc::VarLook would.
2209  rCalc.VarChange( GetAppCharClass().lowercase(
2211 
2212  for( const OUString& rColName : aColNames )
2213  {
2214  // get the column type
2215  sal_Int32 nColumnType = sdbc::DataType::SQLNULL;
2216  uno::Any aCol = xCols->getByName( rColName );
2217  uno::Reference<beans::XPropertySet> xColumnProps;
2218  aCol >>= xColumnProps;
2219  uno::Any aType = xColumnProps->getPropertyValue( "Type" );
2220  aType >>= nColumnType;
2221  double aNumber = DBL_MAX;
2222 
2223  lcl_GetColumnCnt( m_pImpl->pMergeData.get(), xColumnProps, nLanguage, aString, &aNumber );
2224 
2225  sal_uInt32 nFormat = GetColumnFormat( m_pImpl->pMergeData->sDataSource,
2226  m_pImpl->pMergeData->sCommand,
2227  rColName, pDocFormatter, nLanguage );
2228  // aNumber is overwritten by SwDBField::FormatValue, so store initial status
2229  bool colIsNumber = aNumber != DBL_MAX;
2230  bool bValidValue = SwDBField::FormatValue( pDocFormatter, aString, nFormat,
2231  aNumber, nColumnType );
2232  if( colIsNumber )
2233  {
2234  if( bValidValue )
2235  {
2236  SwSbxValue aValue;
2237  aValue.PutDouble( aNumber );
2238  aValue.SetDBvalue( true );
2239  SAL_INFO( "sw.ui", "'" << rColName << "': " << aNumber << " / " << aString );
2240  rCalc.VarChange( rColName, aValue );
2241  }
2242  }
2243  else
2244  {
2245  SwSbxValue aValue;
2246  aValue.PutString( aString );
2247  aValue.SetDBvalue( true );
2248  SAL_INFO( "sw.ui", "'" << rColName << "': " << aString );
2249  rCalc.VarChange( rColName, aValue );
2250  }
2251  }
2252  }
2253 
2254  return true;
2255 }
2256 
2258  const OUString& rDataSource, const OUString& rCommand)
2259 {
2260  SwDSParam* pFound = nullptr;
2261  if(m_pImpl->pMergeData &&
2262  rDataSource == m_pImpl->pMergeData->sDataSource &&
2263  rCommand == m_pImpl->pMergeData->sCommand)
2264  {
2265  pFound = m_pImpl->pMergeData.get();
2266  }
2267  else
2268  {
2269  SwDBData aData;
2270  aData.sDataSource = rDataSource;
2271  aData.sCommand = rCommand;
2272  aData.nCommandType = -1;
2273  pFound = FindDSData(aData, false);
2274  }
2275  lcl_ToNextRecord( pFound );
2276 }
2277 
2278 static bool lcl_ToNextRecord( SwDSParam* pParam, const SwDBNextRecord action )
2279 {
2280  bool bRet = true;
2281 
2282  assert( SwDBNextRecord::NEXT == action ||
2283  (SwDBNextRecord::FIRST == action && pParam) );
2284  if( nullptr == pParam )
2285  return false;
2286 
2287  if( action == SwDBNextRecord::FIRST )
2288  {
2289  pParam->nSelectionIndex = 0;
2290  pParam->bEndOfDB = false;
2291  }
2292 
2293  if( !pParam->HasValidRecord() )
2294  return false;
2295 
2296  try
2297  {
2298  if( pParam->aSelection.hasElements() )
2299  {
2300  if( pParam->nSelectionIndex >= pParam->aSelection.getLength() )
2301  pParam->bEndOfDB = true;
2302  else
2303  {
2304  sal_Int32 nPos = 0;
2305  pParam->aSelection.getConstArray()[ pParam->nSelectionIndex ] >>= nPos;
2306  pParam->bEndOfDB = !pParam->xResultSet->absolute( nPos );
2307  }
2308  }
2309  else if( action == SwDBNextRecord::FIRST )
2310  {
2311  pParam->bEndOfDB = !pParam->xResultSet->first();
2312  }
2313  else
2314  {
2315  sal_Int32 nBefore = pParam->xResultSet->getRow();
2316  pParam->bEndOfDB = !pParam->xResultSet->next();
2317  if( !pParam->bEndOfDB && nBefore == pParam->xResultSet->getRow() )
2318  {
2319  // next returned true but it didn't move
2320  ::dbtools::throwFunctionSequenceException( pParam->xResultSet );
2321  }
2322  }
2323 
2324  ++pParam->nSelectionIndex;
2325  bRet = !pParam->bEndOfDB;
2326  }
2327  catch( const uno::Exception & )
2328  {
2329  // we allow merging with empty databases, so don't warn on init
2331  "sw.mailmerge", "exception in ToNextRecord()");
2332  pParam->bEndOfDB = true;
2333  bRet = false;
2334  }
2335  return bRet;
2336 }
2337 
2338 // synchronized labels contain a next record field at their end
2339 // to assure that the next page can be created in mail merge
2340 // the cursor position must be validated
2342 {
2343  return( m_pImpl->pMergeData && m_pImpl->pMergeData->HasValidRecord() );
2344 }
2345 
2347 {
2348  sal_uInt32 nRet = 0;
2349  assert( m_pImpl->pMergeData &&
2350  m_pImpl->pMergeData->xResultSet.is() && "no data source in merge" );
2351  if(!m_pImpl->pMergeData || !m_pImpl->pMergeData->xResultSet.is())
2352  return 0;
2353  try
2354  {
2355  nRet = m_pImpl->pMergeData->xResultSet->getRow();
2356  }
2357  catch(const uno::Exception&)
2358  {
2359  }
2360  return nRet;
2361 }
2362 
2363 bool SwDBManager::ToRecordId(sal_Int32 nSet)
2364 {
2365  assert( m_pImpl->pMergeData &&
2366  m_pImpl->pMergeData->xResultSet.is() && "no data source in merge" );
2367  if(!m_pImpl->pMergeData || !m_pImpl->pMergeData->xResultSet.is()|| nSet < 0)
2368  return false;
2369  bool bRet = false;
2370  sal_Int32 nAbsPos = nSet;
2371  assert(nAbsPos >= 0);
2372  bRet = lcl_MoveAbsolute(m_pImpl->pMergeData.get(), nAbsPos);
2373  m_pImpl->pMergeData->bEndOfDB = !bRet;
2374  return bRet;
2375 }
2376 
2377 bool SwDBManager::OpenDataSource(const OUString& rDataSource, const OUString& rTableOrQuery)
2378 {
2379  SwDBData aData;
2380  aData.sDataSource = rDataSource;
2381  aData.sCommand = rTableOrQuery;
2382  aData.nCommandType = -1;
2383 
2384  SwDSParam* pFound = FindDSData(aData, true);
2385  if(pFound->xResultSet.is())
2386  return true;
2387  SwDSParam* pParam = FindDSConnection(rDataSource, false);
2388  if(pParam && pParam->xConnection.is())
2389  pFound->xConnection = pParam->xConnection;
2390  if(pFound->xConnection.is())
2391  {
2392  try
2393  {
2394  uno::Reference< sdbc::XDatabaseMetaData > xMetaData = pFound->xConnection->getMetaData();
2395  try
2396  {
2397  pFound->bScrollable = xMetaData
2398  ->supportsResultSetType(sal_Int32(sdbc::ResultSetType::SCROLL_INSENSITIVE));
2399  }
2400  catch(const uno::Exception&)
2401  {
2402  // DB driver may not be ODBC 3.0 compliant
2403  pFound->bScrollable = true;
2404  }
2405  pFound->xStatement = pFound->xConnection->createStatement();
2406  OUString aQuoteChar = xMetaData->getIdentifierQuoteString();
2407  OUString sStatement("SELECT * FROM ");
2408  sStatement = "SELECT * FROM ";
2409  sStatement += aQuoteChar;
2410  sStatement += rTableOrQuery;
2411  sStatement += aQuoteChar;
2412  pFound->xResultSet = pFound->xStatement->executeQuery( sStatement );
2413 
2414  //after executeQuery the cursor must be positioned
2415  pFound->bEndOfDB = !pFound->xResultSet->next();
2416  ++pFound->nSelectionIndex;
2417  }
2418  catch (const uno::Exception&)
2419  {
2420  pFound->xResultSet = nullptr;
2421  pFound->xStatement = nullptr;
2422  pFound->xConnection = nullptr;
2423  }
2424  }
2425  return pFound->xResultSet.is();
2426 }
2427 
2428 uno::Reference< sdbc::XConnection> const & SwDBManager::RegisterConnection(OUString const& rDataSource)
2429 {
2430  SwDSParam* pFound = SwDBManager::FindDSConnection(rDataSource, true);
2431  uno::Reference< sdbc::XDataSource> xSource;
2432  if(!pFound->xConnection.is())
2433  {
2434  SwView* pView = (m_pDoc && m_pDoc->GetDocShell()) ? m_pDoc->GetDocShell()->GetView() : nullptr;
2435  pFound->xConnection = SwDBManager::GetConnection(rDataSource, xSource, pView);
2436  try
2437  {
2438  uno::Reference<lang::XComponent> xComponent(pFound->xConnection, uno::UNO_QUERY);
2439  if(xComponent.is())
2440  xComponent->addEventListener(m_pImpl->m_xDisposeListener.get());
2441  }
2442  catch(const uno::Exception&)
2443  {
2444  }
2445  }
2446  return pFound->xConnection;
2447 }
2448 
2450  const OUString& rDataSource, const OUString& rTableOrQuery, sal_Int32 nCommandType)
2451 {
2452  sal_uInt32 nRet = 0xffffffff;
2453  //check for merge data source first
2454  if(m_pImpl->pMergeData &&
2455  ((rDataSource == m_pImpl->pMergeData->sDataSource &&
2456  rTableOrQuery == m_pImpl->pMergeData->sCommand) ||
2457  (rDataSource.isEmpty() && rTableOrQuery.isEmpty())) &&
2458  (nCommandType == -1 || nCommandType == m_pImpl->pMergeData->nCommandType) &&
2459  m_pImpl->pMergeData->xResultSet.is())
2460  {
2461  nRet = GetSelectedRecordId();
2462  }
2463  else
2464  {
2465  SwDBData aData;
2466  aData.sDataSource = rDataSource;
2467  aData.sCommand = rTableOrQuery;
2468  aData.nCommandType = nCommandType;
2469  SwDSParam* pFound = FindDSData(aData, false);
2470  if(pFound && pFound->xResultSet.is())
2471  {
2472  try
2473  { //if a selection array is set the current row at the result set may not be set yet
2474  if(pFound->aSelection.hasElements())
2475  {
2476  sal_Int32 nSelIndex = pFound->nSelectionIndex;
2477  if(nSelIndex >= pFound->aSelection.getLength())
2478  nSelIndex = pFound->aSelection.getLength() -1;
2479  pFound->aSelection.getConstArray()[nSelIndex] >>= nRet;
2480 
2481  }
2482  else
2483  nRet = pFound->xResultSet->getRow();
2484  }
2485  catch(const uno::Exception&)
2486  {
2487  }
2488  }
2489  }
2490  return nRet;
2491 }
2492 
2493 // close all data sources - after fields were updated
2494 void SwDBManager::CloseAll(bool bIncludingMerge)
2495 {
2496  //the only thing done here is to reset the selection index
2497  //all connections stay open
2498  for (auto & pParam : m_DataSourceParams)
2499  {
2500  if (bIncludingMerge || pParam.get() != m_pImpl->pMergeData.get())
2501  {
2502  pParam->nSelectionIndex = 0;
2503  pParam->bEndOfDB = false;
2504  try
2505  {
2506  if(!m_bInMerge && pParam->xResultSet.is())
2507  pParam->xResultSet->first();
2508  }
2509  catch(const uno::Exception&)
2510  {}
2511  }
2512  }
2513 }
2514 
2515 SwDSParam* SwDBManager::FindDSData(const SwDBData& rData, bool bCreate)
2516 {
2517  //prefer merge data if available
2518  if(m_pImpl->pMergeData &&
2519  ((rData.sDataSource == m_pImpl->pMergeData->sDataSource &&
2520  rData.sCommand == m_pImpl->pMergeData->sCommand) ||
2521  (rData.sDataSource.isEmpty() && rData.sCommand.isEmpty())) &&
2522  (rData.nCommandType == -1 || rData.nCommandType == m_pImpl->pMergeData->nCommandType ||
2523  (bCreate && m_pImpl->pMergeData->nCommandType == -1)))
2524  {
2525  return m_pImpl->pMergeData.get();
2526  }
2527 
2528  SwDSParam* pFound = nullptr;
2529  for (size_t nPos = m_DataSourceParams.size(); nPos; nPos--)
2530  {
2531  SwDSParam* pParam = m_DataSourceParams[nPos - 1].get();
2532  if(rData.sDataSource == pParam->sDataSource &&
2533  rData.sCommand == pParam->sCommand &&
2534  (rData.nCommandType == -1 || rData.nCommandType == pParam->nCommandType ||
2535  (bCreate && pParam->nCommandType == -1)))
2536  {
2537  // calls from the calculator may add a connection with an invalid commandtype
2538  //later added "real" data base connections have to re-use the already available
2539  //DSData and set the correct CommandType
2540  if(bCreate && pParam->nCommandType == -1)
2541  pParam->nCommandType = rData.nCommandType;
2542  pFound = pParam;
2543  break;
2544  }
2545  }
2546  if(bCreate && !pFound)
2547  {
2548  pFound = new SwDSParam(rData);
2549  m_DataSourceParams.push_back(std::unique_ptr<SwDSParam>(pFound));
2550  try
2551  {
2552  uno::Reference<lang::XComponent> xComponent(pFound->xConnection, uno::UNO_QUERY);
2553  if(xComponent.is())
2554  xComponent->addEventListener(m_pImpl->m_xDisposeListener.get());
2555  }
2556  catch(const uno::Exception&)
2557  {
2558  }
2559  }
2560  return pFound;
2561 }
2562 
2563 SwDSParam* SwDBManager::FindDSConnection(const OUString& rDataSource, bool bCreate)
2564 {
2565  //prefer merge data if available
2566  if(m_pImpl->pMergeData && rDataSource == m_pImpl->pMergeData->sDataSource )
2567  {
2568  SetAsUsed(rDataSource);
2569  return m_pImpl->pMergeData.get();
2570  }
2571  SwDSParam* pFound = nullptr;
2572  for (auto & pParam : m_DataSourceParams)
2573  {
2574  if(rDataSource == pParam->sDataSource)
2575  {
2576  SetAsUsed(rDataSource);
2577  pFound = pParam.get();
2578  break;
2579  }
2580  }
2581  if(bCreate && !pFound)
2582  {
2583  SwDBData aData;
2584  aData.sDataSource = rDataSource;
2585  pFound = new SwDSParam(aData);
2586  SetAsUsed(rDataSource);
2587  m_DataSourceParams.push_back(std::unique_ptr<SwDSParam>(pFound));
2588  try
2589  {
2590  uno::Reference<lang::XComponent> xComponent(pFound->xConnection, uno::UNO_QUERY);
2591  if(xComponent.is())
2592  xComponent->addEventListener(m_pImpl->m_xDisposeListener.get());
2593  }
2594  catch(const uno::Exception&)
2595  {
2596  }
2597  }
2598  return pFound;
2599 }
2600 
2602 {
2603  return SW_MOD()->GetDBConfig()->GetAddressSource();
2604 }
2605 
2606 uno::Sequence<OUString> SwDBManager::GetExistingDatabaseNames()
2607 {
2608  uno::Reference<uno::XComponentContext> xContext( ::comphelper::getProcessComponentContext() );
2609  uno::Reference<sdb::XDatabaseContext> xDBContext = sdb::DatabaseContext::create(xContext);
2610  return xDBContext->getElementNames();
2611 }
2612 
2613 namespace sw
2614 {
2616 {
2617  OUString sExt(rURL.GetFileExtension());
2619 
2620  if (sExt == "odb")
2621  {
2622  type = DBConnURIType::ODB;
2623  }
2624  else if (sExt.equalsIgnoreAsciiCase("sxc")
2625  || sExt.equalsIgnoreAsciiCase("ods")
2626  || sExt.equalsIgnoreAsciiCase("xls")
2627  || sExt.equalsIgnoreAsciiCase("xlsx"))
2628  {
2629  type = DBConnURIType::CALC;
2630  }
2631  else if (sExt.equalsIgnoreAsciiCase("sxw") || sExt.equalsIgnoreAsciiCase("odt") || sExt.equalsIgnoreAsciiCase("doc") || sExt.equalsIgnoreAsciiCase("docx"))
2632  {
2633  type = DBConnURIType::WRITER;
2634  }
2635  else if (sExt.equalsIgnoreAsciiCase("dbf"))
2636  {
2637  type = DBConnURIType::DBASE;
2638  }
2639  else if (sExt.equalsIgnoreAsciiCase("csv") || sExt.equalsIgnoreAsciiCase("txt"))
2640  {
2641  type = DBConnURIType::FLAT;
2642  }
2643 #ifdef _WIN32
2644  else if (sExt.equalsIgnoreAsciiCase("mdb") || sExt.equalsIgnoreAsciiCase("mde"))
2645  {
2646  type = DBConnURIType::MSJET;
2647  }
2648  else if (sExt.equalsIgnoreAsciiCase("accdb") || sExt.equalsIgnoreAsciiCase("accde"))
2649  {
2650  type = DBConnURIType::MSACE;
2651  }
2652 #endif
2653  return type;
2654 }
2655 }
2656 
2657 namespace
2658 {
2659 uno::Any GetDBunoURI(const INetURLObject &rURL, DBConnURIType& rType)
2660 {
2661  uno::Any aURLAny;
2662 
2663  if (rType == DBConnURIType::UNKNOWN)
2664  rType = GetDBunoType(rURL);
2665 
2666  switch (rType) {
2667  case DBConnURIType::UNKNOWN:
2668  case DBConnURIType::ODB:
2669  break;
2670  case DBConnURIType::CALC:
2671  {
2672  OUString sDBURL("sdbc:calc:");
2674  aURLAny <<= sDBURL;
2675  }
2676  break;
2677  case DBConnURIType::WRITER:
2678  {
2679  OUString sDBURL("sdbc:writer:");
2681  aURLAny <<= sDBURL;
2682  }
2683  break;
2684  case DBConnURIType::DBASE:
2685  {
2686  INetURLObject aUrlTmp(rURL);
2687  aUrlTmp.removeSegment();
2688  aUrlTmp.removeFinalSlash();
2689  OUString sDBURL("sdbc:dbase:");
2690  sDBURL += aUrlTmp.GetMainURL(INetURLObject::DecodeMechanism::NONE);
2691  aURLAny <<= sDBURL;
2692  }
2693  break;
2694  case DBConnURIType::FLAT:
2695  {
2696  INetURLObject aUrlTmp(rURL);
2697  aUrlTmp.removeSegment();
2698  aUrlTmp.removeFinalSlash();
2699  OUString sDBURL("sdbc:flat:");
2700  //only the 'path' has to be added
2701  sDBURL += aUrlTmp.GetMainURL(INetURLObject::DecodeMechanism::NONE);
2702  aURLAny <<= sDBURL;
2703  }
2704  break;
2705  case DBConnURIType::MSJET:
2706 #ifdef _WIN32
2707  {
2708  OUString sDBURL("sdbc:ado:access:PROVIDER=Microsoft.Jet.OLEDB.4.0;DATA SOURCE=");
2709  sDBURL += rURL.PathToFileName();
2710  aURLAny <<= sDBURL;
2711  }
2712 #endif
2713  break;
2714  case DBConnURIType::MSACE:
2715 #ifdef _WIN32
2716  {
2717  OUString sDBURL("sdbc:ado:PROVIDER=Microsoft.ACE.OLEDB.12.0;DATA SOURCE=");
2718  sDBURL += rURL.PathToFileName();
2719  aURLAny <<= sDBURL;
2720  }
2721 #endif
2722  break;
2723  }
2724  return aURLAny;
2725 }
2726 
2728 OUString getOwnURL(SfxObjectShell const * pDocShell)
2729 {
2730  OUString aRet;
2731 
2732  if (!pDocShell)
2733  return aRet;
2734 
2735  const INetURLObject& rURLObject = pDocShell->GetMedium()->GetURLObject();
2737  return aRet;
2738 }
2739 
2746 OUString LoadAndRegisterDataSource_Impl(DBConnURIType type, const uno::Reference< beans::XPropertySet > *pSettings,
2747  const INetURLObject &rURL, const OUString *pDestDir, SfxObjectShell* pDocShell)
2748 {
2749  OUString sExt(rURL.GetFileExtension());
2750  uno::Any aTableFilterAny;
2751  uno::Any aSuppressVersionsAny;
2752  uno::Any aInfoAny;
2753  bool bStore = true;
2754  OUString sFind;
2755  uno::Sequence<OUString> aFilters(1);
2756 
2757  uno::Any aURLAny = GetDBunoURI(rURL, type);
2758  switch (type) {
2759  case DBConnURIType::UNKNOWN:
2760  case DBConnURIType::CALC:
2761  case DBConnURIType::WRITER:
2762  break;
2763  case DBConnURIType::ODB:
2764  bStore = false;
2765  break;
2766  case DBConnURIType::FLAT:
2767  case DBConnURIType::DBASE:
2768  //set the filter to the file name without extension
2769  aFilters[0] = rURL.getBase();
2770  aTableFilterAny <<= aFilters;
2771  break;
2772  case DBConnURIType::MSJET:
2773  case DBConnURIType::MSACE:
2774  aSuppressVersionsAny <<= true;
2775  break;
2776  }
2777 
2778  try
2779  {
2780  uno::Reference<uno::XComponentContext> xContext(::comphelper::getProcessComponentContext());
2781  uno::Reference<sdb::XDatabaseContext> xDBContext = sdb::DatabaseContext::create(xContext);
2782 
2783  OUString sNewName = INetURLObject::decode(rURL.getName(),
2785  sal_Int32 nExtLen = sExt.getLength();
2786  sNewName = sNewName.replaceAt(sNewName.getLength() - nExtLen - 1, nExtLen + 1, "");
2787 
2788  //find a unique name if sNewName already exists
2789  sFind = sNewName;
2790  sal_Int32 nIndex = 0;
2791  while (xDBContext->hasByName(sFind))
2792  sFind = sNewName + OUString::number(++nIndex);
2793 
2794  uno::Reference<uno::XInterface> xNewInstance;
2795  if (!bStore)
2796  {
2797  //odb-file
2798  uno::Any aDataSource = xDBContext->getByName(rURL.GetMainURL(INetURLObject::DecodeMechanism::NONE));
2799  aDataSource >>= xNewInstance;
2800  }
2801  else
2802  {
2803  xNewInstance = xDBContext->createInstance();
2804  uno::Reference<beans::XPropertySet> xDataProperties(xNewInstance, uno::UNO_QUERY);
2805 
2806  if (aURLAny.hasValue())
2807  xDataProperties->setPropertyValue("URL", aURLAny);
2808  if (aTableFilterAny.hasValue())
2809  xDataProperties->setPropertyValue("TableFilter", aTableFilterAny);
2810  if (aSuppressVersionsAny.hasValue())
2811  xDataProperties->setPropertyValue("SuppressVersionColumns", aSuppressVersionsAny);
2812  if (aInfoAny.hasValue())
2813  xDataProperties->setPropertyValue("Info", aInfoAny);
2814 
2815  if (DBConnURIType::FLAT == type && pSettings)
2816  {
2817  uno::Any aSettings = xDataProperties->getPropertyValue("Settings");
2818  uno::Reference < beans::XPropertySet > xDSSettings;
2819  aSettings >>= xDSSettings;
2820  ::comphelper::copyProperties(*pSettings, xDSSettings);
2821  xDSSettings->setPropertyValue("Extension", uno::makeAny(sExt));
2822  }
2823 
2824  uno::Reference<sdb::XDocumentDataSource> xDS(xNewInstance, uno::UNO_QUERY_THROW);
2825  uno::Reference<frame::XStorable> xStore(xDS->getDatabaseDocument(), uno::UNO_QUERY_THROW);
2826  OUString aOwnURL = getOwnURL(pDocShell);
2827  if (aOwnURL.isEmpty())
2828  {
2829  // Cannot embed, as embedded data source would need the URL of the parent document.
2830  OUString const sOutputExt = ".odb";
2831  OUString sHomePath(SvtPathOptions().GetWorkPath());
2832  utl::TempFile aTempFile(sNewName, true, &sOutputExt, pDestDir ? pDestDir : &sHomePath);
2833  const OUString& sTmpName = aTempFile.GetURL();
2834  xStore->storeAsURL(sTmpName, uno::Sequence<beans::PropertyValue>());
2835  }
2836  else
2837  {
2838  // Embed.
2839  OUString aStreamRelPath = "EmbeddedDatabase";
2840  uno::Reference<embed::XStorage> xStorage = pDocShell->GetStorage();
2841 
2842  // Refer to the sub-storage name in the document settings, so
2843  // we can load it again next time the file is imported.
2844  uno::Reference<lang::XMultiServiceFactory> xFactory(pDocShell->GetModel(), uno::UNO_QUERY);
2845  uno::Reference<beans::XPropertySet> xPropertySet(xFactory->createInstance("com.sun.star.document.Settings"), uno::UNO_QUERY);
2846  xPropertySet->setPropertyValue("EmbeddedDatabaseName", uno::makeAny(aStreamRelPath));
2847 
2848  // Store it only after setting the above property, so that only one data source gets registered.
2849  SwDBManager::StoreEmbeddedDataSource(xStore, xStorage, aStreamRelPath, aOwnURL);
2850  }
2851  }
2852  xDBContext->registerObject(sFind, xNewInstance);
2853  }
2854  catch (const uno::Exception&)
2855  {
2856  sFind.clear();
2857  }
2858  return sFind;
2859 }
2860 
2861 // Construct vnd.sun.star.pkg:// URL
2862 OUString ConstructVndSunStarPkgUrl(const OUString& rMainURL, const OUString& rStreamRelPath)
2863 {
2864  auto xContext(comphelper::getProcessComponentContext());
2865  auto xUri = css::uri::UriReferenceFactory::create(xContext)->parse(rMainURL);
2866  assert(xUri.is());
2867  xUri = css::uri::VndSunStarPkgUrlReferenceFactory::create(xContext)
2868  ->createVndSunStarPkgUrlReference(xUri);
2869  assert(xUri.is());
2870  return xUri->getUriReference() + "/"
2872  rStreamRelPath, INetURLObject::PART_FPATH,
2874 }
2875 }
2876 
2878 {
2879  sfx2::FileDialogHelper aDlgHelper(ui::dialogs::TemplateDescription::FILEOPEN_SIMPLE, FileDialogFlags::NONE, pParent);
2880  uno::Reference < ui::dialogs::XFilePicker3 > xFP = aDlgHelper.GetFilePicker();
2881 
2882  OUString sHomePath(SvtPathOptions().GetWorkPath());
2883  aDlgHelper.SetDisplayDirectory( sHomePath );
2884 
2885  OUString sFilterAll(SwResId(STR_FILTER_ALL));
2886  OUString sFilterAllData(SwResId(STR_FILTER_ALL_DATA));
2887  OUString sFilterSXB(SwResId(STR_FILTER_SXB));
2888  OUString sFilterSXC(SwResId(STR_FILTER_SXC));
2889  OUString sFilterSXW(SwResId(STR_FILTER_SXW));
2890  OUString sFilterDBF(SwResId(STR_FILTER_DBF));
2891  OUString sFilterXLS(SwResId(STR_FILTER_XLS));
2892  OUString sFilterDOC(SwResId(STR_FILTER_DOC));
2893  OUString sFilterTXT(SwResId(STR_FILTER_TXT));
2894  OUString sFilterCSV(SwResId(STR_FILTER_CSV));
2895 #ifdef _WIN32
2896  OUString sFilterMDB(SwResId(STR_FILTER_MDB));
2897  OUString sFilterACCDB(SwResId(STR_FILTER_ACCDB));
2898 #endif
2899  xFP->appendFilter( sFilterAll, "*" );
2900  xFP->appendFilter( sFilterAllData, "*.ods;*.sxc;*.odt;*.sxw;*.dbf;*.xls;*.xlsx;*.doc;*.docx;*.txt;*.csv");
2901 
2902  xFP->appendFilter( sFilterSXB, "*.odb" );
2903  xFP->appendFilter( sFilterSXC, "*.ods;*.sxc" );
2904  xFP->appendFilter( sFilterSXW, "*.odt;*.sxw" );
2905  xFP->appendFilter( sFilterDBF, "*.dbf" );
2906  xFP->appendFilter( sFilterXLS, "*.xls;*.xlsx" );
2907  xFP->appendFilter( sFilterDOC, "*.doc;*.docx" );
2908  xFP->appendFilter( sFilterTXT, "*.txt" );
2909  xFP->appendFilter( sFilterCSV, "*.csv" );
2910 #ifdef _WIN32
2911  xFP->appendFilter(sFilterMDB, "*.mdb;*.mde");
2912  xFP->appendFilter(sFilterACCDB, "*.accdb;*.accde");
2913 #endif
2914 
2915  xFP->setCurrentFilter( sFilterAll ) ;
2916  OUString sFind;
2917  if( ERRCODE_NONE == aDlgHelper.Execute() )
2918  {
2919  uno::Reference< beans::XPropertySet > aSettings;
2920  const INetURLObject aURL( xFP->getSelectedFiles().getConstArray()[0] );
2921  const DBConnURIType type = GetDBunoType( aURL );
2922 
2923  if( DBConnURIType::FLAT == type )
2924  {
2925  uno::Reference<uno::XComponentContext> xContext( ::comphelper::getProcessComponentContext() );
2926  uno::Reference < sdb::XTextConnectionSettings > xSettingsDlg = sdb::TextConnectionSettings::create(xContext);
2927  if( xSettingsDlg->execute() )
2928  aSettings.set( uno::Reference < beans::XPropertySet >( xSettingsDlg, uno::UNO_QUERY_THROW ) );
2929  }
2930  sFind = LoadAndRegisterDataSource_Impl( type, DBConnURIType::FLAT == type ? &aSettings : nullptr, aURL, nullptr, pDocShell );
2931 
2932  m_aUncommittedRegistrations.push_back(std::pair<SwDocShell*, OUString>(pDocShell, sFind));
2933  }
2934  return sFind;
2935 }
2936 
2937 void SwDBManager::StoreEmbeddedDataSource(const uno::Reference<frame::XStorable>& xStorable,
2938  const uno::Reference<embed::XStorage>& xStorage,
2939  const OUString& rStreamRelPath,
2940  const OUString& rOwnURL, bool bCopyTo)
2941 {
2942  // Construct vnd.sun.star.pkg:// URL for later loading, and TargetStorage/StreamRelPath for storing.
2943  OUString const sTmpName = ConstructVndSunStarPkgUrl(rOwnURL, rStreamRelPath);
2944 
2945  uno::Sequence<beans::PropertyValue> aSequence = comphelper::InitPropertySequence(
2946  {
2947  {"TargetStorage", uno::makeAny(xStorage)},
2948  {"StreamRelPath", uno::makeAny(rStreamRelPath)},
2949  {"BaseURI", uno::makeAny(rOwnURL)}
2950  });
2951  if (bCopyTo)
2952  xStorable->storeToURL(sTmpName, aSequence);
2953  else
2954  xStorable->storeAsURL(sTmpName, aSequence);
2955 }
2956 
2957 OUString SwDBManager::LoadAndRegisterDataSource(const OUString &rURI, const OUString *pDestDir)
2958 {
2959  return LoadAndRegisterDataSource_Impl( DBConnURIType::UNKNOWN, nullptr, INetURLObject(rURI), pDestDir, nullptr );
2960 }
2961 
2962 namespace
2963 {
2964  // tdf#117824 switch the embedded database away from using its current storage and point it to temporary storage
2965  // which allows the original storage to be deleted
2966  void switchEmbeddedDatabaseStorage(const uno::Reference<sdb::XDatabaseContext>& rDatabaseContext, const OUString& rName)
2967  {
2968  uno::Reference<sdb::XDocumentDataSource> xDS(rDatabaseContext->getByName(rName), uno::UNO_QUERY);
2969  if (!xDS)
2970  return;
2971  uno::Reference<document::XStorageBasedDocument> xStorageDoc(xDS->getDatabaseDocument(), uno::UNO_QUERY);
2972  if (!xStorageDoc)
2973  return;
2974  xStorageDoc->switchToStorage(comphelper::OStorageHelper::GetTemporaryStorage());
2975  }
2976 }
2977 
2978 void SwDBManager::RevokeDataSource(const OUString& rName)
2979 {
2980  uno::Reference<sdb::XDatabaseContext> xDatabaseContext = sdb::DatabaseContext::create(comphelper::getProcessComponentContext());
2981  if (xDatabaseContext->hasByName(rName))
2982  {
2983  switchEmbeddedDatabaseStorage(xDatabaseContext, rName);
2984  xDatabaseContext->revokeObject(rName);
2985  }
2986 }
2987 
2989 {
2990  uno::Reference<sdb::XDatabaseContext> xDatabaseContext = sdb::DatabaseContext::create(comphelper::getProcessComponentContext());
2991 
2992  OUString sDataSource = rData.sDataSource;
2993 
2994  // Fallback, just in case the document would contain an embedded data source, but no DB fields.
2995  if (sDataSource.isEmpty())
2996  sDataSource = "EmbeddedDatabase";
2997 
2998  SwDBManager::RevokeDataSource( sDataSource );
2999 
3000  // Encode the stream name and the real path into a single URL.
3001  const INetURLObject& rURLObject = rDocShell.GetMedium()->GetURLObject();
3002  OUString const aURL = ConstructVndSunStarPkgUrl(
3004  m_sEmbeddedName);
3005 
3006  uno::Reference<uno::XInterface> xDataSource(xDatabaseContext->getByName(aURL), uno::UNO_QUERY);
3007  xDatabaseContext->registerObject( sDataSource, xDataSource );
3008 
3009  // temp file - don't remember connection
3010  if (rData.sDataSource.isEmpty())
3011  m_aUncommittedRegistrations.push_back(std::pair<SwDocShell*, OUString>(nullptr, sDataSource));
3012 }
3013 
3015  const uno::Sequence<beans::PropertyValue>& rProperties)
3016 {
3017  //prevent second call
3018  if(m_pImpl->pMergeDialog)
3019  return ;
3020  OUString sDataSource, sDataTableOrQuery;
3021  uno::Sequence<uno::Any> aSelection;
3022 
3023  sal_Int32 nCmdType = sdb::CommandType::TABLE;
3024  uno::Reference< sdbc::XConnection> xConnection;
3025 
3026  svx::ODataAccessDescriptor aDescriptor(rProperties);
3027  sDataSource = aDescriptor.getDataSource();
3028  OSL_VERIFY(aDescriptor[svx::DataAccessDescriptorProperty::Command] >>= sDataTableOrQuery);
3029  OSL_VERIFY(aDescriptor[svx::DataAccessDescriptorProperty::CommandType] >>= nCmdType);
3030 
3032  aDescriptor[svx::DataAccessDescriptorProperty::Selection] >>= aSelection;
3034  aDescriptor[svx::DataAccessDescriptorProperty::Connection] >>= xConnection;
3035 
3036  if(sDataSource.isEmpty() || sDataTableOrQuery.isEmpty())
3037  {
3038  OSL_FAIL("PropertyValues missing or unset");
3039  return;
3040  }
3041 
3042  //always create a connection for the dialog and dispose it after the dialog has been closed
3043  SwDSParam* pFound = nullptr;
3044  if(!xConnection.is())
3045  {
3046  xConnection = SwDBManager::RegisterConnection(sDataSource);
3047  pFound = FindDSConnection(sDataSource, true);
3048  }
3050  m_pImpl->pMergeDialog = pFact->CreateMailMergeDlg( &rSh.GetView().GetViewFrame()->GetWindow(), rSh,
3051  sDataSource,
3052  sDataTableOrQuery,
3053  nCmdType,
3054  xConnection);
3055  if(m_pImpl->pMergeDialog->Execute() == RET_OK)
3056  {
3057  aDescriptor[svx::DataAccessDescriptorProperty::Selection] <<= m_pImpl->pMergeDialog->GetSelection();
3058 
3059  uno::Reference<sdbc::XResultSet> xResSet = m_pImpl->pMergeDialog->GetResultSet();
3060  if(xResSet.is())
3061  aDescriptor[svx::DataAccessDescriptorProperty::Cursor] <<= xResSet;
3062 
3063  // SfxObjectShellRef is ok, since there should be no control over the document lifetime here
3064  SfxObjectShellRef xDocShell = rSh.GetView().GetViewFrame()->GetObjectShell();
3065 
3066  lcl_emitEvent(SfxEventHintId::SwMailMerge, STR_SW_EVENT_MAIL_MERGE, xDocShell.get());
3067 
3068  // prepare mail merge descriptor
3069  SwMergeDescriptor aMergeDesc( m_pImpl->pMergeDialog->GetMergeType(), rSh, aDescriptor );
3070  aMergeDesc.sSaveToFilter = m_pImpl->pMergeDialog->GetSaveFilter();
3071  aMergeDesc.bCreateSingleFile = m_pImpl->pMergeDialog->IsSaveSingleDoc();
3072  aMergeDesc.bPrefixIsFilename = aMergeDesc.bCreateSingleFile;
3073  aMergeDesc.sPrefix = m_pImpl->pMergeDialog->GetTargetURL();
3074  if( !aMergeDesc.bCreateSingleFile && m_pImpl->pMergeDialog->IsGenerateFromDataBase() )
3075  {
3076  aMergeDesc.sDBcolumn = m_pImpl->pMergeDialog->GetColumnName();
3077  }
3078 
3079  Merge( aMergeDesc );
3080 
3081  lcl_emitEvent(SfxEventHintId::SwMailMergeEnd, STR_SW_EVENT_MAIL_MERGE_END, xDocShell.get());
3082 
3083  // reset the cursor inside
3084  xResSet = nullptr;
3085  aDescriptor[svx::DataAccessDescriptorProperty::Cursor] <<= xResSet;
3086  }
3087  if(pFound)
3088  {
3089  for (auto & pParam : m_DataSourceParams)
3090  {
3091  if (pParam.get() == pFound)
3092  {
3093  try
3094  {
3095  uno::Reference<lang::XComponent> xComp(pParam->xConnection, uno::UNO_QUERY);
3096  if(xComp.is())
3097  xComp->dispose();
3098  }
3099  catch(const uno::RuntimeException&)
3100  {
3101  //may be disposed already since multiple entries may have used the same connection
3102  }
3103  break;
3104  }
3105  //pFound doesn't need to be removed/deleted -
3106  //this has been done by the SwConnectionDisposedListener_Impl already
3107  }
3108  }
3109  m_pImpl->pMergeDialog.disposeAndClear();
3110 }
3111 
3113  const uno::Sequence< beans::PropertyValue>& rProperties)
3114 {
3115  OUString sDataSource, sDataTableOrQuery;
3116  uno::Reference<sdbc::XResultSet> xResSet;
3117  uno::Sequence<uno::Any> aSelection;
3118  sal_Int16 nCmdType = sdb::CommandType::TABLE;
3119  uno::Reference< sdbc::XConnection> xConnection;
3120  for(const beans::PropertyValue& rValue : rProperties)
3121  {
3122  if ( rValue.Name == "DataSourceName" )
3123  rValue.Value >>= sDataSource;
3124  else if ( rValue.Name == "Command" )
3125  rValue.Value >>= sDataTableOrQuery;
3126  else if ( rValue.Name == "Cursor" )
3127  rValue.Value >>= xResSet;
3128  else if ( rValue.Name == "Selection" )
3129  rValue.Value >>= aSelection;
3130  else if ( rValue.Name == "CommandType" )
3131  rValue.Value >>= nCmdType;
3132  else if ( rValue.Name == "ActiveConnection" )
3133  rValue.Value >>= xConnection;
3134  }
3135  if(sDataSource.isEmpty() || sDataTableOrQuery.isEmpty() || !xResSet.is())
3136  {
3137  OSL_FAIL("PropertyValues missing or unset");
3138  return;
3139  }
3140  uno::Reference< uno::XComponentContext > xContext( ::comphelper::getProcessComponentContext() );
3141  uno::Reference<sdbc::XDataSource> xSource;
3142  uno::Reference<container::XChild> xChild(xConnection, uno::UNO_QUERY);
3143  if(xChild.is())
3144  xSource.set(xChild->getParent(), uno::UNO_QUERY);
3145  if(!xSource.is())
3146  xSource = dbtools::getDataSource(sDataSource, xContext);
3147  uno::Reference< sdbcx::XColumnsSupplier > xColSupp( xResSet, uno::UNO_QUERY );
3148  SwDBData aDBData;
3149  aDBData.sDataSource = sDataSource;
3150  aDBData.sCommand = sDataTableOrQuery;
3151  aDBData.nCommandType = nCmdType;
3152 
3155  xSource,
3156  xColSupp,
3157  aDBData ));
3158  if( RET_OK == pDlg->Execute() )
3159  {
3160  OUString sDummy;
3161  if(!xConnection.is())
3162  xConnection = xSource->getConnection(sDummy, sDummy);
3163  try
3164  {
3165  pDlg->DataToDoc( aSelection , xSource, xConnection, xResSet);
3166  }
3167  catch (const uno::Exception&)
3168  {
3169  css::uno::Any ex( cppu::getCaughtException() );
3170  SAL_WARN("sw.mailmerge", "exception caught: " << exceptionToString(ex));
3171  }
3172  }
3173 }
3174 
3175 uno::Reference<sdbc::XDataSource> SwDBManager::getDataSourceAsParent(const uno::Reference< sdbc::XConnection>& _xConnection,const OUString& _sDataSourceName)
3176 {
3177  uno::Reference<sdbc::XDataSource> xSource;
3178  try
3179  {
3180  uno::Reference<container::XChild> xChild(_xConnection, uno::UNO_QUERY);
3181  if ( xChild.is() )
3182  xSource.set(xChild->getParent(), uno::UNO_QUERY);
3183  if ( !xSource.is() )
3184  xSource = dbtools::getDataSource(_sDataSourceName, ::comphelper::getProcessComponentContext());
3185  }
3186  catch (const uno::Exception&)
3187  {
3188  css::uno::Any ex( cppu::getCaughtException() );
3189  SAL_WARN("sw.mailmerge", "exception caught in getDataSourceAsParent(): " << exceptionToString(ex));
3190  }
3191  return xSource;
3192 }
3193 
3194 uno::Reference<sdbc::XResultSet> SwDBManager::createCursor(const OUString& _sDataSourceName,
3195  const OUString& _sCommand,
3196  sal_Int32 _nCommandType,
3197  const uno::Reference<sdbc::XConnection>& _xConnection,
3198  const SwView* pView)
3199 {
3200  uno::Reference<sdbc::XResultSet> xResultSet;
3201  try
3202  {
3203  uno::Reference< lang::XMultiServiceFactory > xMgr( ::comphelper::getProcessServiceFactory() );
3204  if( xMgr.is() )
3205  {
3206  uno::Reference<uno::XInterface> xInstance = xMgr->createInstance("com.sun.star.sdb.RowSet");
3207  uno::Reference<beans::XPropertySet> xRowSetPropSet(xInstance, uno::UNO_QUERY);
3208  if(xRowSetPropSet.is())
3209  {
3210  xRowSetPropSet->setPropertyValue("DataSourceName", uno::makeAny(_sDataSourceName));
3211  xRowSetPropSet->setPropertyValue("ActiveConnection", uno::makeAny(_xConnection));
3212  xRowSetPropSet->setPropertyValue("Command", uno::makeAny(_sCommand));
3213  xRowSetPropSet->setPropertyValue("CommandType", uno::makeAny(_nCommandType));
3214 
3215  uno::Reference< sdb::XCompletedExecution > xRowSet(xInstance, uno::UNO_QUERY);
3216 
3217  if ( xRowSet.is() )
3218  {
3219  weld::Window* pWindow = pView ? pView->GetFrameWeld() : nullptr;
3220  uno::Reference< task::XInteractionHandler > xHandler( task::InteractionHandler::createWithParent(comphelper::getComponentContext(xMgr), pWindow ? pWindow->GetXWindow() : nullptr), uno::UNO_QUERY_THROW );
3221  xRowSet->executeWithCompletion(xHandler);
3222  }
3223  xResultSet.set(xRowSet, uno::UNO_QUERY);
3224  }
3225  }
3226  }
3227  catch (const uno::Exception&)
3228  {
3229  css::uno::Any ex( cppu::getCaughtException() );
3230  SAL_WARN("sw.mailmerge", "Caught exception while creating a new RowSet: " << exceptionToString(ex));
3231  }
3232  return xResultSet;
3233 }
3234 
3235 void SwDBManager::setEmbeddedName(const OUString& rEmbeddedName, SwDocShell& rDocShell)
3236 {
3237  bool bLoad = m_sEmbeddedName != rEmbeddedName && !rEmbeddedName.isEmpty();
3238  bool bRegisterListener = m_sEmbeddedName.isEmpty() && !rEmbeddedName.isEmpty();
3239 
3240  m_sEmbeddedName = rEmbeddedName;
3241 
3242  if (bLoad)
3243  {
3244  uno::Reference<embed::XStorage> xStorage = rDocShell.GetStorage();
3245  // It's OK that we don't have the named sub-storage yet, in case
3246  // we're in the process of creating it.
3247  if (xStorage->hasByName(rEmbeddedName))
3248  LoadAndRegisterEmbeddedDataSource(rDocShell.GetDoc()->GetDBData(), rDocShell);
3249  }
3250 
3251  if (bRegisterListener)
3252  // Register a remove listener, so we know when the embedded data source is removed.
3253  m_pImpl->m_xDataSourceRemovedListener = new SwDataSourceRemovedListener(*this);
3254 }
3255 
3256 const OUString& SwDBManager::getEmbeddedName() const
3257 {
3258  return m_sEmbeddedName;
3259 }
3260 
3262 {
3263  return m_pDoc;
3264 }
3265 
3267 {
3268  if (m_pImpl->m_xDataSourceRemovedListener.is())
3269  {
3270  m_pImpl->m_xDataSourceRemovedListener->Dispose();
3271  m_pImpl->m_xDataSourceRemovedListener.clear();
3272  }
3273 }
3274 
3276  : m_pDBManager(&rManager)
3277 {
3278 }
3279 
3280 void SwDBManager::ConnectionDisposedListener_Impl::disposing( const lang::EventObject& rSource )
3281 {
3282  ::SolarMutexGuard aGuard;
3283 
3284  if (!m_pDBManager) return; // we're disposed too!
3285 
3286  uno::Reference<sdbc::XConnection> xSource(rSource.Source, uno::UNO_QUERY);
3287  for (size_t nPos = m_pDBManager->m_DataSourceParams.size(); nPos; nPos--)
3288  {
3289  SwDSParam* pParam = m_pDBManager->m_DataSourceParams[nPos - 1].get();
3290  if(pParam->xConnection.is() &&
3291  (xSource == pParam->xConnection))
3292  {
3293  m_pDBManager->m_DataSourceParams.erase(
3294  m_pDBManager->m_DataSourceParams.begin() + nPos - 1);
3295  }
3296  }
3297 }
3298 
3299 std::shared_ptr<SwMailMergeConfigItem> SwDBManager::PerformMailMerge(SwView const * pView)
3300 {
3301  std::shared_ptr<SwMailMergeConfigItem> xConfigItem = pView->GetMailMergeConfigItem();
3302  if (!xConfigItem)
3303  return xConfigItem;
3304 
3305  svx::ODataAccessDescriptor aDescriptor;
3306  aDescriptor.setDataSource(xConfigItem->GetCurrentDBData().sDataSource);
3307  aDescriptor[ svx::DataAccessDescriptorProperty::Connection ] <<= xConfigItem->GetConnection().getTyped();
3308  aDescriptor[ svx::DataAccessDescriptorProperty::Cursor ] <<= xConfigItem->GetResultSet();
3309  aDescriptor[ svx::DataAccessDescriptorProperty::Command ] <<= xConfigItem->GetCurrentDBData().sCommand;
3310  aDescriptor[ svx::DataAccessDescriptorProperty::CommandType ] <<= xConfigItem->GetCurrentDBData().nCommandType;
3311  aDescriptor[ svx::DataAccessDescriptorProperty::Selection ] <<= xConfigItem->GetSelection();
3312 
3313  SwWrtShell& rSh = pView->GetWrtShell();
3314  xConfigItem->SetTargetView(nullptr);
3315 
3316  SwMergeDescriptor aMergeDesc(DBMGR_MERGE_SHELL, rSh, aDescriptor);
3317  aMergeDesc.pMailMergeConfigItem = xConfigItem.get();
3318  aMergeDesc.bCreateSingleFile = true;
3319  rSh.GetDBManager()->Merge(aMergeDesc);
3320 
3321  return xConfigItem;
3322 }
3323 
3325 {
3326  if (!m_aUncommittedRegistrations.empty())
3327  {
3328  SwView* pView = ( m_pDoc && m_pDoc->GetDocShell() ) ? m_pDoc->GetDocShell()->GetView() : nullptr;
3329  if (pView)
3330  {
3331  const std::shared_ptr<SwMailMergeConfigItem>& xConfigItem = pView->GetMailMergeConfigItem();
3332  if (xConfigItem)
3333  {
3334  xConfigItem->DisposeResultSet();
3335  xConfigItem->DocumentReloaded();
3336  }
3337  }
3338 
3339  for (auto it = m_aUncommittedRegistrations.begin(); it != m_aUncommittedRegistrations.end();)
3340  {
3341  if ((m_pDoc && it->first == m_pDoc->GetDocShell()) || it->first == nullptr)
3342  {
3343  RevokeDataSource(it->second);
3344  it = m_aUncommittedRegistrations.erase(it);
3345  }
3346  else
3347  ++it;
3348  }
3349  }
3350 }
3351 
3353 {
3354  for (auto aIt = m_aUncommittedRegistrations.begin(); aIt != m_aUncommittedRegistrations.end();)
3355  {
3356  if (aIt->first == m_pDoc->GetDocShell() || aIt->first == nullptr)
3357  {
3358  m_aNotUsedConnections.push_back(aIt->second);
3359  aIt = m_aUncommittedRegistrations.erase(aIt);
3360  }
3361  else
3362  aIt++;
3363  }
3364 }
3365 
3366 void SwDBManager::SetAsUsed(const OUString& rName)
3367 {
3368  auto aFound = std::find(m_aNotUsedConnections.begin(), m_aNotUsedConnections.end(), rName);
3369  if (aFound != m_aNotUsedConnections.end())
3370  m_aNotUsedConnections.erase(aFound);
3371 }
3372 
3374 {
3375  for (auto aIt = m_aNotUsedConnections.begin(); aIt != m_aNotUsedConnections.end();)
3376  {
3377  RevokeDataSource(*aIt);
3378  aIt = m_aNotUsedConnections.erase(aIt);
3379  }
3380 }
3381 
3382 /* vim:set shiftwidth=4 softtabstop=4 expandtab: */
void InsertLineBreak()
Definition: wrtsh1.cxx:897
virtual Point GetPosPixel() const
static bool lcl_ToNextRecord(SwDSParam *pParam, const SwDBNextRecord action=SwDBNextRecord::NEXT)
Definition: dbmgr.cxx:2278
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:1116
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:3324
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:973
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:1114
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:2428
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:563
OUString const & GetMailAddress() const
bool bEndOfDB
Definition: dbmgr.hxx:110
SwDocShell * GetDocShell()
Definition: doc.hxx:1340
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:2187
static const SwDBData & GetAddressDBName()
Definition: dbmgr.cxx:2601
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:2377
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:2341
bool HasValidRecord() const
Definition: dbmgr.hxx:131
IDocumentLinksAdministration const & getIDocumentLinksAdministration() const
Definition: doc.cxx:292
sal_uInt32 GetSelectedRecordId()
Definition: dbmgr.cxx:2346
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:2937
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:40
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:3280
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:2606
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:1124
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:577
static void Yield()
bool IsMergeError()
Definition: dbmgr.hxx:303
Any SAL_CALL getCaughtException()
#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:2563
void setEmbeddedName(const OUString &rEmbeddedName, SwDocShell &rDocShell)
Definition: dbmgr.cxx:3235
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:3352
SwDoc * GetDoc() const
Definition: viewsh.hxx:284
bool IsLabelDoc() const
Definition: edfld.cxx:385
ConnectionDisposedListener_Impl(SwDBManager &rMgr)
Definition: dbmgr.cxx:3275
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:2515
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:3194
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:3175
static void RevokeDataSource(const OUString &rName)
Unregister a data source.
Definition: dbmgr.cxx:2978
#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
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:1112
const IDocumentDeviceAccess & getIDocumentDeviceAccess() const
Provides access to the document device interface.
Definition: viewsh.cxx:2590
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:2988
vcl::Window & GetWindow() const
bool HasSelection() const
Definition: wrtsh.hxx:139
#define SW_MOD()
Definition: swmodule.hxx:255
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:663
sal_uInt16 GetPageCnt()
Definition: crsrsh.cxx:1279
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:3366
#define LANGUAGE_SYSTEM
bool GetMergeColumnCnt(const OUString &rColumnName, LanguageType nLanguage, OUString &rResult, double *pNumber)
Definition: dbmgr.cxx:2174
#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:2113
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:3112
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:2494
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:3373
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:1115
OString exceptionToString(const css::uno::Any &caught)
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:2363
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:2193
static std::shared_ptr< SwMailMergeConfigItem > PerformMailMerge(SwView const *pView)
Definition: dbmgr.cxx:3299
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:3266
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:1113
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:2615
#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:208
#define SAL_INFO(area, stream)
bool PutString(const OUString &)
SfxEventHintId
SwDoc * getDoc() const
Definition: dbmgr.cxx:3261
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:1138
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:1109
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:2090
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:2877
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:1733
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:1052
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:952
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:3014
CharClass & GetAppCharClass()
Definition: init.cxx:751
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:664
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:3256
void ToNextRecord(const OUString &rDataSource, const OUString &rTableOrQuery)
Definition: dbmgr.cxx:2257
SfxMedium * GetMedium() const
static OUString decode(OUString const &rText, DecodeMechanism eMechanism, rtl_TextEncoding eCharset=RTL_TEXTENCODING_UTF8)