1 /**************************************************************
2  *
3  * Licensed to the Apache Software Foundation (ASF) under one
4  * or more contributor license agreements.  See the NOTICE file
5  * distributed with this work for additional information
6  * regarding copyright ownership.  The ASF licenses this file
7  * to you under the Apache License, Version 2.0 (the
8  * "License"); you may not use this file except in compliance
9  * with the License.  You may obtain a copy of the License at
10  *
11  *   http://www.apache.org/licenses/LICENSE-2.0
12  *
13  * Unless required by applicable law or agreed to in writing,
14  * software distributed under the License is distributed on an
15  * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
16  * KIND, either express or implied.  See the License for the
17  * specific language governing permissions and limitations
18  * under the License.
19  *
20  *************************************************************/
21 
22 
23 
24 // MARKER(update_precomp.py): autogen include statement, do not remove
25 #include "precompiled_dbaccess.hxx"
26 
27 #include "dsnItem.hxx"
28 #ifndef DBAUI_CONNECTIONHELPER_HXX
29 #include "ConnectionHelper.hxx"
30 #endif
31 #ifndef _DBAUI_AUTOCONTROLS_HRC_
32 #include "AutoControls.hrc"
33 #endif
34 #ifndef _DBU_DLG_HRC_
35 #include "dbu_dlg.hrc"
36 #endif
37 #ifndef _DBU_MISC_HRC_
38 #include "dbu_misc.hrc"
39 #endif
40 #ifndef _SFXITEMSET_HXX
41 #include <svl/itemset.hxx>
42 #endif
43 #ifndef INCLUDED_SVTOOLS_MODULEOPTIONS_HXX
44 #include <unotools/moduleoptions.hxx>
45 #endif
46 #ifndef _SFX_FCONTNR_HXX
47 #include <sfx2/fcontnr.hxx>
48 #endif
49 #ifndef INCLUDED_SVTOOLS_PATHOPTIONS_HXX
50 #include <unotools/pathoptions.hxx>
51 #endif
52 #ifndef _SFXSTRITEM_HXX
53 #include <svl/stritem.hxx>
54 #endif
55 #ifndef _SFXENUMITEM_HXX
56 #include <svl/eitem.hxx>
57 #endif
58 #ifndef _SFXINTITEM_HXX
59 #include <svl/intitem.hxx>
60 #endif
61 #ifndef _DBAUI_DATASOURCEITEMS_HXX_
62 #include "dsitems.hxx"
63 #endif
64 #ifndef _DBA_DBACCESS_HELPID_HRC_
65 #include "dbaccess_helpid.hrc"
66 #endif
67 #ifndef _DBAUI_LOCALRESACCESS_HXX_
68 #include "localresaccess.hxx"
69 #endif
70 #ifndef _OSL_PROCESS_H_
71 #include <osl/process.h>
72 #endif
73 #ifndef _SV_MSGBOX_HXX
74 #include <vcl/msgbox.hxx>
75 #endif
76 #ifndef _FILEDLGHELPER_HXX
77 #include <sfx2/filedlghelper.hxx>
78 #endif
79 #ifndef _DBAUI_DBADMIN_HXX_
80 #include "dbadmin.hxx"
81 #endif
82 #ifndef _COMPHELPER_TYPES_HXX_
83 #include <comphelper/types.hxx>
84 #endif
85 #ifndef _VCL_STDTEXT_HXX
86 #include <vcl/stdtext.hxx>
87 #endif
88 #ifndef _DBAUI_SQLMESSAGE_HXX_
89 #include "sqlmessage.hxx"
90 #endif
91 #ifndef _DBAUI_ODBC_CONFIG_HXX_
92 #include "odbcconfig.hxx"
93 #endif
94 #ifndef _DBAUI_DSSELECT_HXX_
95 #include "dsselect.hxx"
96 #endif
97 #ifndef SVTOOLS_FILENOTATION_HXX_
98 #include <svl/filenotation.hxx>
99 #endif
100 #ifndef DBACCESS_SHARED_DBUSTRINGS_HRC
101 #include "dbustrings.hrc"
102 #endif
103 #ifndef _COM_SUN_STAR_UI_DIALOGS_XFOLDERPICKER_HPP_
104 #include <com/sun/star/ui/dialogs/XFolderPicker.hpp>
105 #endif
106 #ifndef _COM_SUN_STAR_SDBC_XROW_HPP_
107 #include <com/sun/star/sdbc/XRow.hpp>
108 #endif
109 #ifndef _COM_SUN_STAR_AWT_XWINDOW_HPP_
110 #include <com/sun/star/awt/XWindow.hpp>
111 #endif
112 // #106016# ------------------------------------
113 #ifndef _COM_SUN_STAR_TASK_XINTERACTIONHANDLER_HPP_
114 #include <com/sun/star/task/XInteractionHandler.hpp>
115 #endif
116 #ifndef _COM_SUN_STAR_TASK_XPROGRESSHANDLER_HPP_
117 #include <com/sun/star/ucb/XProgressHandler.hpp>
118 #endif
119 #ifndef DBAUI_TOOLS_HXX
120 #include "UITools.hxx"
121 #endif
122 #ifndef _UNOTOOLS_LOCALFILEHELPER_HXX
123 #include <unotools/localfilehelper.hxx>
124 #endif
125 #ifndef _UNOTOOLS_UCBHELPER_HXX
126 #include <unotools/ucbhelper.hxx>
127 #endif
128 #ifndef _UCBHELPER_COMMANDENVIRONMENT_HXX
129 #include <ucbhelper/commandenvironment.hxx>
130 #endif
131 #ifndef DBAUI_FILEPICKER_INTERACTION_HXX
132 #include "finteraction.hxx"
133 #endif
134 #ifndef _CONNECTIVITY_COMMONTOOLS_HXX_
135 #include <connectivity/CommonTools.hxx>
136 #endif
137 #ifndef _URLOBJ_HXX
138 #include <tools/urlobj.hxx>
139 #endif
140 #ifndef TOOLS_DIAGNOSE_EX_H
141 #include <tools/diagnose_ex.h>
142 #endif
143 #ifndef _SFX_DOCFILT_HACK_HXX
144 #include <sfx2/docfilt.hxx>
145 #endif
146 #if !defined(WINDOWS_VISTA_PSDK) && defined(WNT)
147 #define _ADO_DATALINK_BROWSE_
148 #endif
149 
150 #ifdef _ADO_DATALINK_BROWSE_
151 #if defined( WNT )
152     #include <tools/prewin.h>
153     #include <windows.h>
154     #include <tools/postwin.h>
155 #endif
156 #ifndef _SV_SYSDATA_HXX
157 #include <vcl/sysdata.hxx>
158 #endif
159 #ifndef _DBAUI_ADO_DATALINK_HXX_
160 #include "adodatalinks.hxx"
161 #endif
162 #endif //_ADO_DATALINK_BROWSE_
163 
164 #ifndef _COM_SUN_STAR_MOZILLA_XMOZILLABOOTSTRAP_HPP_
165 #include <com/sun/star/mozilla/XMozillaBootstrap.hpp>
166 #endif
167 #include <unotools/processfactory.hxx>
168 
169 
170 
171 //.........................................................................
172 namespace dbaui
173 {
174 //.........................................................................
175 	using namespace ::com::sun::star::uno;
176 	using namespace ::com::sun::star::ucb;
177 	using namespace ::com::sun::star::ui::dialogs;
178 	using namespace ::com::sun::star::sdbc;
179 	using namespace ::com::sun::star::beans;
180 	using namespace ::com::sun::star::lang;
181 	using namespace ::com::sun::star::container;
182 	using namespace ::com::sun::star::mozilla;
183 	using namespace ::dbtools;
184 	using namespace ::svt;
185 
186 
DBG_NAME(OConnectionHelper)187 DBG_NAME(OConnectionHelper)
188 
189     OConnectionHelper::OConnectionHelper( Window* pParent, const ResId& _rId, const SfxItemSet& _rCoreAttrs)
190         :OGenericAdministrationPage(pParent, _rId, _rCoreAttrs)
191         ,m_aFT_Connection   ( this, ResId( FT_AUTOBROWSEURL, *_rId.GetResMgr() ) )
192    		,m_aConnectionURL   ( this, ResId( ET_AUTOBROWSEURL, *_rId.GetResMgr() ) )
193         ,m_aPB_Connection   ( this, ResId( PB_AUTOBROWSEURL, *_rId.GetResMgr() ) )
194     {
195         DBG_CTOR(OConnectionHelper,NULL);
196 
197 		// extract the datasource type collection from the item set
198 		DbuTypeCollectionItem* pCollectionItem = PTR_CAST(DbuTypeCollectionItem, _rCoreAttrs.GetItem(DSID_TYPECOLLECTION));
199 		if (pCollectionItem)
200 			m_pCollection = pCollectionItem->getCollection();
201         m_aPB_Connection.SetClickHdl(LINK(this, OConnectionHelper, OnBrowseConnections));
202 		DBG_ASSERT(m_pCollection, "OConnectionHelper::OConnectionHelper : really need a DSN type collection !");
203         m_aConnectionURL.SetTypeCollection(m_pCollection);
204     }
205 
206 
~OConnectionHelper()207 	OConnectionHelper::~OConnectionHelper()
208 	{
209 
210         DBG_DTOR(OConnectionHelper,NULL);
211     }
212 
213 
214     // -----------------------------------------------------------------------
implInitControls(const SfxItemSet & _rSet,sal_Bool _bSaveValue)215 	void OConnectionHelper::implInitControls(const SfxItemSet& _rSet, sal_Bool _bSaveValue)
216 	{
217 		// check whether or not the selection is invalid or readonly (invalid implies readonly, but not vice versa)
218 		sal_Bool bValid, bReadonly;
219 		getFlags(_rSet, bValid, bReadonly);
220 
221 		m_aFT_Connection.Show();
222         m_aConnectionURL.Show();
223         m_aConnectionURL.ShowPrefix( ::dbaccess::DST_JDBC == m_pCollection->determineType(m_eType) );
224 
225         sal_Bool bEnableBrowseButton = m_pCollection->supportsBrowsing( m_eType );
226 		m_aPB_Connection.Show( bEnableBrowseButton );
227 
228 		SFX_ITEMSET_GET(_rSet, pUrlItem, SfxStringItem, DSID_CONNECTURL, sal_True);
229 
230 		// forward the values to the controls
231 		if ( bValid )
232 		{
233 			String sUrl = pUrlItem->GetValue();
234 			setURL( sUrl );
235 
236 			checkTestConnection();
237 			m_aConnectionURL.ClearModifyFlag();
238 		}
239 
240         OGenericAdministrationPage::implInitControls(_rSet, _bSaveValue);
241 	}
242 
243 	// -----------------------------------------------------------------------
implUpdateURLDependentStates() const244     void OConnectionHelper::implUpdateURLDependentStates() const
245     {
246         OSL_PRECOND( m_pAdminDialog, "OConnectionHelper::implUpdateURLDependentStates: no admin dialog!" );
247         if ( !m_pAdminDialog )
248             return;
249 
250         if ( m_pCollection->isFileSystemBased(m_eType) )
251             m_pAdminDialog->enableConfirmSettings( getURLNoPrefix().Len() > 0 );
252     }
253 
254 	// -----------------------------------------------------------------------
255 	IMPL_LINK(OConnectionHelper, OnBrowseConnections, PushButton*, /*_pButton*/)
256 	{
257 		OSL_ENSURE(m_pAdminDialog,"No Admin dialog set! ->GPF");
258         const ::dbaccess::DATASOURCE_TYPE eType = m_pCollection->determineType(m_eType);
259 		switch ( eType )
260 		{
261 			case  ::dbaccess::DST_DBASE:
262 			case  ::dbaccess::DST_FLAT:
263 			{
264 				try
265 				{
266 					::rtl::OUString sFolderPickerService = ::rtl::OUString::createFromAscii(SERVICE_UI_FOLDERPICKER);
267 					Reference< XFolderPicker > xFolderPicker(m_xORB->createInstance(sFolderPickerService), UNO_QUERY);
268 					if (!xFolderPicker.is())
269 					{
270 						ShowServiceNotAvailableError(GetParent(), sFolderPickerService, sal_True);
271 						break;
272 					}
273 
274 					sal_Bool bDoBrowse = sal_False;
275 					String sOldPath = getURLNoPrefix();
276 					do
277 					{
278 						if (sOldPath.Len())
279 							xFolderPicker->setDisplayDirectory(sOldPath);
280 						if (0 == xFolderPicker->execute())
281 							// cancelled by the user
282 							return 0L;
283 
284 						sOldPath = xFolderPicker->getDirectory();
285 						switch (checkPathExistence(sOldPath))
286 						{
287 							case RET_RETRY:
288 								bDoBrowse = sal_True;
289 								break;
290 							case RET_CANCEL:
291 								return 0L;
292 							default:
293 								break;
294 						}
295 					}
296 					while (bDoBrowse);
297 
298 					String sSelectedDirectory = xFolderPicker->getDirectory();
299 					INetURLObject aSelectedDirectory( sSelectedDirectory, INetURLObject::WAS_ENCODED, RTL_TEXTENCODING_UTF8 );
300 
301 					// for UI purpose, we don't want to have the path encoded
302 					sSelectedDirectory = aSelectedDirectory.GetMainURL( INetURLObject::DECODE_WITH_CHARSET, RTL_TEXTENCODING_UTF8  );
303 
304 					setURLNoPrefix( sSelectedDirectory );
305                     SetRoadmapStateValue(sal_True);
306 					callModifiedHdl();
307 				}
308                 catch( const Exception& )
309                 {
310                     DBG_UNHANDLED_EXCEPTION();
311                 }
312 			}
313 			break;
314 			case  ::dbaccess::DST_CALC:
315 			{
316                 SvtModuleOptions aModule;
317 				::sfx2::FileDialogHelper aFileDlg(WB_3DLOOK | WB_STDMODAL | WB_OPEN
318 												,aModule.GetFactoryEmptyDocumentURL(SvtModuleOptions::E_CALC)
319 												,SFX_FILTER_IMPORT);
320 				askForFileName(aFileDlg);
321 			}
322 			break;
323 			case  ::dbaccess::DST_MSACCESS:
324 			{
325 				const ::rtl::OUString sExt(RTL_CONSTASCII_USTRINGPARAM("*.mdb"));
326 				String sFilterName(ModuleRes (STR_MSACCESS_FILTERNAME));
327 				::sfx2::FileDialogHelper aFileDlg(WB_3DLOOK | WB_STDMODAL | WB_OPEN);
328 				aFileDlg.AddFilter(sFilterName,sExt);
329                 aFileDlg.SetCurrentFilter(sFilterName);
330 				askForFileName(aFileDlg);
331             }
332             break;
333             case  ::dbaccess::DST_MSACCESS_2007:
334             {
335 				const ::rtl::OUString sAccdb(RTL_CONSTASCII_USTRINGPARAM("*.accdb"));
336                 String sFilterName2(ModuleRes (STR_MSACCESS_2007_FILTERNAME));
337                 ::sfx2::FileDialogHelper aFileDlg(WB_3DLOOK | WB_STDMODAL | WB_OPEN);
338                 aFileDlg.AddFilter(sFilterName2,sAccdb);
339 				aFileDlg.SetCurrentFilter(sFilterName2);
340 				askForFileName(aFileDlg);
341 			}
342 			break;
343 			case  ::dbaccess::DST_ADABAS:
344 			{
345 				// collect all names from the config dir
346 				// and all dir's of the DBWORK/wrk or DBROOT/wrk dir
347 				// compare the names
348 
349 				// collect the names of the installed databases
350 				StringBag aInstalledDBs;
351 				::rtl::OUString sAdabasConfigDir,sAdabasWorkDir,sRootDir;
352 				::rtl::OUString sEnvVarName(RTL_CONSTASCII_USTRINGPARAM("DBWORK"));
353 				rtl_uString* pDbVar = NULL;
354 				if(osl_getEnvironment(sEnvVarName.pData,&pDbVar) == osl_Process_E_None && pDbVar)
355 				{
356 					sAdabasWorkDir = pDbVar;
357 					String sURL;
358 					utl::LocalFileHelper::ConvertPhysicalNameToURL(sAdabasWorkDir,sURL);
359 					sAdabasWorkDir = sURL;
360 					rtl_uString_release(pDbVar);
361 					pDbVar = NULL;
362 				}
363 
364 				sEnvVarName = ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("DBCONFIG"));
365 				if(osl_getEnvironment(sEnvVarName.pData,&pDbVar) == osl_Process_E_None && pDbVar)
366 				{
367 					sAdabasConfigDir = pDbVar;
368 					String sURL;
369 					utl::LocalFileHelper::ConvertPhysicalNameToURL(sAdabasConfigDir,sURL);
370 					sAdabasConfigDir = sURL;
371 					rtl_uString_release(pDbVar);
372 					pDbVar = NULL;
373 				}
374 
375 				sEnvVarName = ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("DBROOT"));
376 				if(osl_getEnvironment(sEnvVarName.pData,&pDbVar) == osl_Process_E_None && pDbVar)
377 				{
378 					sRootDir = pDbVar;
379 					String sURL;
380 					utl::LocalFileHelper::ConvertPhysicalNameToURL(sRootDir,sURL);
381 					sRootDir = sURL;
382 					rtl_uString_release(pDbVar);
383 					pDbVar = NULL;
384 				}
385 
386 				sal_Bool bOldFashion = sAdabasConfigDir.getLength() && sAdabasWorkDir.getLength();
387 
388 				if(!bOldFashion) // we have a normal adabas installation
389 				{	 // so we check the local database names in $DBROOT/config
390 					sAdabasConfigDir	= sRootDir;
391 					sAdabasWorkDir		= sRootDir;
392 				}
393 
394 				if(sAdabasConfigDir.getLength() && sAdabasWorkDir.getLength() && sRootDir.getLength())
395 				{
396 
397 					aInstalledDBs	= getInstalledAdabasDBs(sAdabasConfigDir,sAdabasWorkDir);
398 
399 					if(!aInstalledDBs.size() && bOldFashion)
400 					{
401 						sAdabasConfigDir	= sRootDir;
402 						sAdabasWorkDir		= sRootDir;
403 						aInstalledDBs		= getInstalledAdabasDBs(sAdabasConfigDir,sAdabasWorkDir);
404 					}
405 
406 					ODatasourceSelectDialog aSelector(GetParent(), aInstalledDBs, true,m_pItemSetHelper->getWriteOutputSet());
407 					if (RET_OK == aSelector.Execute())
408 					{
409 						setURLNoPrefix(aSelector.GetSelected());
410 						//	checkCreateDatabase( ::dbaccess::DST_ADABAS);
411                         SetRoadmapStateValue(sal_True);
412 						callModifiedHdl();
413 					}
414 				}
415 				else
416 				{
417 					LocalResourceAccess aLocRes( PAGE_CONNECTION, RSC_TABPAGE );
418 					String sError = String(ModuleRes(STR_NO_ADABASE_DATASOURCES));
419 					ErrorBox aBox(this, WB_OK, sError);
420 					aBox.Execute();
421 				}
422 			}
423 			break;
424 			case  ::dbaccess::DST_MYSQL_ODBC:
425 			case  ::dbaccess::DST_ODBC:
426 			{
427 				// collect all ODBC data source names
428                 ::rtl::OUString sCurrDatasource = getURLNoPrefix();
429 				::rtl::OUString sDataSource;
430 				if ( getSelectedDataSource(sDataSource,sCurrDatasource) && sDataSource.getLength() )
431 				{
432 					setURLNoPrefix(sDataSource);
433                     SetRoadmapStateValue(sal_True);
434 					callModifiedHdl();
435 				}
436 				else
437 					return 1L;
438 			}
439 			break;
440 #ifdef _ADO_DATALINK_BROWSE_
441             case  ::dbaccess::DST_ADO:
442             {
443                 ::rtl::OUString sOldDataSource=getURLNoPrefix();
444                 ::rtl::OUString sNewDataSource;
445                 HWND hWnd = GetParent()->GetSystemData()->hWnd;
446                 sNewDataSource = getAdoDatalink((long)hWnd,sOldDataSource);
447                 if ( sNewDataSource.getLength() )
448                 {
449                     setURLNoPrefix(sNewDataSource);
450                     SetRoadmapStateValue(sal_True);
451                     callModifiedHdl();
452                 }
453                 else
454                     return 1L;
455 			}
456 			break;
457 #endif
458             case  ::dbaccess::DST_MOZILLA:
459             case  ::dbaccess::DST_THUNDERBIRD:
460             {
461 				MozillaProductType profileType = MozillaProductType_Mozilla;
462 				if (eType ==  ::dbaccess::DST_THUNDERBIRD)
463 					profileType = MozillaProductType_Thunderbird;
464 
465 				Reference<XMultiServiceFactory> xFactory = ::comphelper::getProcessServiceFactory();
466 				OSL_ENSURE( xFactory.is(), "can't get service factory" );
467 
468 				Reference<XInterface> xInstance = xFactory->createInstance(::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM("com.sun.star.mozilla.MozillaBootstrap")) );
469 				OSL_ENSURE( xInstance.is(), "failed to create instance" );
470 				Reference<XMozillaBootstrap> xMozillaBootstrap =  Reference<XMozillaBootstrap>(xInstance,UNO_QUERY);
471 				OSL_ENSURE( xMozillaBootstrap.is(), "failed to create instance" );
472 
473 				if (xMozillaBootstrap.is())
474 				{
475 					// collect all Mozilla Profiles
476 					::com::sun::star::uno::Sequence< ::rtl::OUString > list;
477 
478 					xMozillaBootstrap->getProfileList( profileType, list );
479 					const ::rtl::OUString * pArray = list.getConstArray();
480 
481 					sal_Int32 count = list.getLength();
482 
483 					StringBag aProfiles;
484 					for (sal_Int32 index=0; index < count; index++)
485 						aProfiles.insert(pArray[index]);
486 
487 
488 					// excute the select dialog
489 					ODatasourceSelectDialog aSelector(GetParent(), aProfiles, eType);
490 	                ::rtl::OUString sOldProfile=getURLNoPrefix();
491 
492 					if (sOldProfile.getLength())
493 						aSelector.Select(sOldProfile);
494 					else
495 						aSelector.Select(xMozillaBootstrap->getDefaultProfile(profileType));
496 
497 					if ( RET_OK == aSelector.Execute() )
498 						setURLNoPrefix(aSelector.GetSelected());
499 					break;
500 				}
501 			}
502             default:
503                 break;
504 		}
505 
506 		checkTestConnection();
507 
508 		return 0L;
509 	}
510 
511 	//-------------------------------------------------------------------------
512 
checkTestConnection()513     bool OConnectionHelper::checkTestConnection()
514     {
515         return true;
516     }
517 
518 	//-------------------------------------------------------------------------
impl_setURL(const String & _rURL,sal_Bool _bPrefix)519 	void OConnectionHelper::impl_setURL( const String& _rURL, sal_Bool _bPrefix )
520 	{
521 		String sURL( _rURL );
522 		DBG_ASSERT( m_pCollection, "OConnectionHelper::impl_setURL: have no interpreter for the URLs!" );
523 
524 		if ( m_pCollection && sURL.Len() )
525 		{
526 			if ( m_pCollection->isFileSystemBased( m_eType ) )
527 			{
528 				// get the tow parts: prefix and file URL
529 				String sTypePrefix, sFileURLEncoded;
530 				if ( _bPrefix )
531 				{
532 					sTypePrefix = m_pCollection->getPrefix( m_eType );
533 					sFileURLEncoded = m_pCollection->cutPrefix( sURL );
534 				}
535 				else
536 				{
537 					sFileURLEncoded = sURL;
538 				}
539 
540 				// substitute any variables
541 				sFileURLEncoded = SvtPathOptions().SubstituteVariable( sFileURLEncoded );
542 
543 				// decode the URL
544 				sURL = sTypePrefix;
545 				if ( sFileURLEncoded.Len() )
546 				{
547 					OFileNotation aFileNotation(sFileURLEncoded);
548 					// set this decoded URL as text
549 					sURL += String(aFileNotation.get(OFileNotation::N_SYSTEM));
550 				}
551 			}
552 		}
553 
554 		if ( _bPrefix )
555 			m_aConnectionURL.SetText( sURL );
556 		else
557 			m_aConnectionURL.SetTextNoPrefix( sURL );
558 
559         implUpdateURLDependentStates();
560 	}
561 
562 	//-------------------------------------------------------------------------
impl_getURL(sal_Bool _bPrefix) const563 	String OConnectionHelper::impl_getURL( sal_Bool _bPrefix ) const
564 	{
565 		// get the pure text
566 		String sURL = _bPrefix ? m_aConnectionURL.GetText() : m_aConnectionURL.GetTextNoPrefix();
567 
568 		DBG_ASSERT( m_pCollection, "OConnectionHelper::impl_getURL: have no interpreter for the URLs!" );
569 
570 		if ( m_pCollection && sURL.Len() )
571 		{
572 			if ( m_pCollection->isFileSystemBased( m_eType ) )
573 			{
574 				// get the tow parts: prefix and file URL
575 				String sTypePrefix, sFileURLDecoded;
576 				if ( _bPrefix )
577 				{
578 					sTypePrefix = m_pCollection->getPrefix( m_eType );
579 					sFileURLDecoded = m_pCollection->cutPrefix( sURL );
580 				}
581 				else
582 				{
583 					sFileURLDecoded = sURL;
584 				}
585 
586 				sURL = sTypePrefix;
587 				if ( sFileURLDecoded.Len() )
588 				{
589 					OFileNotation aFileNotation( sFileURLDecoded, OFileNotation::N_SYSTEM );
590 					sURL += String( aFileNotation.get( OFileNotation::N_URL ) );
591 				}
592 
593                 // encode the URL
594 				INetURLObject aFileURL( sFileURLDecoded, INetURLObject::ENCODE_ALL, RTL_TEXTENCODING_UTF8 );
595 				sFileURLDecoded = aFileURL.GetMainURL( INetURLObject::NO_DECODE );
596 			}
597 		}
598 		return sURL;
599 	}
600 
601 	//-------------------------------------------------------------------------
setURL(const String & _rURL)602 	void OConnectionHelper::setURL( const String& _rURL )
603 	{
604 		impl_setURL( _rURL, sal_True );
605 	}
606 
607 	//-------------------------------------------------------------------------
getURLNoPrefix() const608 	String OConnectionHelper::getURLNoPrefix( ) const
609 	{
610 		return impl_getURL( sal_False );
611 	}
612 
613 	//-------------------------------------------------------------------------
setURLNoPrefix(const String & _rURL)614 	void OConnectionHelper::setURLNoPrefix( const String& _rURL )
615 	{
616 		impl_setURL( _rURL, sal_False );
617 	}
618 
619 	//-------------------------------------------------------------------------
checkPathExistence(const String & _rURL)620 	sal_Int32 OConnectionHelper::checkPathExistence(const String& _rURL)
621 	{
622         IS_PATH_EXIST e_exists = pathExists(_rURL, sal_False);
623 		if (( e_exists == PATH_NOT_EXIST) || ( e_exists == PATH_NOT_KNOWN))
624 		{
625 			String sQuery(ModuleRes(STR_ASK_FOR_DIRECTORY_CREATION));
626 			OFileNotation aTransformer(_rURL);
627 			sQuery.SearchAndReplaceAscii("$path$", aTransformer.get(OFileNotation::N_SYSTEM));
628 
629 			m_bUserGrabFocus = sal_False;
630 			QueryBox aQuery(GetParent(), WB_YES_NO | WB_DEF_YES, sQuery);
631 			sal_Int32 nQueryResult = aQuery.Execute();
632 			m_bUserGrabFocus = sal_True;
633 
634 			switch (nQueryResult)
635 			{
636 				case RET_YES:
637 				{
638 					sal_Bool bTryCreate = sal_False;
639 					do
640 					{
641 						if ( !createDirectoryDeep(_rURL) )
642 						{	// could not create the directory
643 							sQuery = String(ModuleRes(STR_COULD_NOT_CREATE_DIRECTORY));
644 							sQuery.SearchAndReplaceAscii("$name$", aTransformer.get(OFileNotation::N_SYSTEM));
645 
646 							m_bUserGrabFocus = sal_False;
647 							QueryBox aWhatToDo(GetParent(), WB_RETRY_CANCEL | WB_DEF_RETRY, sQuery);
648 							nQueryResult = aWhatToDo.Execute();
649 							m_bUserGrabFocus = sal_True;
650 
651 							if (RET_RETRY == nQueryResult)
652 								bTryCreate = sal_True;
653 							else
654                             {
655                                 SetRoadmapStateValue(sal_False);
656 				                callModifiedHdl();
657 								return RET_RETRY;
658                             }
659 						}
660 					}
661 					while (bTryCreate);
662 				}
663 				break;
664 
665 				case RET_NO:
666                      // SetRoadmapStateValue(sal_False);
667 				    callModifiedHdl();
668 					return RET_OK;
669 
670 				default:
671 					// cancelled
672                     SetRoadmapStateValue(sal_False);
673 				    callModifiedHdl();
674                     return RET_CANCEL;
675 			}
676 		}
677 /*        else
678         {
679             // TODO: error msg
680             return RET_CANCEL;
681         } */
682         SetRoadmapStateValue(sal_True);
683 		callModifiedHdl();
684         return RET_OK;
685 	}
686 
687 
688 	//-------------------------------------------------------------------------
getInstalledAdabasDBDirs(const String & _rPath,const::ucbhelper::ResultSetInclude & _reResultSetInclude)689 	StringBag OConnectionHelper::getInstalledAdabasDBDirs(const String& _rPath,const ::ucbhelper::ResultSetInclude& _reResultSetInclude)
690 	{
691 		INetURLObject aNormalizer;
692 		aNormalizer.SetSmartProtocol(INET_PROT_FILE);
693 		aNormalizer.SetSmartURL(_rPath);
694 		String sAdabasConfigDir = aNormalizer.GetMainURL(INetURLObject::NO_DECODE);
695 
696 		::ucbhelper::Content aAdabasConfigDir;
697 		try
698 		{
699 			aAdabasConfigDir = ::ucbhelper::Content(sAdabasConfigDir, Reference< ::com::sun::star::ucb::XCommandEnvironment >());
700 		}
701 		catch(::com::sun::star::ucb::ContentCreationException&)
702 		{
703 			return StringBag();
704 		}
705 
706 		StringBag aInstalledDBs;
707 		sal_Bool bIsFolder = sal_False;
708 		try
709 		{
710 			bIsFolder = aAdabasConfigDir.isFolder();
711 		}
712 		catch(Exception&) // the exception is thrown when the path doesn't exists
713 		{
714 		}
715 		if (bIsFolder && aAdabasConfigDir.get().is())
716 		{	// we have a content for the directory, loop through all entries
717 			Sequence< ::rtl::OUString > aProperties(1);
718 			aProperties[0] = ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("Title"));
719 
720 			try
721 			{
722 				Reference< XResultSet > xFiles = aAdabasConfigDir.createCursor(aProperties, _reResultSetInclude);
723 				Reference< XRow > xRow(xFiles, UNO_QUERY);
724 				xFiles->beforeFirst();
725 				while (xFiles->next())
726 				{
727 #ifdef DBG_UTIL
728 					::rtl::OUString sName = xRow->getString(1);
729 #endif
730 					aInstalledDBs.insert(xRow->getString(1));
731 				}
732 			}
733 			catch(Exception&)
734 			{
735 				DBG_ERROR("OConnectionHelper::getInstalledAdabasDBDirs: could not enumerate the adabas config files!");
736 			}
737 		}
738 
739 
740 		return aInstalledDBs;
741 	}
742 	// -----------------------------------------------------------------------------
getInstalledAdabasDBs(const String & _rConfigDir,const String & _rWorkDir)743 	StringBag OConnectionHelper::getInstalledAdabasDBs(const String &_rConfigDir,const String &_rWorkDir)
744 	{
745 		String sAdabasConfigDir(_rConfigDir),sAdabasWorkDir(_rWorkDir);
746 
747 		if (sAdabasConfigDir.Len() && ('/' == sAdabasConfigDir.GetBuffer()[sAdabasConfigDir.Len() - 1]))
748 			sAdabasConfigDir.AppendAscii("config");
749 		else
750 			sAdabasConfigDir.AppendAscii("/config");
751 
752 		if (sAdabasWorkDir.Len() && ('/' == sAdabasWorkDir.GetBuffer()[sAdabasWorkDir.Len() - 1]))
753 			sAdabasWorkDir.AppendAscii("wrk");
754 		else
755 			sAdabasWorkDir.AppendAscii("/wrk");
756 		// collect the names of the installed databases
757 		StringBag aInstalledDBs;
758 		// collect the names of the installed databases
759 		StringBag aConfigDBs,aWrkDBs;
760 		aConfigDBs	= getInstalledAdabasDBDirs(sAdabasConfigDir,::ucbhelper::INCLUDE_DOCUMENTS_ONLY);
761 		aWrkDBs		= getInstalledAdabasDBDirs(sAdabasWorkDir,::ucbhelper::INCLUDE_FOLDERS_ONLY);
762 		ConstStringBagIterator aOuter = aConfigDBs.begin();
763         ConstStringBagIterator aOuterEnd = aConfigDBs.end();
764 		for(;aOuter != aOuterEnd;++aOuter)
765 		{
766 			ConstStringBagIterator aInner = aWrkDBs.begin();
767             ConstStringBagIterator aInnerEnd = aWrkDBs.end();
768 			for (;aInner != aInnerEnd; ++aInner)
769 			{
770 				if (aInner->equalsIgnoreAsciiCase(*aOuter))
771 				{
772 					aInstalledDBs.insert(*aInner);
773 					break;
774 				}
775 			}
776 		}
777 		return aInstalledDBs;
778 	}
779 	// #106016# -------------------------------------------------------------------
pathExists(const::rtl::OUString & _rURL,sal_Bool bIsFile) const780 	IS_PATH_EXIST OConnectionHelper::pathExists(const ::rtl::OUString& _rURL, sal_Bool bIsFile) const
781 	{
782 		::ucbhelper::Content aCheckExistence;
783 		sal_Bool bExists = sal_False;
784 		IS_PATH_EXIST eExists = PATH_NOT_EXIST;
785 		Reference< ::com::sun::star::task::XInteractionHandler > xInteractionHandler = Reference< ::com::sun::star::task::XInteractionHandler >(
786 			m_xORB->createInstance( ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM("com.sun.star.task.InteractionHandler") ) ), UNO_QUERY );
787 		OFilePickerInteractionHandler* pHandler = new OFilePickerInteractionHandler(xInteractionHandler);
788 		xInteractionHandler = pHandler;
789 
790 		Reference< XCommandEnvironment > xCmdEnv = new ::ucbhelper::CommandEnvironment( xInteractionHandler, Reference< XProgressHandler >() );
791 		try
792 		{
793 			aCheckExistence = ::ucbhelper::Content(_rURL, xCmdEnv );
794 			bExists = bIsFile? aCheckExistence.isDocument(): aCheckExistence.isFolder();
795 			eExists = bExists? PATH_EXIST: PATH_NOT_EXIST;
796 		}
797 		catch(const Exception&)
798 		{
799             eExists = ( pHandler && pHandler->isDoesNotExist() ) ? PATH_NOT_EXIST: (bIsFile ? PATH_NOT_EXIST : PATH_NOT_KNOWN);
800 	   	}
801 		return eExists;
802 	}
803 	//-------------------------------------------------------------------------
PreNotify(NotifyEvent & _rNEvt)804 	long OConnectionHelper::PreNotify( NotifyEvent& _rNEvt )
805 	{
806         if ( m_pCollection->isFileSystemBased(m_eType) )
807         {
808 			switch (_rNEvt.GetType())
809 			{
810 				case EVENT_GETFOCUS:
811 					if (m_aConnectionURL.IsWindowOrChild(_rNEvt.GetWindow()) && m_bUserGrabFocus)
812 					{	// a descendant of the URL edit field got the focus
813 						m_aConnectionURL.SaveValueNoPrefix();
814 					}
815 					break;
816 
817 				case EVENT_LOSEFOCUS:
818 					if (m_aConnectionURL.IsWindowOrChild(_rNEvt.GetWindow()) && m_bUserGrabFocus)
819 					{	// a descendant of the URL edit field lost the focus
820 						if (!commitURL())
821 							return 1L;	// handled
822 					}
823 					break;
824 			} // switch (_rNEvt.GetType())
825         }
826 
827 		return OGenericAdministrationPage::PreNotify( _rNEvt );
828 	}
829 
830 	//-------------------------------------------------------------------------
831 
createDirectoryDeep(const String & _rPathURL)832 	sal_Bool OConnectionHelper::createDirectoryDeep(const String& _rPathURL)
833 	{
834 		::rtl::OUString sPath(_rPathURL);
835 
836 		// get an URL object analyzing the URL for us ...
837 		INetURLObject aParser;
838 		aParser.SetURL(_rPathURL);
839 
840 		INetProtocol eProtocol = aParser.GetProtocol();
841 
842 		::std::vector< ::rtl::OUString > aToBeCreated;	// the to-be-created levels
843 
844 		// search a level which exists
845 		// #106016# ---------------------
846 		IS_PATH_EXIST eParentExists = PATH_NOT_EXIST;
847 		while ( eParentExists == PATH_NOT_EXIST && aParser.getSegmentCount())
848 		{
849 			aToBeCreated.push_back(aParser.getName());	// remember the local name for creation
850 			aParser.removeSegment();					// cut the local name
851 			eParentExists = pathExists(aParser.GetMainURL(INetURLObject::NO_DECODE), sal_False);
852 		}
853 
854 		if (!aParser.getSegmentCount())
855 			return sal_False;
856 
857 		// create all the missing levels
858 		try
859 		{
860 			// the parent content
861 			Reference< XCommandEnvironment > xEmptyEnv;
862 			::ucbhelper::Content aParent(aParser.GetMainURL(INetURLObject::NO_DECODE), xEmptyEnv);
863 
864 			::rtl::OUString sContentType;
865 			if ( INET_PROT_FILE == eProtocol )
866 			{
867 				sContentType = ::rtl::OUString::createFromAscii( "application/vnd.sun.staroffice.fsys-folder" );
868 				// the file UCP currently does not support the ContentType property
869 			}
870 			else
871 			{
872 				Any aContentType = aParent.getPropertyValue( ::rtl::OUString::createFromAscii( "ContentType" ) );
873 				aContentType >>= sContentType;
874 			}
875 
876 			// the properties which need to be set on the new content
877 			Sequence< ::rtl::OUString > aNewDirectoryProperties(1);
878 			aNewDirectoryProperties[0] = ::rtl::OUString::createFromAscii("Title");
879 
880 			// the values to be set
881 			Sequence< Any > aNewDirectoryAttributes(1);
882 
883 			// loop
884 			for (	::std::vector< ::rtl::OUString >::reverse_iterator aLocalName = aToBeCreated.rbegin();
885 					aLocalName != aToBeCreated.rend();
886 					++aLocalName
887 				)
888 			{
889 				aNewDirectoryAttributes[0] <<= *aLocalName;
890 				if (!aParent.insertNewContent(sContentType, aNewDirectoryProperties, aNewDirectoryAttributes, aParent))
891 					return sal_False;
892 			}
893 		}
894 		catch ( const Exception& )
895 		{
896             DBG_UNHANDLED_EXCEPTION();
897 			return sal_False;
898 		}
899 
900 		return sal_True;
901 	}
902 
903 
904 	// -----------------------------------------------------------------------
fillWindows(::std::vector<ISaveValueWrapper * > & _rControlList)905 	void OConnectionHelper::fillWindows(::std::vector< ISaveValueWrapper* >& _rControlList)
906 	{
907 		_rControlList.push_back(new ODisableWrapper<FixedText>(&m_aFT_Connection));
908 		_rControlList.push_back(new ODisableWrapper<PushButton>(&m_aPB_Connection));
909 	}
910 
911 
912 	// -----------------------------------------------------------------------
fillControls(::std::vector<ISaveValueWrapper * > & _rControlList)913 	void OConnectionHelper::fillControls(::std::vector< ISaveValueWrapper* >& _rControlList)
914 	{
915 		_rControlList.push_back( new OSaveValueWrapper<Edit>( &m_aConnectionURL ) );
916 	}
917 
918 	//-------------------------------------------------------------------------
commitURL()919 	sal_Bool OConnectionHelper::commitURL()
920 	{
921         String sURL;
922         String sOldPath;
923 		sOldPath = m_aConnectionURL.GetSavedValueNoPrefix();
924 		sURL = m_aConnectionURL.GetTextNoPrefix();
925 
926         if ( m_pCollection->isFileSystemBased(m_eType) )
927 		{
928 			if ( ( sURL != sOldPath ) && ( 0 != sURL.Len() ) )
929 			{	// the text changed since entering the control
930 
931 				// the path may be in system notation ....
932 				OFileNotation aTransformer(sURL);
933 				sURL = aTransformer.get(OFileNotation::N_URL);
934 
935                 const ::dbaccess::DATASOURCE_TYPE eType = m_pCollection->determineType(m_eType);
936 
937 				if ( ( ::dbaccess::DST_CALC == eType) || ( ::dbaccess::DST_MSACCESS == eType) || ( ::dbaccess::DST_MSACCESS_2007 == eType) )
938 				{ // #106016# --------------------------
939 					if( pathExists(sURL, sal_True) == PATH_NOT_EXIST )
940 					{
941 						String sFile = String( ModuleRes( STR_FILE_DOES_NOT_EXIST ) );
942 						sFile.SearchAndReplaceAscii("$file$", aTransformer.get(OFileNotation::N_SYSTEM));
943                         OSQLWarningBox( this, sFile ).Execute();
944 						setURLNoPrefix(sOldPath);
945                         SetRoadmapStateValue(sal_False);
946 		                callModifiedHdl();
947 						return sal_False;
948 					}
949 				}
950 				else
951 				{
952 					switch (checkPathExistence(sURL))
953 					{
954 						case RET_RETRY:
955 							m_bUserGrabFocus = sal_False;
956 							m_aConnectionURL.GrabFocus();
957 							m_bUserGrabFocus = sal_True;
958 							return sal_False;
959 
960 						case RET_CANCEL:
961 							setURLNoPrefix(sOldPath);
962 							return sal_False;
963 					}
964 				}
965 			}
966 		}
967 
968 		setURLNoPrefix(sURL);
969 		m_aConnectionURL.SaveValueNoPrefix();
970 		return sal_True;
971 	}
972     //-------------------------------------------------------------------------
askForFileName(::sfx2::FileDialogHelper & _aFileOpen)973     void OConnectionHelper::askForFileName(::sfx2::FileDialogHelper& _aFileOpen)
974 	{
975 		String sOldPath = getURLNoPrefix();
976 		if ( sOldPath.Len() )
977 			_aFileOpen.SetDisplayDirectory(sOldPath);
978 		else
979 			_aFileOpen.SetDisplayDirectory( SvtPathOptions().GetWorkPath() );
980 		if (0 == _aFileOpen.Execute())
981 		{
982 		    setURLNoPrefix(_aFileOpen.GetPath());
983             SetRoadmapStateValue(checkTestConnection());
984 			callModifiedHdl();
985 		}
986 	}
987 
988 //.........................................................................
989 }	// namespace dbaui
990 //.........................................................................
991