-
Notifications
You must be signed in to change notification settings - Fork 9
/
ZWikiPage.py
1559 lines (1358 loc) · 60.3 KB
/
ZWikiPage.py
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
"""
The main Zwiki module. See README.txt.
(c) 1999-2004 Simon Michael <[email protected]> for the zwiki community.
Wikiwikiweb formatting by Tres Seaver <[email protected]>
Parenting code and regulations by Ken Manheimer <[email protected]>
Initial Zope CMF integration by Chris McDonough <[email protected]>
Full credits are at http://zwiki.org/ZwikiContributors .
This product is available under the GNU GPL. All rights reserved, all
disclaimers apply, etc.
"""
from __future__ import nested_scopes
import os, sys, re, string, time, thread
from string import split,join,find,lower,rfind,atoi,strip
from urllib import quote, unquote
from types import *
#import ZODB # need this for pychecker
from AccessControl import getSecurityManager, ClassSecurityInfo
from App.Common import rfc1123_date
from DateTime import DateTime
from Globals import InitializeClass
from OFS.DTMLDocument import DTMLDocument
import Permissions
from Defaults import AUTO_UPGRADE, IDS_TO_AVOID, \
PAGE_METATYPE, LINK_TO_ALL_CATALOGED, LINK_TO_ALL_OBJECTS, \
WIKINAME_LINKS, BRACKET_LINKS, DOUBLE_BRACKET_LINKS, \
DOUBLE_PARENTHESIS_LINKS, ISSUE_LINKS, PAGE_METADATA, \
CONDITIONAL_HTTP_GET, CONDITIONAL_HTTP_GET_IGNORE
from Regexps import url, bracketedexpr, singlebracketedexpr, \
doublebracketedexpr, doubleparenthesisexpr, wikiname, wikilink, \
interwikilink, remotewikiurl, protected_line, zwikiidcharsexpr, \
anywikilinkexpr, markedwikilinkexpr, localwikilink, \
spaceandlowerexpr, dtmlorsgmlexpr, wikinamewords, hashnumberexpr, \
bracketmatch
from Utils import PageUtils, BLATHER, DateTimeSyntaxError, isunicode, \
safe_hasattr, ZOPEVERSION
from Views import PageViews
from OutlineSupport import PageOutlineSupport
from Archive import ArchiveSupport
from Diff import PageDiffSupport # XXX to be replaced by..
from History import PageHistorySupport
from Mail import PageSubscriptionSupport, PageMailSupport, PageMailinSupport
from Catalog import PageCatalogSupport
from CMF import PageCMFSupport
from Comments import PageCommentsSupport
from Admin import PageAdminSupport
from Editing import PageEditingSupport
from i18n import DTMLFile, _
from plugins.pagetypes import PAGETYPES, PAGE_TYPES, pageTypeWithId
from plugins.pagetypes.common import MIDSECTIONMARKER
from plugins.pagetypes.stx import PageTypeStx
from plugins import PLUGINS
DEFAULT_PAGETYPE = PAGETYPES[0]
# see plugins/__init__.py
#
# PageCMFSupport is last to avoid PortalContent.id overriding
# DTMLDocument.id() as older code expects ZWikiPage.id() to be callable.
class ZWikiPage(
PLUGINS[0],
PLUGINS[1],
PLUGINS[2],
PLUGINS[3],
PLUGINS[4],
PLUGINS[5],
PLUGINS[6],
PLUGINS[7],
PLUGINS[8],
PLUGINS[9],
PLUGINS[10],
PLUGINS[11],
PLUGINS[12],
PLUGINS[13],
PLUGINS[14],
PLUGINS[15],
ArchiveSupport,
PageEditingSupport,
PageOutlineSupport,
PageDiffSupport,
PageHistorySupport,
PageMailSupport,
PageMailinSupport,
PageSubscriptionSupport,
PageCatalogSupport,
PageCommentsSupport,
PageAdminSupport,
PageUtils,
PageViews,
DTMLDocument,
PageCMFSupport,
):
"""
A ZWikiPage is essentially a DTML Document which knows how to render
itself in various wiki styles, and can function inside or outside a
CMF site. A lot of extra methods are provided to support
wiki-building, email, issue tracking, etc. Mixins are used to
organize functionality into modules.
"""
if ZOPEVERSION < (2,12):
from webdav.WriteLockInterface import WriteLockInterface
__implements__ = (WriteLockInterface, PageCMFSupport.__implements__)
else:
from webdav.interfaces import IWriteLock
__implements__ = (IWriteLock, PageCMFSupport.__implements__)
security = ClassSecurityInfo()
security.declareObjectProtected('View')
security.declareProtected(Permissions.Edit, 'revert')
security.declareProtected(Permissions.Edit, 'manage_upload')
security.declareProtected(Permissions.FTP, 'manage_FTPstat') # needed
security.declareProtected(Permissions.FTP, 'manage_FTPlist') # ?
def checkPermission(self, permission, object):
return getSecurityManager().checkPermission(permission,object)
# perms need at least one declaration (in this file ?) to be recognized
# this is dumb indeed.. need tests to figure out the rules of this game
security.declareProtected(Permissions.ChangeType, 'dummy')
def dummy(self): pass
security.declareProtected(Permissions.Reparent, 'dummy2')
def dummy2(self): pass
# properties visible in the ZMI
_properties=(
# XXX title is read only for now to avoid de-syncing title & id
# but they can still rename in ZMI.. we should override
# manage_changeProperties and manage_renameObject perhaps
# reverted - too many breakages
{'id':'title', 'type': 'string', 'mode':'w'},
# page_type is now an object.. can we show pageTypeId() ?
#{'id':'page_type', 'type': 'selection', 'mode': 'w',
# 'select_variable': 'ALL_PAGE_TYPES'},
{'id':'creator', 'type': 'string', 'mode': 'r'},
{'id':'creator_ip', 'type': 'string', 'mode': 'r'},
{'id':'creation_time', 'type': 'string', 'mode': 'r'},
{'id':'last_editor', 'type': 'string', 'mode': 'r'},
{'id':'last_editor_ip', 'type': 'string', 'mode': 'r'},
{'id':'last_edit_time', 'type': 'string', 'mode': 'r'},
{'id':'last_log', 'type': 'string', 'mode': 'r'},
{'id':'revision_number', 'type': 'int', 'mode': 'r'},
) \
+ PageOutlineSupport._properties \
+ PageSubscriptionSupport._properties \
+ PageCatalogSupport._properties
meta_type = PAGE_METATYPE
icon = "misc_/ZWiki/ZWikiPage_icon"
creator = ''
creator_ip = ''
creation_time = ''
last_editor = ''
last_editor_ip = ''
last_edit_time = ''
last_log = ''
revision_number = 1
PAGE_TYPES = PAGE_TYPES # used by skin templates
# page_type used to be a string used to select a render method.
# As of 0.25 it is an object which encapsulates the page's formatting
# behaviour. It will return the old id string when called, which
# should keep existing catalogs working.
page_type = DEFAULT_PAGETYPE()
# pre-rendered text cache
_prerendered = ''
def __unicode__(self):
return self.tounicode(self.read())
def __str__(self):
return self.toencoded(self.read())
def setPageType(self,id=None):
self.page_type = id
security.declareProtected('Manage properties', 'setType')
def setType(self,type=DEFAULT_PAGETYPE):
"""Quietly (without leaving history or sending mail) change
this page's page type and re-render it. A helper for
admin cleanup."""
self.setPageType(type)
self.clearCache()
self.index_object()
self.REQUEST.RESPONSE.redirect(self.pageUrl())
security.declarePublic('pageType')
def pageType(self):
"""Return this page's page type as a page type object."""
if AUTO_UPGRADE: self.upgradePageType()
return pageTypeWithId(self.page_type)()
security.declarePublic('pageTypeId')
def pageTypeId(self): # useful for troubleshooting
"""Return the short id for this page's page type."""
return self.pageType().getId()
security.declarePublic('lookupPageType')
def lookupPageType(self,id=None):
"""Return the page type object with this id (or the default)"""
match = filter(lambda x:x._id==id,PAGETYPES)
return (match and match[0]) or DEFAULT_PAGETYPE
def setPreRendered(self,t): self._prerendered = t
def preRendered(self):
# cope with non-existing or None attribute on old instances - needed ?
try:
return unicode(getattr(self,'_prerendered','') or '')
except UnicodeError:
return ''
######################################################################
# initialization
def __init__(self, source_string='', mapping=None, __name__=''):
"""
Initialise this instance, including it's CMF data if applicable.
Ugly, but putting PageCMFSupport before DTMLDocument in the
inheritance order creates problems.
"""
if self.supportsCMF():
PageCMFSupport.__init__(self,
source_string=source_string,
mapping=mapping,
__name__=__name__,
)
else:
DTMLDocument.__init__(self,
source_string=source_string,
mapping=mapping,
__name__=__name__,
)
######################################################################
# generic rendering code (see also pagetypes/*)
security.declareProtected(Permissions.View, '__call__')
def __call__(self, client=None, REQUEST={}, RESPONSE=None, **kw):
"""
Render this zwiki page, or, return a cache-friendly 304 response
if it seems appropriate. Also upgrade it on the fly if needed.
"""
if AUTO_UPGRADE: self.upgrade(REQUEST)
if self.handle_modified_headers(REQUEST=REQUEST): return ''
else: return self.render(client,REQUEST,RESPONSE,**kw)
def render(self, client=None, REQUEST={}, RESPONSE=None, **kw):
"""
Render this page according to it's page_type.
Also tries to ensure the HTTP content-type (and charset) have an
appropriate value. These may be set by the page type, or
overridden by a zwiki_content_type property (LatexWiki support).
NB this can also get set in I18n.py.
"""
if not self.preRendered(): self.preRender()
r = self.pageType().render(self, REQUEST, RESPONSE, **kw)
if RESPONSE:
if safe_hasattr(self,'zwiki_content_type'):
RESPONSE.setHeader('content-type',getattr(self,'zwiki_content_type'))
elif not RESPONSE.getHeader('content-type'):
RESPONSE.setHeader('content-type','text/html')
return r
def preRender(self,clear_cache=0):
"""
Make sure any applicable pre-rendering for this page has been done.
If clear_cache is true, blow away any cached data.
XXX I think this happens anyway.
"""
if clear_cache: self.clearCache()
self.setPreRendered(self.pageType().preRender(self))
security.declarePublic('renderText')
def renderText(self, text, type, **kw):
"""
Render some source text according to the specified page type.
"""
return self.lookupPageType(type)().renderText(self,text,**kw)
security.declareProtected(Permissions.View, 'clearCache')
def clearCache(self,REQUEST=None):
"""
forcibly clear out any cached render data for this page
"""
self.setPreRendered('')
if safe_hasattr(self,'_v_cooked'):
delattr(self,'_v_cooked')
delattr(self,'_v_blocks')
if REQUEST: REQUEST.RESPONSE.redirect(self.pageUrl())
clear = clearCache
def cookDtmlIfNeeded(self):
if self.dtmlAllowed() and self.hasDynamicContent(): self.cook()
security.declareProtected(Permissions.View, 'cook')
def cook(self, cooklock=thread.allocate_lock()):
"""
Pre-parse this page's text (the pre-rendered, if available) for DTML.
"""
t = self.preRendered() or self.read()
# dtml can break with a unicode string here (eg
# test_dtml_in_rst); we'll encode it and decode again in
# evaluatePreRenderedAsDtml
t = self.toencoded(t)
cooklock.acquire()
try:
self._v_blocks=self.parse(t)
self._v_cooked=None
finally:
cooklock.release()
def evaluatePreRenderedAsDtml(self,client=None, REQUEST={},
RESPONSE=None, **kw):
# optimization: to save memory, avoid unnecessarily calling DTML
# and generating _v_blocks data
if not self.hasDynamicContent(): return self.preRendered()
t = DTMLDocument.__call__(
self.__of__(self.folder()), # ensure dtml in pages can acquire
client,
REQUEST,
RESPONSE,
**kw)
# cook encoded it for safe passage through the DTML monster
t = self.tounicode(t)
return t
def renderMidsectionIn(self, text, **kw):
"""
Insert some final things between the rendered document and discussion.
A page's "midsection" is after the pristine gem-like main document,
right before the mudslinging. This is where we want to put the
automatic children list (subtopics), next/prev links, etc.
XXX This is not good enough. The midsection marker can get mixed
up with other rendering in the various page types.
"""
# page may not have been prerendered with midsection marker yet -
# we'll also insert at a messages separator, if we see one,
# otherwise leave it be
if string.find(text,MIDSECTIONMARKER) != -1:
try: doc, discussion = re.split(MIDSECTIONMARKER,text)
except ValueError:
#our marker got clobbered, or there's more than one - bail out
return text
elif string.find(text,r'<a name="messages">') != -1:
doc, discussion = re.split(r'<a name="messages">',text)
discussion = '<a name="messages">' + discussion
else:
return text
return doc + self.renderMidsection(**kw) + discussion
def renderMidsection(self,**kw):
"""
Render whatever should be in this page's midsection.
This is the subtopics, in the preferred style, if enabled, or
nothing. As a convenience, if it seems subtopics are already
displayed via custom DTML code, we won't display them again.
"""
if self.subtopicsEnabled(**kw) and not self.displaysSubtopicsWithDtml():
return self.subtopics()
else:
return ''
def displaysSubtopicsWithDtml(self):
"""
True if this page appears to display subtopics via custom DTML.
"""
return (self.hasDynamicContent() and
self.dtmlAllowed() and
(re.search(r'(?i)(<dtml-var[^>]+subtopics|&dtml-subtopics)',
self.read()) is not None))
security.declareProtected(Permissions.View, 'supportsStx')
def supportsStx(self):
"""supportsStx"""
return self.pageType().supportsStx()
security.declareProtected(Permissions.View, 'supportsRst')
def supportsRst(self):
"""supportsRst"""
return self.pageType().supportsRst()
security.declareProtected(Permissions.View, 'supportsWikiLinks')
def supportsWikiLinks(self):
"""supportsWikiLinks"""
return self.pageType().supportsWikiLinks()
security.declareProtected(Permissions.View, 'supportsHtml')
def supportsHtml(self):
"""Does this page render ordinary HTML tags ?"""
return self.pageType().supportsHtml()
security.declareProtected(Permissions.View, 'supportsDtml')
def supportsDtml(self):
"""Does this page support embedded DTML ?"""
return self.pageType().supportsDtml()
security.declareProtected(Permissions.View, 'hasDynamicContent')
def hasDynamicContent(self):
"""hasDynamicContent"""
return (self.supportsDtml() and
re.search(r'(?i)(<dtml|&dtml)',self.read()) is not None)
security.declareProtected(Permissions.View, 'dtmlAllowed')
def dtmlAllowed(self):
"""Is embedded DTML permitted on this page ?"""
return (
getattr(self,'allow_dtml',0) and
not safe_hasattr(self,'no_dtml')
)
def handle_modified_headers(self, last_mod=None, REQUEST=None):
"""
Check if the headers indicate we have changed content.
Return True if nothing changed, False otherwise. Set Headers as needed.
Methods using this should call this before returning any content,
then if a 304 is called for this method returns True and
the calling method should give no content to the browser.
"""
RESPONSE = getattr(REQUEST,'RESPONSE',None)
if not RESPONSE:return False
RESPONSE.setHeader('Cache-Control',
'max-age=86400, s-maxage=86400, public, must-revalidate, proxy-revalidate')
# do we handle things at all?
if not getattr(self, 'conditional_http_get', CONDITIONAL_HTTP_GET):
return False
# admins can specify a list of property names that make us ignore
# "Conditional HTTP Get" processing if they are set
# especially useful for ignoring pages with allow_dtml
ignore = getattr(
self, 'conditional_http_get_ignore', CONDITIONAL_HTTP_GET_IGNORE)
for ignore_property in ignore:
if getattr(self, ignore_property, False): return False
if last_mod == None:
try:
# bobobase_modification_time reflects also changes
# to voting, not like last_edit_time
last_mod = self.bobobase_modification_time()
except DateTimeSyntaxError:
# if anything goes wrong with the stored date, we just
# ignore all 304 handling and go on as if nothing happened
BLATHER("invalid bobobase_modification time in page %s" \
% (self.id()))
return False
try: # we could have been fed an illegal date string
last_mod = long(DateTime(last_mod).timeTime())
except DateTimeSyntaxError:
BLATHER("invalid date input on page %s" % (self.id()))
return False
header=REQUEST.get_header('If-Modified-Since', None)
if header is not None:
header=header.split( ';')[0]
# Some proxies seem to send invalid date strings for this
# header. If the date string is not valid, we ignore it
# rather than raise an error to be generally consistent
# with common servers such as Apache (which can usually
# understand the screwy date string as a lucky side effect
# of the way they parse it).
# This happens to be what RFC2616 tells us to do in the face of an
# invalid date.
try: mod_since=long(DateTime(header).timeTime())
except DateTimeSyntaxError: mod_since=None
if mod_since is not None:
if last_mod > 0 and last_mod <= mod_since:
RESPONSE.setHeader('Last-Modified',rfc1123_date(last_mod))
RESPONSE.setStatus(304)
return True
RESPONSE.setHeader('Last-Modified', rfc1123_date(last_mod))
return False
# link rendering and handling
def wikinameLinksAllowed(self):
"""Are wikinames linked in this wiki ?"""
return getattr(self,'use_wikiname_links',WIKINAME_LINKS)
def issueLinksAllowed(self):
"""Are issue numbers (#NNNN) linked in this wiki ?"""
return getattr(self,'use_issue_links',ISSUE_LINKS)
def bracketLinksAllowed(self):
"""Are bracketed freeform names linked in this wiki ?"""
return getattr(self,'use_bracket_links',BRACKET_LINKS)
def doubleBracketLinksAllowed(self):
"""Are wikipedia-style double bracketed names linked in this wiki ?"""
return getattr(self,'use_double_bracket_links',DOUBLE_BRACKET_LINKS)
def doubleParenthesisLinksAllowed(self):
"""Are wicked-style double parenthesis names linked in this wiki ?"""
return getattr(
self,'use_double_parenthesis_links',DOUBLE_PARENTHESIS_LINKS)
def isWikiName(self,name):
"""Is name a WikiName ?"""
return re.match('^%s$' % wikiname,name) is not None
def isValidWikiLinkSyntax(self,link):
"""Does link look a valid wiki link syntax for this wiki ?
"""
return ((
(self.wikinameLinksAllowed() and
re.match(wikiname,link))
or (self.issueLinksAllowed() and
re.match(hashnumberexpr,link))
or (self.bracketLinksAllowed() and
re.match(singlebracketedexpr,link))
or (self.doubleBracketLinksAllowed() and
re.match(doublebracketedexpr,link))
or (self.doubleParenthesisLinksAllowed() and
re.match(doubleparenthesisexpr,link))) and 1)
def firstBracketStyle(self): # -> tuple of strings
"""
Find the first allowed freeform link syntax.
"""
if self.bracketLinksAllowed(): return ('[', ']')
if self.doubleBracketLinksAllowed(): return ('[[', ']]')
if doubleParenthesisLinksAllowed(): return ('((', '))')
else:
# XXX: raise? or return something that won't work?
return ('[', ']')
def markLinksIn(self,text,urls=1):
"""
Find and mark links in text, for fast replacement later.
Successor to _preLink. Instead of generating a list of text
extents and link names, this simply marks the links in place to
make them easy to find again. Tries to be smart about finding
links only where you want it to.
As well as all kinds of Zwiki wiki-links, marks bare urls, unless
urls is false (useful for restructured text).
"""
markedtext = ''
state = {'lastend':0,'inpre':0,'incode':0,'intag':0,'inanchor':0}
lastpos = 0
while 1:
m = anywikilinkexpr.search(text,lastpos)
if m:
# found some sort of link pattern - check if we should link it
link = m.group()
linkstart,linkend = m.span()
if (link[0]=='!'
or not (self.isValidWikiLinkSyntax(link)
or (urls and re.match(url,link))
)
or within_literal(linkstart,linkend-1,state,text) # XXX these
or withinSgmlOrDtml((linkstart,linkend),text)): # overlap ?
# no - ignore it (and strip the !)
if link[0] == '!':
link=link[1:]
markedtext += text[lastpos:linkstart] + link
else:
# yes - mark it for later
markedtext += '%s<zwiki>%s</zwiki>' \
% (text[lastpos:linkstart],link)
lastpos = linkend
else:
# no more links - save the final text extent & quit
markedtext += text[lastpos:]
break
return markedtext
def renderMarkedLinksIn(self,text):
"""
Render the links in text previously marked by markLinksIn.
"""
return re.sub(markedwikilinkexpr,self.renderLink,text)
#XXX optimisation - could call renderLink for unique links only
def renderLinksIn(self,text):
"""
Find and render all links in text in one step.
An alternative to the more usual markLinksIn + renderMarkedLinksIn.
"""
t = self.applyWikiLinkLineEscapesIn(text)
# ken's clever thunk_substituter helps keep track of state
return re.sub(anywikilinkexpr, thunk_substituter(self.renderLink, t), t)
wikilink = renderLinksIn # convenience alias
security.declareProtected(Permissions.View, 'applyWikiLinkLineEscapesIn')
def applyWikiLinkLineEscapesIn(self, text):
"""
Escape all wikilinks in lines in text which begin with !.
"""
return re.sub(
protected_line,
lambda m:re.sub(wikilink, r'!\1', m.group(1)),
text)
def renderLink(self,link,state=None,text='',link_title=None,access_key=None):
"""
Render various kinds of hyperlink, based on page and wiki state.
Can be called three ways:
- directly (link should be a string)
- from re.sub (link will be a match object, state will be None)
- from re.sub via thunk substituter (state will be a dictionary) (old)
"""
# preliminaries
if not link: return ''
if type(link) == StringType:
text = self.preRendered()
elif state == None:
link = link.group()
text = self.preRendered()
else:
match = link
link = match.group()
# we are being called from re.sub, using thunk_substituter to
# keep state - do the within_literal and within sgml checks that
# would normally be done in markLinksIn
if (within_literal(match.start(),match.end()-1,state,text) or
withinSgmlOrDtml(match.span(),text)):
return link
link = linkorig = re.sub(markedwikilinkexpr, r'\1', link)
label = None
# here we go
# is this link escaped ?
if link[0] == '!':
return link[1:]
# ignore certain WikiNames from a property ('Lines' type property)
ignore_wikinames = getattr(self, 'ignore_wikinames', [])
if link in ignore_wikinames:
return link
# is it an interwiki link ?
if re.match(interwikilink,link):
return self.renderInterwikiLink(link)
# is it a STX footnote ? check for matching named anchor in the page text
if re.match(singlebracketedexpr,link):
linknobrackets = re.sub(singlebracketedexpr, r'\1', link)
if re.search(
r'(?s)<a name="ref%s"' % (re.escape(linknobrackets)),text):
return '<a href="%s#ref%s" title="footnote %s">[%s]</a>' % (
self.pageUrl(),linknobrackets,
linknobrackets,linknobrackets)
# is it a bare URL ?
if re.match(url,link):
label = re.sub(r'^mailto:','',link)
return '<a href="%s">%s</a>' % (link, label)
# is it a hash number issue link (#123) ?
if re.match(hashnumberexpr,link):
# yes - convert to the id of the issue page with that number
# and continue; if we can't, don't bother linking
p = self.issuePageWithNumber(self.issueNumberFrom(link))
if p:
try: link = p.getId() # XXX poor caching
except AttributeError: link = p.id # all-brains
return self.renderLinkToPage(link,
linkorig=linkorig,
link_title=link_title,
access_key=access_key)
else:
return linkorig
# is it a wiki link, of a kind that's allowed in this wiki ?
# (bare, bracketed, double bracketed, double parenthesis)
if not self.isValidWikiLinkSyntax(link):
# no - we have exhausted our linking arsenal, give up
return linkorig
# is it a freeform (bracketed) wiki link ?
if not self.isWikiName(link):
# yes - use fuzzy matching to match an existing page if possible.
# strip brackets/parentheses
link = stripDelimitersFrom(linkorig)
# XXX experimental MW-style link labels
def linkTargetAndLabel(link):
"""Return target and label from link text possibly containing |."""
l = link.split("|")
if len(l) < 2: l = l + ['']
if len(l) > 2: l = [l[0], '|'.join(l[1:])]
return l[0], l[1]
link, label = linkTargetAndLabel(link)
# end
p = self.pageWithFuzzyName(link)
if p:
# found the page, use its id for linking
try: link = p.getId() # XXX poor caching
except AttributeError: link = p.id # all-brains
else:
# no such page, maybe this is an external link ?
if re.match(url,link):
label = re.sub(r'^mailto:','',label)
return '<a href="%s">%s</a>' % (link, label)
# no - treat it as an uncreated page
return self.renderLinkToPage(link,
linkorig=linkorig,
link_title=link_title,
access_key=access_key,
label=label)
# XXX helper for above
def renderLinkToPage(self,page,linkorig=None,link_title=None,
access_key=None,name=None,label=None):
"""
Render a wiki link to page, which may or may not exist.
page is renderLink's best guess at the id or name of the page
intended.
"""
# does page exist in this wiki ?
p = self.pageWithNameOrId(page)
if p:
# yes - link to it
# make sure we have the page's id
if not self.pageWithId(page): # XXX this check helps avoid zodb loads ?
try: page = p.getId() # XXX poor caching
except AttributeError: page = p.id # all-brains
title = (link_title and ' title="%s"' % link_title) or '' #' title="%s"' % self.pageWithId(page).linkTitle()
name = (name and ' name="%s"' % name) or ''
accesskey = (access_key and ' accesskey="%s"' % access_key) or ''
# XXX tracker plugin dependency
if p.isIssue():
try:
style=' style="background-color:%s;"' % p.issueColour() # poor caching
except AttributeError:
style=' style="background-color:%s;"' % p.issueColour # all-brains
else:
style = ''
link = stripDelimitersFrom(linkorig or page)
label = label and label or self.formatWikiname(link)
return '<a href="%s/%s"%s%s%s%s>%s</a>' % (
self.wikiUrl(),
quote(page),
title,
name,
accesskey,
style,
label)
else:
# no - provide a creation link
return (
'%s<a class="new visualNoPrint" href="%s/%s/createform?page=%s" title="%s">?</a>' % (
self.formatWikiname(linkorig or page),
self.wikiUrl(),
quote(self.id()),
quote(self.toencoded(page)),
_("create this page")))
def renderInterwikiLink(self, link):
"""
Render an occurence of interwikilink. link is a string.
"""
if link[0] == '!': return link[1:]
m = re.match(interwikilink,link)
local, remote = m.group('local'), m.group('remote')
# check local is an allowed link syntax for this wiki
if not self.isValidWikiLinkSyntax(local): return link
local = re.sub(bracketedexpr, r'\1', local) #XXX should support ((..))
# look for a RemoteWikiURL definition
localpage = self.pageWithName(local)
if localpage:
m = re.search(remotewikiurl, localpage.text())
if m:
return '<a href="%s%s">%s:%s</a>' \
% (m.group('remoteurl'),remote,local,remote)
#XXX old html_unquote needed ? I don't think so
# otherwise return unchanged
return link
def _replaceLinksInSourceText(self,oldlink,newlink,text): # -> string; depends on: link styles
"""
Replace occurrences of oldlink with newlink in a string.
Depends on: allowed link styles (brackets etc.) on this wiki
or the current wiki page
Freeform links given should not be enclosed in brackets.
We're trying to keep each link in the style it was before
(e.g. bracket, double parenthesis, WikiLink...)
Only if the new page's canonical id isn't a valid WikiLink
and the old link was a WikiLink will we make the new link
a freeform link (choosing the simplest link style we can find).
We'll also replace bare wiki links to a freeform page's id,
but not fuzzy links.
This tries not to do too much damage.
It's slow, since it re-renders every page it changes.
"""
markedtext = ''
state = {'lastend':0,'inpre':0,'incode':0,'intag':0,'inanchor':0}
lastpos = 0
oldlink_canonical = self.canonicalIdFrom(oldlink)
newlink_is_wikiname = self.isWikiName(newlink)
newlink_canonical = self.canonicalIdFrom(newlink)
newlink_canonical_is_wikiname = self.isWikiName(newlink_canonical)
l, r = self.firstBracketStyle()
while 1:
m = anywikilinkexpr.search(text,lastpos)
if m:
# found some sort of link pattern - check if we should link it
link = m.group()
linkstart,linkend = m.span()
if (not((oldlink in link) or (oldlink_canonical in link)) # not our link
or link[0]=='!'
or not self.isValidWikiLinkSyntax(link)
or within_literal(linkstart,linkend-1,state,text) # XXX these
or withinSgmlOrDtml((linkstart,linkend),text)): # overlap ?
markedtext += text[lastpos:linkstart] + link
else: # yes - change the link
if self.isWikiName(link):
if newlink_is_wikiname:
replacelink = newlink
elif newlink_canonical_is_wikiname:
replacelink = newlink_canonical
else:
replacelink = r'%s%s%s' % (l, newlink, r)
else:
replacelink = bracketmatch.sub(r'\1%s\3' % newlink, link)
markedtext += text[lastpos:linkstart] + replacelink
lastpos = linkend
else:
# no more links - save the final text extent & quit
markedtext += text[lastpos:]
break
return markedtext
security.declareProtected(Permissions.View, 'formatWikiname')
def formatWikiname(self,wikiname):
"""
Convert a wikiname to this wiki's standard display format.
Ie, leave it be or add ungodly spaces depending on the
'space_wikinames' property.
"""
if self.spacedWikinamesEnabled():
return self.spacedNameFrom(wikiname)
else:
return wikiname
security.declareProtected(Permissions.View, 'spacedNameFrom')
def spacedNameFrom(self,pagename):
"""
Return pagename with spaces inserted if it's a WikiName, or unchanged.
Uses the wikiname regexp to follow localised capitalisation.
"""
if re.match('^%s$' % wikiname, pagename):
words = [x[0] for x in re.findall(wikinamewords,pagename)]
return ' '.join(words)
else:
return pagename
security.declareProtected(Permissions.View, 'spacedWikinamesEnabled')
def spacedWikinamesEnabled(self):
"""Should all wikinames be displayed with spaces in this wiki ?"""
return getattr(self.folder(),'space_wikinames',0) and 1
security.declareProtected(Permissions.View, 'links')
def links(self):
"""
List the unique links occurring on this page - useful for cataloging.
Includes urls & interwiki links but not structured text links.
Extracts the marked links from prerendered data.
"""
# don't generate this if missing - too expensive when cataloging ?
#if not self.preRendered(): self.preRender()
links = []
for l in re.findall(markedwikilinkexpr,self.preRendered()):
if not l in links: links.append(l)
return links
security.declareProtected(Permissions.View, 'canonicalLinks')
def canonicalLinks(self):
"""
List the canonical id form of the local wiki links in this page.
Useful for calculating backlinks. Extracts this information
from prerendered data, does not generate this if missing.
"""
clinks = []
localwikilinkexpr = re.compile(localwikilink)
for link in self.links():
if localwikilinkexpr.match(link):
if link[0] == r'[' and link[-1] == r']': link = link[1:-1]
if link[0] == r'[' and link[-1] == r']': link = link[1:-1]
clink = self.canonicalIdFrom(link)
clinks.append(clink)
return clinks
security.declareProtected(Permissions.View, 'linkTitle')
def linkTitle(self,prettyprint=0):
"""
return a suitable value for the title attribute of links to this page
with prettyprint=1, format it for use in the standard header.
"""
return self.linkTitleFrom(self.last_edit_time,
self.lastEditor(),
prettyprint=prettyprint)
# please clean me up
security.declareProtected(Permissions.View, 'linkTitleFrom')
def linkTitleFrom(self,last_edit_time=None,last_editor=None,prettyprint=0):
"""
make a link title string from these last_edit_time and editor strings
with prettyprint=1, format it for use in the standard header.
"""
try:
interval = self.asAgeString(last_edit_time)
except DateTimeSyntaxError:
# we got fed with a non-valid date
interval = self.asAgeString(None)
if not prettyprint:
s = _("last edited %(interval)s ago") % {"interval":interval}
else:
lastlog = self.lastlog()
if lastlog and len(lastlog)>0:
lastlog = ' ('+lastlog+')'
# build the link around the interval
linked_interval = (
' <a href="%s/history" title="%s%s" >%s</a>' % (
self.pageUrl(),
_('show last edit'),
lastlog,
interval))
# use the link in a clear i18n way
s = _('last edited %(interval)s ago') % {"interval": linked_interval}
if (last_editor and
# anonymous? try to find out by somehow matching an ip address:
not re.match(r'^(?:\d{1,3}\.){3}\d{1,3}$',last_editor)):
# escape some things that might cause trouble in an attribute
editor = re.sub(r'"',r'',last_editor)
#XXX cleanup
if not prettyprint:
s = s + " " + _("by %(editor)s")% {"editor":editor}
else:
s = s + " " + _("by %(editor)s") % {"editor":"<b>%s</b>" % editor}
return s
def linkToAllCataloged(self):
return getattr(self,'link_to_all_cataloged',
LINK_TO_ALL_CATALOGED) and 1
def linkToAllObjects(self):
return getattr(self,'link_to_all_objects',
LINK_TO_ALL_OBJECTS) and 1
######################################################################
# page naming and lookup
security.declareProtected(Permissions.View, 'pageName')
def pageName(self):
"""
Return the name of this wiki page, as a unicode string.
This is normally in the title attribute, but use title_or_id to
handle eg pages created via the ZMI.
"""
return self.tounicode(self.title_or_id())
def pageId(self):
return self.id()
security.declareProtected(Permissions.View, 'spacedPageName')
def spacedPageName(self):
"""
Return this page's name, with spaces inserted if it's a WikiName.
We use this for eg the html title tag to improve search engine relevance.
"""
return self.spacedNameFrom(self.pageName())
security.declareProtected(Permissions.View, 'formattedPageName')
def formattedPageName(self):
"""
Return this page's name in the standard display format (spaced or not).
"""