-
-
Notifications
You must be signed in to change notification settings - Fork 542
/
XWiki.java
6590 lines (5754 loc) · 259 KB
/
XWiki.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* See the NOTICE file distributed with this work for additional
* information regarding copyright ownership.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package com.xpn.xwiki;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Type;
import java.net.InetAddress;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URL;
import java.text.DateFormatSymbols;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Collections;
import java.util.Date;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.ListIterator;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
import java.util.TimeZone;
import java.util.Vector;
import java.util.regex.Pattern;
import java.util.zip.ZipOutputStream;
import javax.naming.NamingException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.httpclient.Credentials;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.URIException;
import org.apache.commons.httpclient.UsernamePasswordCredentials;
import org.apache.commons.httpclient.auth.AuthScope;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.util.URIUtil;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.LocaleUtils;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.math.NumberUtils;
import org.apache.commons.lang3.reflect.FieldUtils;
import org.apache.commons.net.smtp.SMTPClient;
import org.apache.commons.net.smtp.SMTPReply;
import org.apache.velocity.VelocityContext;
import org.hibernate.HibernateException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.xwiki.bridge.event.DocumentCreatedEvent;
import org.xwiki.bridge.event.DocumentCreatingEvent;
import org.xwiki.bridge.event.DocumentDeletedEvent;
import org.xwiki.bridge.event.DocumentDeletingEvent;
import org.xwiki.bridge.event.DocumentRolledBackEvent;
import org.xwiki.bridge.event.DocumentRollingBackEvent;
import org.xwiki.bridge.event.DocumentUpdatedEvent;
import org.xwiki.bridge.event.DocumentUpdatingEvent;
import org.xwiki.bridge.event.WikiCopiedEvent;
import org.xwiki.bridge.event.WikiDeletedEvent;
import org.xwiki.bridge.event.WikiReadyEvent;
import org.xwiki.cache.Cache;
import org.xwiki.classloader.ClassLoaderManager;
import org.xwiki.component.descriptor.ComponentInstantiationStrategy;
import org.xwiki.component.descriptor.DefaultComponentDescriptor;
import org.xwiki.component.manager.ComponentLookupException;
import org.xwiki.component.manager.ComponentRepositoryException;
import org.xwiki.component.phase.Initializable;
import org.xwiki.component.phase.InitializationException;
import org.xwiki.configuration.ConfigurationSource;
import org.xwiki.context.Execution;
import org.xwiki.job.Job;
import org.xwiki.job.event.status.JobProgressManager;
import org.xwiki.localization.ContextualLocalizationManager;
import org.xwiki.model.EntityType;
import org.xwiki.model.reference.DocumentReference;
import org.xwiki.model.reference.DocumentReferenceResolver;
import org.xwiki.model.reference.EntityReference;
import org.xwiki.model.reference.EntityReferenceResolver;
import org.xwiki.model.reference.EntityReferenceSerializer;
import org.xwiki.model.reference.EntityReferenceValueProvider;
import org.xwiki.model.reference.LocalDocumentReference;
import org.xwiki.model.reference.ObjectReference;
import org.xwiki.model.reference.RegexEntityReference;
import org.xwiki.model.reference.SpaceReference;
import org.xwiki.model.reference.WikiReference;
import org.xwiki.observation.EventListener;
import org.xwiki.observation.ObservationManager;
import org.xwiki.observation.event.Event;
import org.xwiki.query.QueryException;
import org.xwiki.query.QueryFilter;
import org.xwiki.rendering.parser.ParseException;
import org.xwiki.rendering.syntax.Syntax;
import org.xwiki.rendering.syntax.SyntaxFactory;
import org.xwiki.resource.ResourceReference;
import org.xwiki.resource.ResourceReferenceManager;
import org.xwiki.resource.ResourceReferenceResolver;
import org.xwiki.resource.entity.EntityResourceReference;
import org.xwiki.stability.Unstable;
import org.xwiki.wiki.descriptor.WikiDescriptor;
import org.xwiki.wiki.descriptor.WikiDescriptorManager;
import org.xwiki.wiki.manager.WikiManager;
import org.xwiki.wiki.manager.WikiManagerException;
import org.xwiki.xml.XMLUtils;
import com.xpn.xwiki.api.Api;
import com.xpn.xwiki.api.Document;
import com.xpn.xwiki.api.User;
import com.xpn.xwiki.criteria.api.XWikiCriteriaService;
import com.xpn.xwiki.doc.DeletedAttachment;
import com.xpn.xwiki.doc.MandatoryDocumentInitializer;
import com.xpn.xwiki.doc.XWikiAttachment;
import com.xpn.xwiki.doc.XWikiDeletedDocument;
import com.xpn.xwiki.doc.XWikiDocument;
import com.xpn.xwiki.doc.XWikiDocument.XWikiAttachmentToRemove;
import com.xpn.xwiki.doc.XWikiDocumentArchive;
import com.xpn.xwiki.internal.XWikiCfgConfigurationSource;
import com.xpn.xwiki.internal.XWikiConfigDelegate;
import com.xpn.xwiki.internal.XWikiInitializerJob;
import com.xpn.xwiki.internal.event.XObjectAddedEvent;
import com.xpn.xwiki.internal.event.XObjectDeletedEvent;
import com.xpn.xwiki.internal.event.XObjectEvent;
import com.xpn.xwiki.internal.event.XObjectPropertyAddedEvent;
import com.xpn.xwiki.internal.event.XObjectPropertyDeletedEvent;
import com.xpn.xwiki.internal.event.XObjectPropertyEvent;
import com.xpn.xwiki.internal.event.XObjectPropertyUpdatedEvent;
import com.xpn.xwiki.internal.event.XObjectUpdatedEvent;
import com.xpn.xwiki.internal.template.PrivilegedTemplateRenderer;
import com.xpn.xwiki.objects.BaseObject;
import com.xpn.xwiki.objects.PropertyInterface;
import com.xpn.xwiki.objects.classes.BaseClass;
import com.xpn.xwiki.objects.classes.PasswordClass;
import com.xpn.xwiki.objects.classes.PropertyClass;
import com.xpn.xwiki.objects.meta.MetaClass;
import com.xpn.xwiki.plugin.XWikiPluginInterface;
import com.xpn.xwiki.plugin.XWikiPluginManager;
import com.xpn.xwiki.render.XWikiRenderingEngine;
import com.xpn.xwiki.render.XWikiVelocityRenderer;
import com.xpn.xwiki.render.groovy.XWikiGroovyRenderer;
import com.xpn.xwiki.render.groovy.XWikiPageClassLoader;
import com.xpn.xwiki.stats.api.XWikiStatsService;
import com.xpn.xwiki.stats.impl.SearchEngineRule;
import com.xpn.xwiki.stats.impl.XWikiStatsServiceImpl;
import com.xpn.xwiki.store.AttachmentRecycleBinStore;
import com.xpn.xwiki.store.AttachmentVersioningStore;
import com.xpn.xwiki.store.XWikiAttachmentStoreInterface;
import com.xpn.xwiki.store.XWikiCacheStore;
import com.xpn.xwiki.store.XWikiCacheStoreInterface;
import com.xpn.xwiki.store.XWikiHibernateStore;
import com.xpn.xwiki.store.XWikiRecycleBinStoreInterface;
import com.xpn.xwiki.store.XWikiStoreInterface;
import com.xpn.xwiki.store.XWikiVersioningStoreInterface;
import com.xpn.xwiki.user.api.XWikiAuthService;
import com.xpn.xwiki.user.api.XWikiGroupService;
import com.xpn.xwiki.user.api.XWikiRightService;
import com.xpn.xwiki.user.api.XWikiUser;
import com.xpn.xwiki.user.impl.xwiki.XWikiAuthServiceImpl;
import com.xpn.xwiki.user.impl.xwiki.XWikiGroupServiceImpl;
import com.xpn.xwiki.user.impl.xwiki.XWikiRightServiceImpl;
import com.xpn.xwiki.util.Util;
import com.xpn.xwiki.util.XWikiStubContextProvider;
import com.xpn.xwiki.web.Utils;
import com.xpn.xwiki.web.XWikiEngineContext;
import com.xpn.xwiki.web.XWikiMessageTool;
import com.xpn.xwiki.web.XWikiRequest;
import com.xpn.xwiki.web.XWikiURLFactory;
import com.xpn.xwiki.web.XWikiURLFactoryService;
import com.xpn.xwiki.web.XWikiURLFactoryServiceImpl;
import com.xpn.xwiki.web.includeservletasstring.IncludeServletAsString;
public class XWiki implements EventListener
{
/** Name of the default wiki. */
public static final String DEFAULT_MAIN_WIKI = "xwiki";
/** Name of the default home space. */
public static final String DEFAULT_HOME_SPACE = "Main";
/** Name of the default system space. */
public static final String SYSTEM_SPACE = "XWiki";
/** Name of the default space homepage. */
public static final String DEFAULT_SPACE_HOMEPAGE = "WebHome";
/** Logging helper object. */
protected static final Logger LOGGER = LoggerFactory.getLogger(XWiki.class);
/** Frequently used Document reference, the class which holds virtual wiki definitions. */
private static final DocumentReference VIRTUAL_WIKI_DEFINITION_CLASS_REFERENCE = new DocumentReference(
DEFAULT_MAIN_WIKI, SYSTEM_SPACE, "XWikiServerClass");
/** The default encoding, and the internally used encoding when dealing with byte representation of strings. */
public static final String DEFAULT_ENCODING = "UTF-8";
/** The main document storage. */
private XWikiStoreInterface store;
/** The attachment storage (excluding attachment history). */
private XWikiAttachmentStoreInterface attachmentStore;
/** Store for attachment archives. */
private AttachmentVersioningStore attachmentVersioningStore;
/** Document versioning storage. */
private XWikiVersioningStoreInterface versioningStore;
/** Deleted documents storage. */
private XWikiRecycleBinStoreInterface recycleBinStore;
/**
* Storage for deleted attachment.
*
* @since 1.4M1
*/
private AttachmentRecycleBinStore attachmentRecycleBinStore;
private XWikiPluginManager pluginManager;
private XWikiAuthService authService;
private XWikiRightService rightService;
private XWikiGroupService groupService;
private XWikiStatsService statsService;
private XWikiURLFactoryService urlFactoryService;
private XWikiCriteriaService criteriaService;
/** Lock object used for the lazy initialization of the authentication service. */
private final Object AUTH_SERVICE_LOCK = new Object();
/** Lock object used for the lazy initialization of the authorization service. */
private final Object RIGHT_SERVICE_LOCK = new Object();
/** Lock object used for the lazy initialization of the group management service. */
private final Object GROUP_SERVICE_LOCK = new Object();
/** Lock object used for the lazy initialization of the statistics service. */
private final Object STATS_SERVICE_LOCK = new Object();
/** Lock object used for the lazy initialization of the URL Factory service. */
private final Object URLFACTORY_SERVICE_LOCK = new Object();
private MetaClass metaclass = MetaClass.getMetaClass();
private String version = null;
private XWikiEngineContext engine_context;
private String database;
private String fullNameSQL;
/**
* The list of initialized wikis.
*/
private List<String> virtualWikiList = new ArrayList<String>();
/**
* The cache containing the names of the wikis already initialized.
*/
private Cache<DocumentReference> virtualWikiMap;
private boolean isReadOnly = false;
/**
* @deprecated since 6.1M2, use {@link XWikiCfgConfigurationSource#CFG_ENV_NAME} instead
*/
@Deprecated
public static final String CFG_ENV_NAME = XWikiCfgConfigurationSource.CFG_ENV_NAME;
public static final String MACROS_FILE = "/templates/macros.txt";
/**
* File containing XWiki's version, in the format: <version name>.<SVN revision number>.
*/
private static final String VERSION_FILE = "/WEB-INF/version.properties";
/**
* Property containing the version value in the {@link #VERSION_FILE} file.
*/
private static final String VERSION_FILE_PROPERTY = "version";
/**
* List of configured syntax ids.
*/
private List<String> configuredSyntaxes;
/**
* Used to convert a proper Document Reference to string (standard form).
*/
private EntityReferenceSerializer<String> defaultEntityReferenceSerializer = Utils
.getComponent(EntityReferenceSerializer.TYPE_STRING);
private EntityReferenceValueProvider defaultEntityReferenceValueProvider = Utils
.getComponent((Type) EntityReferenceValueProvider.class);
/**
* Used to resolve a string into a proper Document Reference using the current document's reference to fill the
* blanks, except for the page name for which the default page name is used instead.
*/
private DocumentReferenceResolver<String> currentMixedDocumentReferenceResolver = Utils.getComponent(
DocumentReferenceResolver.TYPE_STRING, "currentmixed");
private DocumentReferenceResolver<EntityReference> currentReferenceDocumentReferenceResolver = Utils.getComponent(
DocumentReferenceResolver.TYPE_REFERENCE, "current");
private EntityReferenceResolver<String> currentMixedEntityReferenceResolver = Utils.getComponent(
EntityReferenceResolver.TYPE_STRING, "currentmixed");
private EntityReferenceResolver<String> relativeEntityReferenceResolver = Utils.getComponent(
EntityReferenceResolver.TYPE_STRING, "relative");
private SyntaxFactory syntaxFactory = Utils.getComponent((Type) SyntaxFactory.class);
/** Renderer for elevating privileges for selected file system templates. */
private PrivilegedTemplateRenderer privilegedTemplateRenderer = Utils
.getComponent(PrivilegedTemplateRenderer.class);
private ResourceReferenceManager resourceReferenceManager = Utils
.getComponent((Type) ResourceReferenceManager.class);
/**
* Whether backlinks are enabled or not (cached for performance).
*
* @since 3.2M2
*/
private Boolean hasBacklinks;
private static XWikiInitializerJob job;
private static ConfigurationSource getConfiguration()
{
return Utils.getComponent(ConfigurationSource.class, XWikiCfgConfigurationSource.ROLEHINT);
}
public static XWiki getMainXWiki(XWikiContext context) throws XWikiException
{
return getMainXWiki(true, context);
}
public static XWiki getMainXWiki(boolean wait, XWikiContext context) throws XWikiException
{
String xwikiname = DEFAULT_MAIN_WIKI;
context.setMainXWiki(xwikiname);
XWiki xwiki;
try {
XWikiEngineContext econtext = context.getEngineContext();
xwiki = (XWiki) econtext.getAttribute(xwikiname);
if (xwiki == null) {
// Start XWiki initialization
synchronized (XWiki.class) {
xwiki = (XWiki) econtext.getAttribute(xwikiname);
if (xwiki == null && job == null) {
job = Utils.getComponent((Type) Job.class, XWikiInitializerJob.JOBTYPE);
if (job.getStatus() == null) {
// "Pre-initialize" XWikiStubContextProvider so that XWiki initializer can find one
Utils.<XWikiStubContextProvider> getComponent((Type) XWikiStubContextProvider.class)
.initialize(context);
job.startAsync();
}
}
}
// Wait until XWiki is initialized
if (wait) {
job.join();
xwiki = (XWiki) econtext.getAttribute(xwikiname);
}
}
context.setWiki(xwiki);
return xwiki;
} catch (Exception e) {
throw new XWikiException(XWikiException.MODULE_XWIKI, XWikiException.ERROR_XWIKI_INIT_FAILED,
"Could not initialize main XWiki context", e);
}
}
public static boolean isInitializing(XWikiContext xcontext)
{
return Boolean.TRUE.equals(xcontext.getEngineContext().getAttribute("xwiki.init"));
}
/**
* Return the XWiki object (as in "the Wiki API") corresponding to the requested wiki.
*
* @param context the current context
* @return an XWiki object configured for the wiki corresponding to the current request
* @throws XWikiException if the requested URL does not correspond to a real wiki, or if there's an error in the
* storage
*/
public static XWiki getXWiki(XWikiContext context) throws XWikiException
{
return getXWiki(true, context);
}
/**
* Return the XWiki object (as in "the Wiki API") corresponding to the requested wiki.
* <p>
* Unless <code>wait</code> is false the method return right away null if XWiki is not yet initialized.
*
* @param wait wait until XWiki is initialized
* @param context the current context
* @return an XWiki object configured for the wiki corresponding to the current request
* @throws XWikiException if the requested URL does not correspond to a real wiki, or if there's an error in the
* storage
*/
public static XWiki getXWiki(boolean wait, XWikiContext context) throws XWikiException
{
XWiki xwiki = getMainXWiki(wait, context);
if (xwiki == null) {
return null;
}
// Extract Entity Resource from URL and put it in the Execution Context
EntityResourceReference entityResourceReference = initializeResourceFromURL(context);
// Get the wiki id
String wikiId = entityResourceReference.getEntityReference().extractReference(EntityType.WIKI).getName();
if (wikiId.equals(context.getMainXWiki())) {
// The main wiki was requested.
return xwiki;
}
// Check if the wiki exists by checking if a descriptor exists for the wiki id.
WikiDescriptorManager wikiDescriptorManager = Utils.getComponent(WikiDescriptorManager.class);
WikiDescriptor descriptor;
try {
descriptor = wikiDescriptorManager.getById(wikiId);
} catch (WikiManagerException e) {
throw new XWikiException(XWikiException.MODULE_XWIKI, XWikiException.ERROR_XWIKI_STORE_MISC, String.format(
"Failed find wiki descriptor for wiki id [%s]", wikiId), e);
}
if (descriptor == null) {
throw new XWikiException(XWikiException.MODULE_XWIKI, XWikiException.ERROR_XWIKI_DOES_NOT_EXIST,
String.format("The wiki [%s] does not exist", wikiId));
}
context.setWikiId(wikiId);
context.setOriginalWikiId(wikiId);
try {
// Let's make sure the virtual wikis are upgraded to the latest database version
xwiki.updateDatabase(wikiId, false, context);
} catch (HibernateException e) {
// Just report it, hopefully the database is in a good enough state
LOGGER.error("Failed to upgrade database [{}]", wikiId, e);
}
return xwiki;
}
private static EntityResourceReference initializeResourceFromURL(XWikiContext context) throws XWikiException
{
// Extract the Entity Resource from the URL
// TODO: This code should be put in an ExecutionContextInitializer but we couldn't do yet since this code
// requires that the XWiki object be initialized first (the line above). Thus we'll be able to to move it only
// after the XWiki init is done also in an ExecutionContextInitializer (and with priorities).
ResourceReferenceResolver<URL> urlResolver = Utils.getComponent(ResourceReferenceResolver.TYPE_URL);
URL url = context.getURL();
EntityResourceReference entityResourceReference;
try {
entityResourceReference =
(EntityResourceReference) urlResolver.resolve(url,
Collections.<String, Object> singletonMap("ignorePrefix", context.getRequest().getContextPath()));
} catch (Exception e) {
throw new XWikiException(XWikiException.MODULE_XWIKI, XWikiException.ERROR_XWIKI_APP_URL_EXCEPTION,
String.format("Failed to extract Entity Resource Reference from URL [%s]", url), e);
}
Utils.getComponent(Execution.class).getContext()
.setProperty(ResourceReferenceManager.RESOURCE_CONTEXT_PROPERTY, entityResourceReference);
return entityResourceReference;
}
public static URL getRequestURL(XWikiRequest request) throws XWikiException
{
try {
StringBuffer requestURL = request.getRequestURL();
String qs = request.getQueryString();
if ((qs != null) && (!qs.equals(""))) {
return new URL(requestURL.toString() + "?" + qs);
} else {
return new URL(requestURL.toString());
}
} catch (Exception e) {
throw new XWikiException(XWikiException.MODULE_XWIKI_APP, XWikiException.ERROR_XWIKI_APP_URL_EXCEPTION,
"Exception while getting URL from request", e);
}
}
public static Object callPrivateMethod(Object obj, String methodName)
{
return callPrivateMethod(obj, methodName, null, null);
}
public static Object callPrivateMethod(Object obj, String methodName, Class< ? >[] classes, Object[] args)
{
try {
Method method = obj.getClass().getDeclaredMethod(methodName, classes);
method.setAccessible(true);
return method.invoke(obj, args);
} catch (IllegalAccessException e) {
e.printStackTrace();
return null;
} catch (NoSuchMethodException e) {
return null;
} catch (InvocationTargetException e) {
e.printStackTrace();
return null;
}
}
public static HttpClient getHttpClient(int timeout, String userAgent)
{
HttpClient client = new HttpClient();
if (timeout != 0) {
client.getParams().setSoTimeout(timeout);
client.getParams().setParameter("http.connection.timeout", Integer.valueOf(timeout));
}
client.getParams().setParameter("http.useragent", userAgent);
String proxyHost = System.getProperty("http.proxyHost");
String proxyPort = System.getProperty("http.proxyPort");
if ((proxyHost != null) && (!proxyHost.equals(""))) {
int port = 3128;
if ((proxyPort != null) && (!proxyPort.equals(""))) {
port = Integer.parseInt(proxyPort);
}
client.getHostConfiguration().setProxy(proxyHost, port);
}
String proxyUser = System.getProperty("http.proxyUser");
if ((proxyUser != null) && (!proxyUser.equals(""))) {
String proxyPassword = System.getProperty("http.proxyPassword");
Credentials defaultcreds = new UsernamePasswordCredentials(proxyUser, proxyPassword);
client.getState().setProxyCredentials(AuthScope.ANY, defaultcreds);
}
return client;
}
/**
* @deprecated use {@link FieldUtils#readDeclaredField(Object, String, boolean)} instead
*/
@Deprecated
public static Object getPrivateField(Object obj, String fieldName)
{
try {
Field field = obj.getClass().getDeclaredField(fieldName);
field.setAccessible(true);
return field.get(obj);
} catch (NoSuchFieldException e) {
return null;
} catch (IllegalAccessException e) {
e.printStackTrace();
return null;
} finally {
}
}
public static String getServerWikiPage(String servername)
{
return "XWiki.XWikiServer" + StringUtils.capitalize(servername);
}
public static String getTextArea(String content, XWikiContext context)
{
StringBuilder result = new StringBuilder();
// Forcing a new line after the <textarea> tag, as
// http://www.w3.org/TR/html4/appendix/notes.html#h-B.3.1 causes an empty line at the start
// of the document content to be trimmed.
result.append("<textarea name=\"content\" id=\"content\" rows=\"25\" cols=\"80\">\n");
result.append(XMLUtils.escape(content));
result.append("</textarea>");
return result.toString();
}
/**
* This provide a way to create an XWiki object without initializing the whole XWiki (including plugins, storage,
* etc.).
* <p>
* Needed for tools or tests which need XWiki because it is used everywhere in the API.
* </p>
*/
public XWiki()
{
}
public XWiki(XWikiContext context, XWikiEngineContext engine_context, boolean noupdate) throws XWikiException
{
initXWiki(context, engine_context, noupdate);
}
public XWiki(XWikiContext context) throws XWikiException
{
this(context, null, false);
}
public void initXWiki(XWikiContext context, XWikiEngineContext engine_context, boolean noupdate)
throws XWikiException
{
initXWiki(null, context, engine_context, noupdate);
}
/**
* Initialize all xwiki subsystems.
*
* @deprecated since 6.1M2, use {@link #initXWiki(XWikiContext, XWikiEngineContext, boolean)} instead
*/
@Deprecated
public void initXWiki(XWikiConfig config, XWikiContext context, XWikiEngineContext engine_context, boolean noupdate)
throws XWikiException
{
JobProgressManager progress = Utils.getComponent(JobProgressManager.class);
progress.pushLevelProgress(4, this);
try {
setDatabase(context.getMainXWiki());
setEngineContext(engine_context);
context.setWiki(this);
// Prepare the store
if (config != null) {
setConfig(config);
}
XWikiStoreInterface mainStore =
Utils.getComponent(XWikiStoreInterface.class,
getConfiguration().getProperty("xwiki.store.main.hint", "hibernate"));
// Check if we need to use the cache store..
boolean nocache = "0".equals(getConfiguration().getProperty("xwiki.store.cache", "1"));
if (!nocache) {
XWikiCacheStoreInterface cachestore = new XWikiCacheStore(mainStore, context);
setStore(cachestore);
} else {
setStore(mainStore);
}
setCriteriaService((XWikiCriteriaService) createClassFromConfig("xwiki.criteria.class",
"com.xpn.xwiki.criteria.impl.XWikiCriteriaServiceImpl", context));
setAttachmentStore(Utils.<XWikiAttachmentStoreInterface> getComponent(
(Type) XWikiAttachmentStoreInterface.class,
getConfiguration().getProperty("xwiki.store.attachment.hint", "hibernate")));
setVersioningStore(Utils.<XWikiVersioningStoreInterface> getComponent(
(Type) XWikiVersioningStoreInterface.class,
getConfiguration().getProperty("xwiki.store.versioning.hint", "hibernate")));
setAttachmentVersioningStore(Utils.<AttachmentVersioningStore> getComponent(
(Type) AttachmentVersioningStore.class, hasAttachmentVersioning(context) ? getConfiguration()
.getProperty("xwiki.store.attachment.versioning.hint", "hibernate") : "void"));
if (hasRecycleBin(context)) {
setRecycleBinStore(Utils.<XWikiRecycleBinStoreInterface> getComponent(
(Type) XWikiRecycleBinStoreInterface.class,
getConfiguration().getProperty("xwiki.store.recyclebin.hint", "hibernate")));
}
if (hasAttachmentRecycleBin(context)) {
setAttachmentRecycleBinStore(Utils.<AttachmentRecycleBinStore> getComponent(
(Type) AttachmentRecycleBinStore.class,
getConfiguration().getProperty("xwiki.store.attachment.recyclebin.hint", "hibernate")));
}
// "Pre-initialize" XWikiStubContextProvider so that rendering engine, plugins or listeners reacting to
// potential document changes can use it
Utils.<XWikiStubContextProvider> getComponent((Type) XWikiStubContextProvider.class).initialize(context);
progress.stepPropress(this);
// Make sure these classes exists
if (noupdate) {
initializeMandatoryClasses(context);
getStatsService(context);
}
progress.stepPropress(this);
// Prepare the Plugin Engine
preparePlugins(context);
progress.stepPropress(this);
String ro = getConfiguration().getProperty("xwiki.readonly", "no");
this.isReadOnly = ("yes".equalsIgnoreCase(ro) || "true".equalsIgnoreCase(ro) || "1".equalsIgnoreCase(ro));
// Save the configured syntaxes
String syntaxes = getConfiguration().getProperty("xwiki.rendering.syntaxes", "xwiki/1.0");
this.configuredSyntaxes = Arrays.asList(StringUtils.split(syntaxes, " ,"));
ObservationManager observationManager = Utils.getComponent((Type) ObservationManager.class);
observationManager.addListener(this);
} finally {
progress.popLevelProgress(this);
}
}
/**
* Ensure that mandatory classes (ie classes XWiki needs to work properly) exist and create them if they don't
* exist.
*/
private void initializeMandatoryClasses(XWikiContext context) throws XWikiException
{
if (context.get("initdone") == null) {
List<MandatoryDocumentInitializer> initializers =
Utils.getComponentList(MandatoryDocumentInitializer.class);
for (MandatoryDocumentInitializer initializer : initializers) {
DocumentReference documentReference =
this.currentReferenceDocumentReferenceResolver.resolve(initializer.getDocumentReference());
if (documentReference.getWikiReference().getName().equals(context.getWikiId())) {
XWikiDocument document = context.getWiki().getDocument(documentReference, context);
if (initializer.updateDocument(document)) {
saveDocument(document, context);
}
}
}
}
}
public XWikiStoreInterface getNotCacheStore()
{
XWikiStoreInterface store = getStore();
if (store instanceof XWikiCacheStoreInterface) {
store = ((XWikiCacheStoreInterface) store).getStore();
}
return store;
}
public XWikiHibernateStore getHibernateStore()
{
XWikiStoreInterface store = getStore();
if (store instanceof XWikiHibernateStore) {
return (XWikiHibernateStore) store;
} else if (store instanceof XWikiCacheStoreInterface) {
store = ((XWikiCacheStoreInterface) store).getStore();
if (store instanceof XWikiHibernateStore) {
return (XWikiHibernateStore) store;
} else {
return null;
}
} else {
return null;
}
}
public void updateDatabase(String wikiName, XWikiContext context) throws HibernateException, XWikiException
{
updateDatabase(wikiName, false, context);
}
public void updateDatabase(String wikiName, boolean force, XWikiContext context) throws HibernateException,
XWikiException
{
updateDatabase(wikiName, force, true, context);
}
public void updateDatabase(String wikiName, boolean force, boolean initClasses, XWikiContext context)
throws HibernateException, XWikiException
{
String database = context.getWikiId();
try {
List<String> wikiList = getVirtualWikiList();
// Make sure the wiki is updated
if (force) {
wikiList.remove(wikiName);
context.remove("initdone");
}
context.setWikiId(wikiName);
synchronized (wikiName) {
if (!wikiList.contains(wikiName)) {
wikiList.add(wikiName);
// Make sure these classes exists
if (initClasses) {
initializeMandatoryClasses(context);
getPluginManager().virtualInit(context);
getRenderingEngine().virtualInit(context);
}
// Add initdone which will allow to
// bypass some initializations
context.put("initdone", "1");
// Send event to notify listeners that the subwiki is ready
ObservationManager observationManager = Utils.getComponent((Type) ObservationManager.class);
observationManager.notify(new WikiReadyEvent(wikiName), wikiName, context);
}
}
} finally {
context.setWikiId(database);
}
}
/**
* @return a cached list of all active virtual wikis (i.e. wikis who have been hit by a user request). To get a full
* list of all virtual wikis database names use {@link #getVirtualWikisDatabaseNames(XWikiContext)}.
* @deprecated since 5.3, use {@link WikiDescriptorManager#getAll()} instead
*/
@Deprecated
public List<String> getVirtualWikiList()
{
return this.virtualWikiList;
}
/**
* @return the full list of all wiki names of all defined wikis. The wiki names are computed from the names of
* documents having a XWiki.XWikiServerClass object attached to them by removing the "XWiki.XWikiServer"
* prefix and making it lower case. For example a page named "XWiki.XWikiServerMyDatabase" would return
* "mydatabase" as the wiki name. This list will also contain the main wiki.
* <p/>
* Note: the wiki name is commonly also the name of the databse where the wiki's data is stored. However, if
* configured accordingly, the database can be diferent from the wiki name, like for example when setting a
* wiki database prefix.
* @deprecated since 5.3, use {@link WikiDescriptorManager#getAllIds()} instead
*/
@Deprecated
public List<String> getVirtualWikisDatabaseNames(XWikiContext context) throws XWikiException
{
WikiDescriptorManager descriptorManager = Utils.getComponent(WikiDescriptorManager.class);
try {
return new ArrayList<String>(descriptorManager.getAllIds());
} catch (WikiManagerException e) {
throw new XWikiException(XWikiException.MODULE_XWIKI, XWikiException.ERROR_XWIKI_UNKNOWN,
"Failed to get the list of wikis", e);
}
}
/**
* @return the cache containing the names of the wikis already initialized.
* @since 1.5M2.
*/
public Cache<DocumentReference> getVirtualWikiCache()
{
return this.virtualWikiMap;
}
/**
* Get the reference of the owner for the provider wiki.
*
* @param wikiName the technical name of the wiki
* @param context the XWiki context
* @return the wiki owner or null if none is set
* @throws XWikiException failed to get wiki descriptor document
*/
public String getWikiOwner(String wikiName, XWikiContext context) throws XWikiException
{
String wikiOwner;
String currentdatabase = context.getWikiId();
try {
context.setWikiId(context.getMainXWiki());
String serverwikipage = getServerWikiPage(wikiName);
XWikiDocument doc = getDocument(serverwikipage, context);
if (doc.isNew()) {
if (!context.isMainWiki(wikiName)) {
throw new XWikiException(XWikiException.MODULE_XWIKI, XWikiException.ERROR_XWIKI_DOES_NOT_EXIST,
"The wiki " + wikiName + " does not exist");
} else {
wikiOwner = null;
}
} else {
wikiOwner = doc.getStringValue(VIRTUAL_WIKI_DEFINITION_CLASS_REFERENCE, "owner");
if (wikiOwner.indexOf(':') == -1) {
wikiOwner = context.getMainXWiki() + ":" + wikiOwner;
}
}
} finally {
context.setWikiId(currentdatabase);
}
return wikiOwner;
}
protected Object createClassFromConfig(String param, String defClass, XWikiContext context) throws XWikiException
{
String storeclass = getConfiguration().getProperty(param, defClass);
try {
Class< ? >[] classes = new Class< ? >[] {XWikiContext.class};
Object[] args = new Object[] {context};
Object result = Class.forName(storeclass).getConstructor(classes).newInstance(args);
return result;
} catch (Exception e) {
Throwable ecause = e;
if (e instanceof InvocationTargetException) {
ecause = ((InvocationTargetException) e).getTargetException();
}
Object[] args = {param, storeclass};
throw new XWikiException(XWikiException.MODULE_XWIKI_STORE,
XWikiException.ERROR_XWIKI_STORE_CLASSINVOCATIONERROR, "Cannot load class {1} from param {0}", ecause,
args);
}
}
public void resetRenderingEngine(XWikiContext context) throws XWikiException
{
XWikiRenderingEngine engine;
try {
engine = Utils.getComponentManager().getInstance(XWikiRenderingEngine.class);
} catch (ComponentLookupException e) {
throw new XWikiException(XWikiException.MODULE_XWIKI_RENDERING, XWikiException.ERROR_XWIKI_UNKNOWN,
"Failed to lookup rendering engine", e);
}
if (engine instanceof Initializable) {
try {
((Initializable) engine).initialize();
} catch (InitializationException e) {
throw new XWikiException(XWikiException.MODULE_XWIKI_RENDERING, XWikiException.ERROR_XWIKI_UNKNOWN,
"Failed to initialize rendering engine", e);
}
}
}
private void preparePlugins(XWikiContext context)
{
setPluginManager(new XWikiPluginManager(getXWikiPreference("plugins", context), context));
String plugins = getConfiguration().getProperty("xwiki.plugins", "");
if (!plugins.equals("")) {
getPluginManager().addPlugins(StringUtils.split(plugins, " ,"), context);
}
}
/**
* @return the XWiki core version as specified in the {@link #VERSION_FILE} file
*/
public String getVersion()
{
if (this.version == null) {
try {
InputStream is = getResourceAsStream(VERSION_FILE);
try {
XWikiConfig properties = new XWikiConfig(is);
this.version = properties.getProperty(VERSION_FILE_PROPERTY);
} finally {
IOUtils.closeQuietly(is);
}
} catch (Exception e) {
// Failed to retrieve the version, log a warning and default to "Unknown"
LOGGER.warn("Failed to retrieve XWiki's version from [" + VERSION_FILE + "], using the ["