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