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