Debian Codegraph @

swext/mediawiki/src/com/sun/star/wiki/Helper.java

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