1 /*************************************************************************
2  *
3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
4  *
5  * Copyright 2000, 2010 Oracle and/or its affiliates.
6  *
7  * OpenOffice.org - a multi-platform office productivity suite
8  *
9  * This file is part of OpenOffice.org.
10  *
11  * OpenOffice.org is free software: you can redistribute it and/or modify
12  * it under the terms of the GNU Lesser General Public License version 3
13  * only, as published by the Free Software Foundation.
14  *
15  * OpenOffice.org is distributed in the hope that it will be useful,
16  * but WITHOUT ANY WARRANTY; without even the implied warranty of
17  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
18  * GNU Lesser General Public License version 3 for more details
19  * (a copy is included in the LICENSE file that accompanied this code).
20  *
21  * You should have received a copy of the GNU Lesser General Public License
22  * version 3 along with OpenOffice.org.  If not, see
23  * <http://www.openoffice.org/license.html>
24  * for a copy of the LGPLv3 License.
25  *
26  ************************************************************************/
27 
28 package com.sun.star.wiki;
29 
30 import com.sun.star.awt.MessageBoxButtons;
31 import com.sun.star.awt.XControl;
32 import com.sun.star.awt.XControlContainer;
33 import com.sun.star.awt.XDialog;
34 import com.sun.star.awt.XMessageBox;
35 import com.sun.star.awt.XMessageBoxFactory;
36 import com.sun.star.awt.XWindowPeer;
37 import com.sun.star.beans.NamedValue;
38 import com.sun.star.beans.PropertyValue;
39 import com.sun.star.beans.XPropertySet;
40 import com.sun.star.container.XContainerQuery;
41 import com.sun.star.container.XEnumeration;
42 import com.sun.star.container.XNameAccess;
43 import com.sun.star.container.XNameContainer;
44 import com.sun.star.document.XDocumentInfoSupplier;
45 import com.sun.star.frame.XModel;
46 import com.sun.star.frame.XModuleManager;
47 import com.sun.star.io.XInputStream;
48 import com.sun.star.io.XOutputStream;
49 import com.sun.star.io.XSeekable;
50 import com.sun.star.io.XStream;
51 import com.sun.star.lang.XMultiComponentFactory;
52 import com.sun.star.lang.XMultiServiceFactory;
53 import com.sun.star.lang.XComponent;
54 import com.sun.star.system.SystemShellExecuteFlags;
55 import com.sun.star.system.XSystemShellExecute;
56 import com.sun.star.task.UrlRecord;
57 import com.sun.star.task.XInteractionHandler;
58 import com.sun.star.task.XMasterPasswordHandling;
59 import com.sun.star.task.XPasswordContainer;
60 import com.sun.star.uno.AnyConverter;
61 import com.sun.star.uno.UnoRuntime;
62 import com.sun.star.uno.XComponentContext;
63 import com.sun.star.util.XChangesBatch;
64 import java.net.*;
65 import java.io.*;
66 import java.util.Hashtable;
67 import java.util.Random;
68 import javax.net.ssl.SSLException;
69 import javax.swing.text.html.HTMLEditorKit;
70 
71 import org.apache.commons.httpclient.HttpClient;
72 import org.apache.commons.httpclient.HostConfiguration;
73 import org.apache.commons.httpclient.HttpMethodBase;
74 import org.apache.commons.httpclient.cookie.CookiePolicy;
75 import org.apache.commons.httpclient.MultiThreadedHttpConnectionManager;
76 import org.apache.commons.httpclient.protocol.Protocol;
77 import org.apache.commons.httpclient.URI;
78 import org.apache.commons.httpclient.methods.GetMethod;
79 import org.apache.commons.httpclient.methods.PostMethod;
80 
81 public class Helper
82 {
83     public final static int GENERALSEND_ERROR = 0;
84     public final static int NOWIKIFILTER_ERROR = 1;
85     public final static int NOURLCONNECTION_ERROR = 2;
86     public final static int WRONGLOGIN_ERROR = 3;
87     public final static int INVALIDURL_ERROR = 4;
88     public final static int NOURL_ERROR = 5;
89 
90     public final static int DLG_SENDTITLE = 6;
91     public final static int DLG_WIKIARTICLE = 7;
92     public final static int DLG_NO = 8;
93     public final static int DLG_OK = 9;
94     public final static int DLG_YES = 10;
95     // 11 is reserved
96     public final static int DLG_ADDBUTTON = 12;
97     public final static int DLG_EDITBUTTON = 13;
98     public final static int DLG_SENDBUTTON = 14;
99     public final static int DLG_REMOVEBUTTON = 15;
100 
101     public final static int DLG_EDITSETTING_URLLABEL = 16;
102     public final static int DLG_EDITSETTING_USERNAMELABEL = 17;
103     public final static int DLG_EDITSETTING_PASSWORDLABEL = 18;
104     public final static int DLG_NEWWIKIPAGE_LABEL1 = 19;
105     public final static int DLG_SENDTOMEDIAWIKI_LABEL1 = 20;
106     public final static int DLG_SENDTOMEDIAWIKI_LABEL2 = 21;
107     public final static int DLG_SENDTOMEDIAWIKI_LABEL3 = 22;
108     public final static int DLG_SENDTOMEDIAWIKI_MINORCHECK = 23;
109     public final static int DLG_SENDTOMEDIAWIKI_BROWSERCHECK = 24;
110     public final static int UNKNOWNCERT_ERROR = 25;
111     public final static int DLG_MEDIAWIKI_TITLE = 26;
112     public final static int DLG_EDITSETTING_ACCOUNTLINE = 27;
113     public final static int DLG_EDITSETTING_WIKILINE = 28;
114     public final static int DLG_EDITSETTING_SAVEBOX = 29;
115     public final static int CANCELSENDING_ERROR = 30;
116     public final static int DLG_MEDIAWIKIEXTENSION_STRING = 31;
117     public final static int DLG_WIKIPAGEEXISTS_LABEL1 = 32;
118 
119     public final static int STRINGS_NUM = 33;
120 
121     private final static String[] m_pEntryNames = { "GeneralSendError",
122                                                     "NoWikiFilter",
123                                                     "NoConnectionToURL",
124                                                     "WrongLogin",
125                                                     "InvalidURL",
126                                                     "NoURL",
127                                                     "Dlg_SendTitle",
128                                                     "Dlg_WikiArticle",
129                                                     "Dlg_No",
130                                                     "Dlg_OK",
131                                                     "Dlg_Yes",
132                                                     null, // reserved
133                                                     "Dlg_AddButton",
134                                                     "Dlg_EditButton",
135                                                     "Dlg_SendButton",
136                                                     "Dlg_RemoveButton",
137                                                     "Dlg_EditSetting_UrlLabel",
138                                                     "Dlg_EditSetting_UsernameLabel",
139                                                     "Dlg_EditSetting_PasswordLabel",
140                                                     "Dlg_NewWikiPage_Label1",
141                                                     "Dlg_SendToMediaWiki_Label1",
142                                                     "Dlg_SendToMediaWiki_Label2",
143                                                     "Dlg_SendToMediaWiki_Label3",
144                                                     "Dlg_SendToMediaWiki_MinorCheck",
145                                                     "Dlg_SendToMediaWiki_BrowserCheck",
146                                                     "UnknownCert",
147                                                     "Dlg_MediaWiki_Title",
148                                                     "Dlg_EditSetting_AccountLine",
149                                                     "Dlg_EditSetting_WikiLine",
150                                                     "Dlg_EditSetting_SaveBox",
151                                                     "CancelSending",
152                                                     "Dlg_MediaWiki_Extension_String",
153                                                     "Dlg_WikiPageExists_Label1" };
154 
155     private static String[] m_pConfigStrings;
156 
157     private static final String sHTMLHeader = "<HTML><HEAD><meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\" /><TITLE></TITLE></HEAD><BODY>";
158     private static final String sHTMLFooter = "</BODY></HTML>";
159 
160     private static Random m_aRandom;
161     private static MultiThreadedHttpConnectionManager m_aConnectionManager;
162     private static HttpClient m_aClient;
163     private static boolean m_bAllowConnection = true;
164     private static Hashtable m_aAcceptedUnknownCerts;
165 
166     private static Boolean m_bShowInBrowser = null;
167 
168     private static XPasswordContainer m_xPasswordContainer;
169     private static XInteractionHandler m_xInteractionHandler;
170 
171     synchronized protected static String GetLocalizedString( XComponentContext xContext, int nID )
172         throws com.sun.star.uno.Exception
173     {
174         if ( nID >= STRINGS_NUM )
175             throw new com.sun.star.uno.RuntimeException();
176 
177         if ( m_pConfigStrings == null )
178         {
179             XNameAccess xNameAccess = GetConfigNameAccess( xContext, "org.openoffice.Office.Custom.WikiExtension/Strings" );
180 
181             String[] pStrings = new String[STRINGS_NUM];
182             for ( int nInd = 0; nInd < STRINGS_NUM; nInd++ )
183                 if ( m_pEntryNames[nInd] != null )
184                     pStrings[nInd] = AnyConverter.toString( xNameAccess.getByName( m_pEntryNames[nInd] ) );
185                 else
186                     pStrings[nInd] = "";
187 
188             m_pConfigStrings = pStrings;
189         }
190 
191         return m_pConfigStrings[nID];
192     }
193 
194     synchronized protected static HttpClient GetHttpClient()
195         throws WikiCancelException
196     {
197         if ( !m_bAllowConnection )
198             throw new WikiCancelException();
199 
200         if ( m_aConnectionManager == null )
201             m_aConnectionManager = new MultiThreadedHttpConnectionManager();
202 
203         if ( m_aClient == null )
204         {
205             m_aClient = new HttpClient( m_aConnectionManager );
206             m_aClient.getParams().setParameter( "http.protocol.cookie-policy", CookiePolicy.BROWSER_COMPATIBILITY );
207             m_aClient.getParams().setParameter( "http.protocol.single-cookie-header", Boolean.TRUE );
208             m_aClient.getParams().setParameter( "http.protocol.content-charset", "UTF-8" );
209         }
210 
211         return m_aClient;
212     }
213 
214     synchronized protected static void AllowConnection( boolean bAllow )
215     {
216         m_bAllowConnection = bAllow;
217         if ( !bAllow && m_aConnectionManager != null )
218         {
219             m_aClient = null;
220             m_aConnectionManager.shutdown();
221             m_aConnectionManager = null;
222         }
223     }
224 
225     synchronized protected static boolean IsConnectionAllowed()
226     {
227         return m_bAllowConnection;
228     }
229 
230     synchronized protected static boolean GetShowInBrowserByDefault( XComponentContext xContext )
231     {
232         if ( m_bShowInBrowser == null )
233         {
234             try
235             {
236                 XNameAccess xAccess = Helper.GetConfigNameAccess( xContext, "org.openoffice.Office.Custom.WikiExtension/Settings" );
237                 m_bShowInBrowser = new Boolean( AnyConverter.toBoolean( xAccess.getByName( "PreselectShowBrowser" ) ) );
238             }
239             catch( com.sun.star.uno.Exception e )
240             {
241                 e.printStackTrace();
242             }
243         }
244 
245         return m_bShowInBrowser.booleanValue();
246     }
247 
248     synchronized protected static void SetShowInBrowserByDefault( XComponentContext xContext, boolean bValue )
249     {
250         try
251         {
252             m_bShowInBrowser = new Boolean( bValue );
253 
254             XPropertySet xProps = Helper.GetConfigProps( xContext, "org.openoffice.Office.Custom.WikiExtension/Settings" );
255             xProps.setPropertyValue( "PreselectShowBrowser", new Boolean( bValue ) );
256             XChangesBatch xBatch = ( XChangesBatch ) UnoRuntime.queryInterface( XChangesBatch.class, xProps );
257             if ( xBatch != null )
258                 xBatch.commitChanges();
259         }
260         catch( Exception e )
261         {
262             e.printStackTrace();
263         }
264     }
265 
266     synchronized protected static XPasswordContainer GetPasswordContainer( XComponentContext xContext )
267         throws com.sun.star.uno.Exception
268     {
269         if ( m_xPasswordContainer == null && xContext != null )
270         {
271             XMultiComponentFactory xFactory = xContext.getServiceManager();
272             if ( xFactory != null )
273                 m_xPasswordContainer = (XPasswordContainer)UnoRuntime.queryInterface(
274                                         XPasswordContainer.class,
275                                         xFactory.createInstanceWithContext( "com.sun.star.task.PasswordContainer", xContext ) );
276         }
277 
278         if ( m_xPasswordContainer == null )
279             throw new com.sun.star.uno.RuntimeException();
280 
281         return m_xPasswordContainer;
282     }
283 
284     synchronized protected static XInteractionHandler GetInteractionHandler( XComponentContext xContext )
285         throws com.sun.star.uno.Exception
286     {
287         if ( m_xInteractionHandler == null && xContext != null )
288         {
289             XMultiComponentFactory xFactory = xContext.getServiceManager();
290             if ( xFactory != null )
291                 m_xInteractionHandler = ( XInteractionHandler )UnoRuntime.queryInterface(
292                                         XInteractionHandler.class,
293                                         xFactory.createInstanceWithContext( "com.sun.star.task.InteractionHandler", xContext ) );
294         }
295 
296         if ( m_xInteractionHandler == null )
297             throw new com.sun.star.uno.RuntimeException();
298 
299         return m_xInteractionHandler;
300     }
301 
302     protected static Protocol GetOwnHttps( int nPort )
303     {
304         return new Protocol( "https", new WikiProtocolSocketFactory(), ( ( nPort < 0 ) ? 443 : nPort ) );
305     }
306 
307     protected static String GetMainURL( String sWebPage, String sVURL )
308     {
309         String sResultURL = "";
310         try
311         {
312             StringReader aReader = new StringReader( sWebPage );
313             HTMLEditorKit.Parser aParser = GetHTMLParser();
314             EditPageParser aCallback = new EditPageParser();
315 
316             aParser.parse( aReader, aCallback, true );
317             sResultURL = aCallback.m_sMainURL;
318 
319             if ( !sResultURL.startsWith( "http" ) )
320             {
321                 //if the url is only relative then complete it
322                 URL aURL = new URL( sVURL );
323                 sResultURL = aURL.getProtocol() + "://" + aURL.getHost() + sResultURL;
324             }
325         }
326         catch( Exception e )
327         {
328             e.printStackTrace();
329         }
330 
331         if ( sResultURL.length() == 0 )
332         {
333             // usually that should not happen
334             // workaround: try to get index.php from the provided URL
335             int nIndex = sVURL.indexOf( "index.php" );
336             if ( nIndex >= 0 )
337                 sResultURL = sVURL.substring( 0, nIndex );
338         }
339 
340         return sResultURL;
341     }
342 
343     protected static String GetRedirectURL( String sWebPage, String sURL )
344     {
345         //scrape the HTML source and find the EditURL
346         // TODO/LATER: Use parser in future
347 
348         String sResultURL = "";
349         int nInd = sWebPage.indexOf( "http-equiv=\"refresh\"" );
350         if ( nInd != -1 )
351         {
352             int nContent = sWebPage.indexOf( "content=", nInd );
353             if ( nContent > 0 )
354             {
355                 int nURL = sWebPage.indexOf( "URL=", nContent );
356                 if ( nURL > 0 )
357                 {
358                     int nEndURL = sWebPage.indexOf( "\"", nURL );
359                     if ( nEndURL > 0 )
360                         sResultURL = sWebPage.substring( nURL + 4, nEndURL );
361                 }
362             }
363 
364             try
365             {
366                 URL aURL = new URL( sURL );
367                 if ( !sResultURL.startsWith( aURL.getProtocol() ))
368                 {
369                     //if the url is only relative then complete it
370                     if ( sResultURL.startsWith( "/" ) )
371                         sResultURL = aURL.getProtocol() + "://" + aURL.getHost() + sResultURL;
372                     else
373                         sResultURL = aURL.getProtocol() + "://" + aURL.getHost() + aURL.getPath() + sResultURL;
374                 }
375             }
376             catch ( MalformedURLException ex )
377             {
378                 ex.printStackTrace();
379             }
380         }
381 
382         return sResultURL;
383 
384     }
385 
386     protected static XInputStream SaveHTMLTemp( XComponentContext xContext, String sArticle )
387     {
388         XInputStream xResult = null;
389 
390         if ( xContext != null )
391         {
392             try
393             {
394                 Object oTempFile = xContext.getServiceManager().createInstanceWithContext( "com.sun.star.io.TempFile", xContext );
395                 XStream xStream = ( XStream ) UnoRuntime.queryInterface( XStream.class, oTempFile );
396                 XSeekable xSeekable = ( XSeekable ) UnoRuntime.queryInterface( XSeekable.class, oTempFile );
397                 if ( xStream != null && xSeekable != null )
398                 {
399                     XOutputStream xOutputStream = xStream.getOutputStream();
400                     XInputStream xInputStream = xStream.getInputStream();
401                     if ( xOutputStream != null && xInputStream != null )
402                     {
403                         String sHTML = sHTMLHeader.concat( sArticle );
404                         sHTML = sHTML.concat( sHTMLFooter );
405                         xOutputStream.writeBytes( sHTML.getBytes( "UTF-8" ) );
406                         // xOutputStream.closeOutput();
407                         xSeekable.seek( 0 );
408 
409                         xResult = xInputStream;
410                     }
411                 }
412             }
413             catch ( Exception ex )
414             {
415                 ex.printStackTrace();
416             }
417         }
418 
419         return xResult;
420     }
421 
422 
423     protected static String CreateTempFile( XComponentContext xContext )
424     {
425         String sURL = "";
426         try
427         {
428             Object oTempFile = xContext.getServiceManager().createInstanceWithContext( "com.sun.star.io.TempFile", xContext );
429             XPropertySet xPropertySet = ( XPropertySet ) UnoRuntime.queryInterface( XPropertySet.class, oTempFile );
430             xPropertySet.setPropertyValue( "RemoveFile", Boolean.FALSE );
431             sURL = ( String ) xPropertySet.getPropertyValue( "Uri" );
432 
433             XInputStream xInputStream = ( XInputStream ) UnoRuntime.queryInterface( XInputStream.class, oTempFile );
434             xInputStream.closeInput();
435             XOutputStream xOutputStream = ( XOutputStream ) UnoRuntime.queryInterface( XOutputStream.class, oTempFile );
436             xOutputStream.closeOutput();
437         } catch ( com.sun.star.uno.Exception ex )
438         {
439             ex.printStackTrace();
440         }
441         return sURL;
442     }
443 
444     protected static String EachLine( String sURL )
445     {
446         String sText = "";
447         try
448         {
449             URL aURL = new URL( sURL );
450             File aFile = new File( aURL.getFile() );
451             InputStreamReader aInputReader = new InputStreamReader( new FileInputStream( aFile ), "UTF-8" );
452             BufferedReader aBufReader = new BufferedReader( aInputReader );
453 
454             StringBuffer aBuf = new StringBuffer();
455             String sEachLine = aBufReader.readLine();
456 
457             while( sEachLine != null )
458             {
459                 aBuf.append( sEachLine );
460                 aBuf.append( "\n" );
461 
462                 sEachLine = aBufReader.readLine();
463             }
464             sText = aBuf.toString();
465         } catch ( Exception e )
466         {
467             e.printStackTrace();
468         }
469         return sText;
470     }
471 
472     protected static String GetDocTitle( XModel xDoc )
473     {
474         String sTitle = "";
475         XDocumentInfoSupplier xDocInfoSup = ( XDocumentInfoSupplier ) UnoRuntime.queryInterface( XDocumentInfoSupplier.class, xDoc );
476         XPropertySet xPropSet = ( XPropertySet ) UnoRuntime.queryInterface( XPropertySet.class, xDocInfoSup.getDocumentInfo() );
477         try
478         {
479             sTitle = ( String ) xPropSet.getPropertyValue( "Title" );
480         } catch ( Exception ex )
481         {
482             ex.printStackTrace();
483         }
484         return sTitle;
485     }
486 
487     protected static void SetDocTitle( XModel xDoc, String sTitle )
488     {
489         XDocumentInfoSupplier xDocInfoSup = ( XDocumentInfoSupplier ) UnoRuntime.queryInterface( XDocumentInfoSupplier.class, xDoc );
490         if ( xDocInfoSup != null )
491         {
492             XPropertySet xPropSet = ( XPropertySet ) UnoRuntime.queryInterface( XPropertySet.class, xDocInfoSup.getDocumentInfo() );
493             if ( xPropSet != null )
494             {
495                 try
496                 {
497                     xPropSet.setPropertyValue( "Title", sTitle );
498                 }
499                 catch ( Exception ex )
500                 {
501                     ex.printStackTrace();
502                 }
503             }
504         }
505     }
506 
507     protected static String GetDocServiceName( XComponentContext xContext, XModel xModel )
508     {
509         String aDocServiceName = "";
510         if ( xModel != null && xContext != null )
511         {
512             try
513             {
514                 XMultiComponentFactory xFactory = xContext.getServiceManager();
515                 if ( xFactory == null )
516                     throw new com.sun.star.uno.RuntimeException();
517 
518                 Object oModuleManager = xFactory.createInstanceWithContext( "com.sun.star.frame.ModuleManager", xContext );
519                 XModuleManager xModuleManager = ( XModuleManager ) UnoRuntime.queryInterface( XModuleManager.class, oModuleManager );
520                 if ( xModuleManager != null )
521                     aDocServiceName = xModuleManager.identify( xModel );
522             }
523             catch( java.lang.Exception e )
524             {
525                 e.printStackTrace();
526             }
527         }
528 
529         return aDocServiceName;
530     }
531 
532     protected static String GetFilterName( XComponentContext xContext, String aTypeName, String aDocServiceName )
533     {
534         String aFilterName = "";
535         if ( xContext != null && aTypeName != null && aTypeName.length() != 0
536           && aDocServiceName != null && aDocServiceName.length() != 0 )
537         {
538             try
539             {
540                 Object oFilterFactory = xContext.getServiceManager().createInstanceWithContext( "com.sun.star.document.FilterFactory", xContext );
541                 XContainerQuery xQuery = ( XContainerQuery )UnoRuntime.queryInterface( XContainerQuery.class, oFilterFactory );
542                 if ( xQuery != null )
543                 {
544                     NamedValue[] aRequest = new NamedValue[2];
545                     aRequest[0] = new NamedValue( "Type", aTypeName );
546                     aRequest[1] = new NamedValue( "DocumentService", aDocServiceName );
547 
548                     XEnumeration xSet = xQuery.createSubSetEnumerationByProperties( aRequest );
549                     if ( xSet != null )
550                     {
551                         boolean bAcceptable = false;
552                         while ( xSet.hasMoreElements() && !bAcceptable )
553                         {
554                             PropertyValue[] pFilterProps = ( PropertyValue[] )AnyConverter.toArray( xSet.nextElement() );
555                             if ( pFilterProps != null )
556                             {
557                                 int nLen = pFilterProps.length;
558                                 String aTmpFilter = null;
559 
560                                 for ( int nInd = 0; nInd < nLen; nInd++ )
561                                 {
562                                     if ( pFilterProps[nInd].Name.equals( "Name" ) )
563                                         aTmpFilter = AnyConverter.toString( pFilterProps[nInd].Value );
564                                     else if ( pFilterProps[nInd].Name.equals( "Flags" ) )
565                                         bAcceptable = ( ( AnyConverter.toInt( pFilterProps[nInd].Value ) & 2 ) == 2 ); // must allow export
566                                 }
567 
568                                 if ( bAcceptable )
569                                     aFilterName = aTmpFilter;
570                             }
571                         }
572                     }
573                 }
574             }
575             catch( java.lang.Exception e )
576             {
577                 e.printStackTrace();
578             }
579         }
580 
581         return aFilterName;
582     }
583 
584     protected static XMultiServiceFactory GetConfigurationProvider( XComponentContext xContext )
585         throws com.sun.star.uno.Exception
586     {
587         XMultiServiceFactory xConfigurationProvider = null;
588         if ( xContext != null )
589         {
590             XMultiComponentFactory xFactory = xContext.getServiceManager();
591             Object oConfigProvider = xFactory.createInstanceWithContext( "com.sun.star.configuration.ConfigurationProvider", xContext );
592             xConfigurationProvider = ( XMultiServiceFactory ) UnoRuntime.queryInterface( XMultiServiceFactory.class, oConfigProvider );
593         }
594 
595         if ( xConfigurationProvider == null )
596             throw new com.sun.star.uno.RuntimeException();
597 
598         return xConfigurationProvider;
599     }
600 
601     protected static Object GetConfig( XComponentContext xContext, String sNodepath, boolean bWriteAccess )
602         throws com.sun.star.uno.Exception
603     {
604         if ( xContext == null || sNodepath == null )
605             throw new com.sun.star.uno.RuntimeException();
606 
607         PropertyValue aVal = new PropertyValue();
608         aVal.Name = "nodepath";
609         aVal.Value = sNodepath;
610         Object[] aArgs = new Object[1];
611         aArgs[0] = aVal;
612 
613         return GetConfigurationProvider( xContext ).createInstanceWithArguments(
614                                     ( bWriteAccess ? "com.sun.star.configuration.ConfigurationUpdateAccess"
615                                                    : "com.sun.star.configuration.ConfigurationAccess" ),
616                                     aArgs );
617     }
618 
619     protected static XPropertySet GetConfigProps( XComponentContext xContext, String sNodepath )
620         throws com.sun.star.uno.Exception
621     {
622         XPropertySet xProps = ( XPropertySet ) UnoRuntime.queryInterface( XPropertySet.class, GetConfig( xContext, sNodepath, true ) );
623         if ( xProps == null )
624             throw new com.sun.star.uno.RuntimeException();
625 
626         return xProps;
627     }
628 
629 
630     protected static XNameContainer GetConfigNameContainer( XComponentContext xContext, String sNodepath )
631         throws com.sun.star.uno.Exception
632     {
633         XNameContainer xContainer = ( XNameContainer ) UnoRuntime.queryInterface( XNameContainer.class, GetConfig( xContext, sNodepath, true ) );
634         if ( xContainer == null )
635             throw new com.sun.star.uno.RuntimeException();
636 
637         return xContainer;
638     }
639 
640     protected static XNameAccess GetConfigNameAccess( XComponentContext xContext, String sNodepath )
641         throws com.sun.star.uno.Exception
642     {
643         XNameAccess xNameAccess = ( XNameAccess ) UnoRuntime.queryInterface( XNameAccess.class, GetConfig( xContext, sNodepath, false ) );
644         if ( xNameAccess == null )
645             throw new com.sun.star.uno.RuntimeException();
646 
647         return xNameAccess;
648     }
649 
650     protected static void SetConfigurationProxy( HostConfiguration aHostConfig, XComponentContext xContext )
651     {
652         if ( aHostConfig == null || xContext == null )
653             return;
654 
655         try
656         {
657             XNameAccess xNameAccess = GetConfigNameAccess( xContext, "org.openoffice.Inet/Settings" );
658 
659             int nProxyType = AnyConverter.toInt( xNameAccess.getByName( "ooInetProxyType" ) );
660             if ( nProxyType == 0 )
661                 aHostConfig.setProxyHost( null );
662             else
663             {
664                 if ( nProxyType == 1 )
665                 {
666                     // system proxy
667                 }
668                 else if ( nProxyType == 2 )
669                 {
670                     String aProxyNameProp = "ooInetHTTPProxyName";
671                     String aProxyPortProp = "ooInetHTTPProxyPort";
672 
673                     if ( aHostConfig.getProtocol().getScheme().equals( "https" ) )
674                     {
675                         aProxyNameProp = "ooInetHTTPSProxyName";
676                         aProxyPortProp = "ooInetHTTPSProxyPort";
677                     }
678 
679                     String aNoProxyList = AnyConverter.toString( xNameAccess.getByName( "ooInetNoProxy" ) );
680                     String aProxyName = AnyConverter.toString( xNameAccess.getByName( aProxyNameProp ) );
681 
682                     int nProxyPort = 80;
683 
684                     Object aPortNo = xNameAccess.getByName( aProxyPortProp );
685                     if ( !AnyConverter.isVoid( aPortNo ) )
686                         nProxyPort = AnyConverter.toInt( aPortNo );
687 
688                     if ( nProxyPort == -1 )
689                         nProxyPort = 80;
690 
691                     // TODO: check whether the URL is in the NoProxy list
692                     aHostConfig.setProxy( aProxyName, nProxyPort );
693                 }
694             }
695         }
696         catch( java.lang.Exception e )
697         {
698             e.printStackTrace();
699         }
700     }
701 
702     protected static void ShowURLInBrowser( XComponentContext xContext, String sURL )
703     {
704         if ( xContext != null && sURL != null && sURL.length() > 0 )
705         {
706             try
707             {
708                 Object oSystemShell = xContext.getServiceManager().createInstanceWithContext( "com.sun.star.system.SystemShellExecute", xContext );
709                 XSystemShellExecute xSystemShell = (XSystemShellExecute)UnoRuntime.queryInterface( XSystemShellExecute.class, oSystemShell );
710                 if ( xSystemShell != null )
711                     xSystemShell.execute( sURL, "", SystemShellExecuteFlags.DEFAULTS );
712             }
713             catch( Exception e )
714             {
715                 e.printStackTrace();
716             }
717         }
718     }
719 
720     protected static void ExecuteMethod( HttpMethodBase aMethod, HostConfiguration aHostConfig, URI aURI, XComponentContext xContext, boolean bSetHost )
721         throws WikiCancelException, IOException, SSLException
722     {
723         if ( aMethod != null && aHostConfig != null && aURI != null && xContext != null )
724         {
725             if ( bSetHost )
726             {
727                 aHostConfig.setHost( aURI );
728                 SetConfigurationProxy( aHostConfig, xContext );
729             }
730 
731             boolean bNoUnknownCertNotification = false;
732             if ( aHostConfig.getProtocol().getScheme().equals( "https" )
733               && AllowUnknownCert( xContext, aURI.getHost() ) )
734             {
735                 // let unknown certificates be accepted
736                 {
737                     {
738                         aHostConfig.setHost( aHostConfig.getHost(), ( aURI.getPort() < 0 ? 443 : aURI.getPort() ), Helper.GetOwnHttps( aURI.getPort() ) );
739                         Helper.GetHttpClient().executeMethod( aHostConfig, aMethod );
740                     }
741                 }
742             }
743             else
744             {
745                 Helper.GetHttpClient().executeMethod( aHostConfig, aMethod );
746             }
747         }
748     }
749 
750     static private class HTMLParse extends HTMLEditorKit
751     {
752 
753         public HTMLEditorKit.Parser getParser()
754         {
755             return super.getParser();
756         }
757     }
758 
759     static protected HTMLEditorKit.Parser GetHTMLParser()
760     {
761         return new HTMLParse().getParser();
762     }
763 
764     static protected boolean LoginReportsError( String sRespond )
765     {
766         boolean bResult = true;
767         if ( sRespond != null )
768         {
769             try
770             {
771                 StringReader aReader = new StringReader( sRespond );
772                 HTMLEditorKit.Parser aParser = GetHTMLParser();
773                 EditPageParser aCallback = new EditPageParser();
774 
775                 aParser.parse( aReader, aCallback, true );
776                 bResult = ( aCallback.m_nErrorInd >= 0 );
777             }
778             catch( Exception e )
779             {
780                 e.printStackTrace();
781             }
782         }
783 
784         return bResult;
785     }
786 
787     static protected String GetLoginToken( String sLoginPage )
788     {
789         String sResult = "";
790         if ( sLoginPage != null && sLoginPage.length() > 0 )
791         {
792             try
793             {
794                 StringReader aReader = new StringReader( sLoginPage );
795                 HTMLEditorKit.Parser aParser = Helper.GetHTMLParser();
796                 EditPageParser aCallbacks = new EditPageParser();
797 
798                 aParser.parse( aReader, aCallbacks, true );
799                 sResult = aCallbacks.m_sLoginToken;
800             }
801             catch( Exception e )
802             {
803                 e.printStackTrace();
804             }
805         }
806 
807         return sResult;
808     }
809 
810     static protected HostConfiguration Login( URI aMainURL, String sWikiUser, String sWikiPass, XComponentContext xContext )
811         throws com.sun.star.uno.Exception, java.io.IOException, WikiCancelException
812     {
813         HostConfiguration aHostConfig = null;
814 
815         if ( sWikiUser != null && sWikiPass != null && xContext != null )
816         {
817             HostConfiguration aNewHostConfig = new HostConfiguration();
818 
819             URI aURI = new URI( aMainURL.toString() + "index.php?title=Special:Userlogin" );
820             GetMethod aGetCookie = new GetMethod( aURI.getEscapedPathQuery() );
821 
822             ExecuteMethod( aGetCookie, aNewHostConfig, aURI, xContext, true );
823 
824             int nResultCode = aGetCookie.getStatusCode();
825             String sLoginPage = null;
826             if ( nResultCode == 200 )
827                 sLoginPage = aGetCookie.getResponseBodyAsString();
828 
829             aGetCookie.releaseConnection();
830 
831             if ( sLoginPage != null )
832             {
833                 String sLoginToken = GetLoginToken( sLoginPage );
834 
835                 PostMethod aPost = new PostMethod();
836                 URI aPostURI = new URI( aMainURL.getPath() + "index.php?title=Special:Userlogin&action=submitlogin" );
837                 aPost.setPath( aPostURI.getEscapedPathQuery() );
838 
839                 aPost.addParameter( "wpName", sWikiUser );
840                 aPost.addParameter( "wpRemember", "1" );
841                 aPost.addParameter( "wpPassword", sWikiPass );
842                 if ( sLoginToken.length() > 0 )
843                     aPost.addParameter( "wpLoginToken", sLoginToken );
844 
845                 String[][] pArgs = GetSpecialArgs( xContext, aMainURL.getHost() );
846                 if ( pArgs != null )
847                     for ( int nArgInd = 0; nArgInd < pArgs.length; nArgInd++ )
848                         if ( pArgs[nArgInd].length == 2 && pArgs[nArgInd][0] != null && pArgs[nArgInd][1] != null )
849                             aPost.addParameter( pArgs[nArgInd][0], pArgs[nArgInd][1] );
850 
851                 ExecuteMethod( aPost, aNewHostConfig, aPostURI, xContext, false );
852 
853                 nResultCode = aPost.getStatusCode();
854 
855                 while( nResultCode >= 301 && nResultCode <= 303 || nResultCode == 307 )
856                 {
857                     String sRedirectURL = aPost.getResponseHeader( "Location" ).getValue();
858                     aPost.releaseConnection();
859 
860                     aURI = new URI( sRedirectURL );
861                     aPost = new PostMethod();
862                     aPost.setPath( aURI.getEscapedPathQuery() );
863                     ExecuteMethod( aPost, aNewHostConfig, aURI, xContext, false );
864 
865                     nResultCode = aPost.getStatusCode();
866                 }
867 
868                 if ( nResultCode == 200 )
869                 {
870                     String sResult = aPost.getResponseBodyAsString();
871                     if ( !LoginReportsError( sResult ) )
872                         aHostConfig = aNewHostConfig;
873                 }
874 
875                 aPost.releaseConnection();
876             }
877         }
878 
879         return aHostConfig;
880     }
881 
882     private static XControl GetControlFromDialog( XDialog xDialog, String aControlName )
883     {
884         XControl xResult = null;
885         XControlContainer xControlCont = (XControlContainer) UnoRuntime.queryInterface( XControlContainer.class, xDialog );
886 
887         if ( xControlCont != null )
888         {
889             Object oControl = xControlCont.getControl( aControlName );
890             xResult = ( XControl ) UnoRuntime.queryInterface( XControl.class, oControl );
891         }
892 
893         return xResult;
894     }
895 
896     private static XPropertySet GetSubControlPropSet( XDialog xDialog, String aControlName )
897     {
898         XControl xControl = GetControlFromDialog( xDialog, aControlName );
899         if ( xControl != null )
900             return ( XPropertySet ) UnoRuntime.queryInterface( XPropertySet.class, xControl.getModel() );
901 
902         return null;
903     }
904 
905     protected static void SetControlPropInDialog( XDialog xDialog, String aControlName, String aPropName, Object aPropValue )
906     {
907         if ( xDialog != null && aControlName != null && aPropName != null && aPropValue != null )
908         {
909             try
910             {
911                 XPropertySet xPropSet = GetSubControlPropSet( xDialog, aControlName );
912                 if ( xPropSet != null )
913                     xPropSet.setPropertyValue( aPropName, aPropValue );
914             }
915             catch ( com.sun.star.uno.Exception e )
916             {
917                 e.printStackTrace();
918             }
919         }
920     }
921 
922     protected static String[] GetPasswordsForURLAndUser( XComponentContext xContext, String sURL, String sUserName )
923     {
924         String[] aResult = null;
925 
926         try
927         {
928             if ( xContext != null && sURL != null && sURL.length() > 0 && sUserName != null && sUserName.length() > 0 )
929             {
930                 UrlRecord aRec = GetPasswordContainer( xContext ).findForName( sURL, sUserName, GetInteractionHandler( xContext ) );
931                 if ( aRec != null && aRec.UserList != null && aRec.UserList.length > 0
932                   && aRec.UserList[0].UserName.equals( sUserName ) )
933                     aResult = aRec.UserList[0].Passwords;
934             }
935         }
936         catch( Exception e )
937         {
938             e.printStackTrace();
939         }
940 
941         return aResult;
942     }
943 
944     protected static boolean PasswordStoringIsAllowed( XComponentContext xContext )
945     {
946         boolean bResult = false;
947         try
948         {
949             XMasterPasswordHandling xMasterHdl = (XMasterPasswordHandling)UnoRuntime.queryInterface( XMasterPasswordHandling.class, GetPasswordContainer( xContext ) );
950             if ( xMasterHdl != null )
951                 bResult = xMasterHdl.isPersistentStoringAllowed();
952         }
953         catch( Exception e )
954         {
955             e.printStackTrace();
956         }
957 
958         return bResult;
959     }
960 
961     protected static void ShowError( XComponentContext xContext, XDialog xDialog, int nTitleID, int nErrorID, String sArg, boolean bQuery )
962     {
963         XWindowPeer xPeer = null;
964         XControl xControl = (XControl)UnoRuntime.queryInterface( XControl.class, xDialog );
965         if ( xControl != null )
966             xPeer = xControl.getPeer();
967         ShowError( xContext, xPeer, nTitleID, nErrorID, sArg, bQuery );
968     }
969 
970     protected static boolean ShowError( XComponentContext xContext, XWindowPeer xParentPeer, int nTitleID, int nErrorID, String sArg, boolean bQuery )
971     {
972         boolean bResult = false;
973 
974         if ( xContext != null && nErrorID >= 0 && nErrorID < STRINGS_NUM )
975         {
976             boolean bShown = false;
977 
978             String sError = null;
979             String sTitle = "";
980 
981             try
982             {
983                 sError = GetLocalizedString( xContext, nErrorID );
984                 if ( sError != null && sArg != null )
985                     sError = sError.replaceAll( "\\$ARG1", sArg );
986 
987                 sTitle = GetLocalizedString( xContext, nTitleID );
988             }
989             catch( Exception e )
990             {
991                 e.printStackTrace();
992             }
993 
994             if ( sError == null )
995                 sError = "Error: " + nErrorID;
996 
997             if ( xParentPeer != null )
998             {
999                 XMessageBoxFactory xMBFactory = null;
1000                 XMessageBox xMB = null;
1001                 try
1002                 {
1003                     XMultiComponentFactory xFactory = xContext.getServiceManager();
1004                     if ( xFactory != null )
1005                         xMBFactory = (XMessageBoxFactory)UnoRuntime.queryInterface(
1006                                      XMessageBoxFactory.class,
1007                                      xFactory.createInstanceWithContext( "com.sun.star.awt.Toolkit", xContext ) );
1008 
1009                     if ( xMBFactory != null )
1010                     {
1011                         if ( bQuery )
1012                         {
1013                             xMB = xMBFactory.createMessageBox(
1014                                                      xParentPeer,
1015                                                      new com.sun.star.awt.Rectangle(),
1016                                                      "querybox",
1017                                                      MessageBoxButtons.BUTTONS_YES_NO | MessageBoxButtons.DEFAULT_BUTTON_NO,
1018                                                      sTitle,
1019                                                      sError );
1020                         }
1021                         else
1022                         {
1023                             xMB = xMBFactory.createMessageBox(
1024                                                      xParentPeer,
1025                                                      new com.sun.star.awt.Rectangle(),
1026                                                      "errorbox",
1027                                                      MessageBoxButtons.BUTTONS_OK,
1028                                                      sTitle,
1029                                                      sError );
1030                         }
1031                         if ( xMB != null )
1032                         {
1033                             bResult = MainThreadDialogExecutor.Execute( xContext, xMB );
1034                             bShown = true;
1035                         }
1036                     }
1037                 }
1038                 catch( Exception e )
1039                 {
1040                     e.printStackTrace();
1041                 }
1042                 finally
1043                 {
1044                     if ( xMB != null )
1045                         Dispose( xMB );
1046                 }
1047             }
1048         }
1049 
1050         return bResult;
1051     }
1052 
1053     private static boolean AllowUnknownCert( XComponentContext xContext, String aURL )
1054     {
1055         try
1056         {
1057             XNameAccess xNameAccess = GetConfigNameAccess( xContext, "org.openoffice.Office.Custom.WikiExtension/SpecialData" );
1058             if ( xNameAccess.hasByName( aURL ) )
1059             {
1060                 XNameAccess xEntry = (XNameAccess)UnoRuntime.queryInterface( XNameAccess.class, xNameAccess.getByName( aURL ) );
1061                 if ( xEntry != null && xEntry.hasByName( "AllowUnknownCertificate" ) )
1062                     return AnyConverter.toBoolean( xEntry.getByName( "AllowUnknownCertificate" ) );
1063             }
1064         }
1065         catch( Exception e )
1066         {
1067             e.printStackTrace();
1068         }
1069 
1070         return false;
1071     }
1072 
1073     private static String[][] GetSpecialArgs( XComponentContext xContext, String aURL )
1074     {
1075         try
1076         {
1077             XNameAccess xNameAccess = GetConfigNameAccess( xContext, "org.openoffice.Office.Custom.WikiExtension/SpecialData" );
1078             if ( xNameAccess.hasByName( aURL ) )
1079             {
1080                 XNameAccess xEntry = (XNameAccess)UnoRuntime.queryInterface( XNameAccess.class, xNameAccess.getByName( aURL ) );
1081                 if ( xEntry != null )
1082                 {
1083                     XNameAccess xArgs = (XNameAccess)UnoRuntime.queryInterface( XNameAccess.class, xEntry.getByName( "AdditionalLoginArguments" ) );
1084                     if ( xArgs != null )
1085                     {
1086                         String[] pNames = xArgs.getElementNames();
1087                         if ( pNames != null && pNames.length > 0 )
1088                         {
1089                             String[][] pResult = new String[pNames.length][2];
1090                             for ( int nInd = 0; nInd < pNames.length; nInd++ )
1091                             {
1092                                 XNameAccess xArgument = (XNameAccess)UnoRuntime.queryInterface( XNameAccess.class, xArgs.getByName( pNames[nInd] ) );
1093                                 if ( xArgument == null )
1094                                     throw new com.sun.star.uno.RuntimeException();
1095 
1096                                 pResult[nInd][0] = pNames[nInd];
1097                                 pResult[nInd][1] = AnyConverter.toString( xArgument.getByName( "Value" ) );
1098                             }
1099 
1100                             return pResult;
1101                         }
1102                     }
1103                 }
1104             }
1105         }
1106         catch( Exception e )
1107         {
1108             e.printStackTrace();
1109         }
1110 
1111         return null;
1112     }
1113 
1114     protected static boolean AllowThreadUsage( XComponentContext xContext )
1115     {
1116         if ( xContext != null )
1117         {
1118             try
1119             {
1120                 XMultiComponentFactory xFactory = xContext.getServiceManager();
1121                 if ( xFactory == null )
1122                     throw new com.sun.star.uno.RuntimeException();
1123 
1124                 Object oCheckCallback = xFactory.createInstanceWithContext( "com.sun.star.awt.AsyncCallback", xContext );
1125                 return ( oCheckCallback != null );
1126             }
1127             catch( Exception e )
1128             {
1129                 e.printStackTrace();
1130             }
1131         }
1132 
1133         return false;
1134     }
1135 
1136     public static void Dispose( Object oObject )
1137     {
1138         if ( oObject != null )
1139         {
1140             try
1141             {
1142                 XComponent xComp = (XComponent)UnoRuntime.queryInterface( XComponent.class, oObject );
1143                 if ( xComp != null )
1144                     xComp.dispose();
1145             }
1146             catch( Exception e )
1147             {
1148                 e.printStackTrace();
1149             }
1150         }
1151     }
1152 }
1153 
1154