-
Notifications
You must be signed in to change notification settings - Fork 0
/
_zreferableitem.py
454 lines (415 loc) · 17 KB
/
_zreferableitem.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
################################################################################
# _zreferableitem.py
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program 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 General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
################################################################################
# Imports.
from Products.PageTemplates.PageTemplateFile import PageTemplateFile
import base64
import copy
import re
import urllib
# Product Imports.
import standard
import _confmanager
import _objattrs
# ------------------------------------------------------------------------------
# isMailLink:
# ------------------------------------------------------------------------------
def isMailLink(url):
rtn = type(url) is str and url.lower().startswith('mailto:')
return rtn
# ------------------------------------------------------------------------------
# isInternalLink:
# ------------------------------------------------------------------------------
def isInternalLink(url):
rtn = type(url) is str and url.startswith('{$') and url.endswith('}')
return rtn
# ------------------------------------------------------------------------------
# getInternalLinkDict:
# ------------------------------------------------------------------------------
def getInternalLinkDict(self, url):
#-- [ReqBuff]: Fetch buffered value from Http-Request.
docelmnt = self.getDocumentElement()
reqBuffId = 'getInternalLinkDict.%s'%url
try: return docelmnt.fetchReqBuff(reqBuffId)
except: pass
d = {}
# Params.
ref_params = ''
if url.find(';') > 0:
ref_params = url[url.find(';'):-1]
url = '{$%s}'%url[2:url.find(';')]
ref_obj = self.getLinkObj(url)
if ref_obj is not None:
request = self.REQUEST
url = '{$%s%s}'%(self.getRefObjPath( ref_obj)[2:-1],ref_params)
d['data-id'] = url
d['data-url'] = getInternalLinkUrl(self,url,ref_obj)
if not ref_obj.isActive(request):
d['data-target'] = "inactive"
elif self.getTrashcan().isAncestor(ref_obj):
d['data-target'] = 'trashcan'
else:
d['data-id'] = "{$__%s__}"%url[2:-1]
d['data-target'] = "missing"
#-- [ReqBuff]: Returns value and stores it in buffer of Http-Request.
return docelmnt.storeReqBuff( reqBuffId, d)
# ------------------------------------------------------------------------------
# getInternalLinkUrl:
# ------------------------------------------------------------------------------
def getInternalLinkUrl(self, url, ob):
request = self.REQUEST
if ob is None:
index_html = './index_%s.html?error_type=NotFound&op=not_found&url=%s'%(request.get('lang',self.getPrimaryLanguage()),str(url))
else:
# Contextualized index_html.
context = request.get('ZMS_THIS',self)
index_html = ob.getHref2IndexHtmlInContext(context,REQUEST=request)
return index_html
# ----------------------------------------------------------------------------
# getInlineRefs:
#
# Parses internal links.
# ----------------------------------------------------------------------------
def getInlineRefs(text):
l = []
p = '<a(.*?)>(.*?)<\\/a>'
r = re.compile(p)
for f in r.findall(str(text)):
d = dict(re.findall('\\s(.*?)="(.*?)"',f[0]))
if d.has_key('data-id'):
l.append(d['data-id'])
return l
################################################################################
################################################################################
###
### class ZReferableItem
###
################################################################################
################################################################################
class ZReferableItem:
# Management Permissions.
# -----------------------
__authorPermissions__ = (
'manage_RefForm', 'manage_browse_iframe',
)
__ac_permissions__=(
('ZMS Author', __authorPermissions__),
)
# Management Interface.
# ---------------------
manage_RefForm = PageTemplateFile('zpt/ZMSLinkElement/manage_refform',globals())
manage_browse_iframe = PageTemplateFile('zpt/ZMSLinkElement/manage_browse_iframe',globals())
# ----------------------------------------------------------------------------
# ZReferableItem.getRelativeUrl:
# ----------------------------------------------------------------------------
def getRelativeUrl(self, path, url):
import urlparse
import posixpath
u_dest = urlparse.urlsplit(url)
u_src = urlparse.urlsplit(path)
_uc1 = urlparse.urlunsplit(u_dest[:2]+tuple('' for i in range(3)))
_uc2 = urlparse.urlunsplit(u_src[:2]+tuple('' for i in range(3)))
if _uc1 != _uc2:
## This is a different domain
return url
_relpath = posixpath.relpath(u_dest.path, posixpath.dirname(u_src.path))
return './%s'%urlparse.urlunsplit(('', '', _relpath, u_dest.query, u_dest.fragment))
# ----------------------------------------------------------------------------
# ZReferableItem.getRefObjPath:
# ----------------------------------------------------------------------------
def getRefObjPath(self, ob, anchor=''):
ref = ''
if ob is not None:
def default(*args, **kwargs):
self = args[0]
ob = args[1]['ob']
anchor = args[1]['anchor']
abs_home = self.getAbsoluteHome().getPhysicalPath()
ob_home = ob.getPhysicalPath()[len(abs_home)-1:]
path = '/'.join(ob_home).replace('/content/','@')
if path.startswith('@'):
path = path[1:]
return '{$' + path + anchor + '}'
request = self.REQUEST
key = request.get('ExtensionPoint.ZReferableItem.getRefObjPath','ExtensionPoint.ZReferableItem.getRefObjPath')
ref = self.evalExtensionPoint(key,default,ob=ob,anchor=anchor)
return ref
"""
##############################################################################
###
### References FROM other objects.
###
##############################################################################
"""
# ----------------------------------------------------------------------------
# ZReferableItem.getRefByObjs:
#
# Returns references FROM other objects.
# ----------------------------------------------------------------------------
def getRefByObjs(self, REQUEST=None):
ref_by = []
if 'ref_by' in self.__dict__.keys():
ref_by = self.ref_by
ref_by = list(set(ref_by))
return ref_by
# ----------------------------------------------------------------------------
# ZReferableItem.synchronizeRefByObjs:
#
# Synchronizes references FROM other objects.
# ----------------------------------------------------------------------------
def synchronizeRefByObjs(self, strict=1):
v = self.getRefByObjs()
ref_by = []
for i in v:
ob = self.getLinkObj(i)
if ob is not None:
for ref_to in ob.getRefToObjs():
ref_ob = self.getLinkObj(ref_to)
if self == ref_ob:
ref = self.getRefObjPath(ob)
ref_by.append(ref)
break
ref_by = list(set(ref_by))
ref_by.sort()
if ref_by != v:
self.ref_by = ref_by
return ref_by
# ----------------------------------------------------------------------------
# ZReferableItem.registerRefObj:
#
# Registers reference FROM other object.
# ----------------------------------------------------------------------------
def registerRefObj(self, ob):
ref = self.getRefObjPath(ob)
standard.writeLog(self,'[registerRefObj]: ref='+ref)
ref_by = self.synchronizeRefByObjs()
if ref not in ref_by:
ref_by.append(ref)
self.ref_by = ref_by
# ----------------------------------------------------------------------------
# ZReferableItem.unregisterRefObj:
#
# Unregisters reference FROM other object.
# ----------------------------------------------------------------------------
def unregisterRefObj(self, ob):
ref = self.getRefObjPath(ob)
standard.writeLog(self,'[unregisterRefObj]: ref='+ref)
ref_by = self.synchronizeRefByObjs()
if ref in ref_by:
ref_by = filter( lambda x: x!=ref,ref_by)
self.ref_by = ref_by
"""
##############################################################################
###
### References TO other objects.
###
##############################################################################
"""
# ----------------------------------------------------------------------------
# ZReferableItem.getRefToObjs:
#
# Returns list of references TO other objects.
# ----------------------------------------------------------------------------
def getRefToObjs(self):
d = {}
for key in self.getObjAttrs().keys():
objAttr = self.getObjAttr(key)
datatype = objAttr['datatype']
if datatype in ['richtext','string','text','url']:
lang_suffixes = ['']
if objAttr['multilang']:
lang_suffixes = map(lambda x:'_%s'%x,self.getLangIds())
for lang_suffix in lang_suffixes:
for obj_vers in self.getObjVersions():
v = getattr(obj_vers,'%s%s'%(key,lang_suffix),None)
if v is not None:
if datatype in ['richtext','string','text']:
for iv in getInlineRefs(str(v)):
ref_ob = self.getLinkObj(iv)
if ref_ob is not None:
ref = self.getRefObjPath(ref_ob)
d[ref] = 1
elif datatype in ['url']:
ref_ob = self.getLinkObj(v)
if ref_ob is not None:
ref = self.getRefObjPath(ref_ob)
d[ref] = 1
return d.keys()
# ----------------------------------------------------------------------------
# ZReferableItem.prepareRefreshRefToObjs:
#
# Prepare refresh of references TO other objects.
# ----------------------------------------------------------------------------
def prepareRefreshRefToObjs(self):
standard.writeBlock( self, '[prepareRefreshRefToObjs]')
if 'ref_to' not in self.__dict__.keys():
self.ref_to = self.getRefToObjs()
# ----------------------------------------------------------------------------
# ZReferableItem.refreshRefToObjs:
#
# Synchronizes references TO other objects.
# ----------------------------------------------------------------------------
def refreshRefToObjs(self):
standard.writeBlock( self, '[refreshRefToObjs]')
if 'ref_to' in self.__dict__.keys():
old_ref_to = self.ref_to
standard.writeBlock( self, '[refreshRefToObjs]: old=%s'%str(old_ref_to))
new_ref_to = self.getRefToObjs()
standard.writeBlock( self, '[refreshRefToObjs] new=%s'%str(old_ref_to))
delattr(self,'ref_to')
for ref in old_ref_to:
ref_ob = self.getLinkObj(ref)
if ref_ob is not None:
self_ref = ref_ob.getRefObjPath(self)
if ref not in new_ref_to and self_ref in ref_ob.synchronizeRefByObjs():
ref_ob.unregisterRefObj(self)
for ref in new_ref_to:
ref_ob = self.getLinkObj(ref)
if ref_ob is not None:
self_ref = ref_ob.getRefObjPath(self)
if ref not in old_ref_to or self_ref not in ref_ob.synchronizeRefByObjs():
ref_ob.registerRefObj(self)
"""
##############################################################################
###
### Resolve Links
###
##############################################################################
"""
# ----------------------------------------------------------------------------
# ZReferableItem.validateInlineLinkObj:
#
# Validates internal links.
# ----------------------------------------------------------------------------
def validateInlineLinkObj(self, text):
if not int(self.getConfProperty('ZReferableItem.validateLinkObj',1)): return text
for pq in [('<a(.*?)>','href'),('<img(.*?)>','src')]:
p = pq[0]
q = pq[1]
r = re.compile(p)
for f in r.findall(str(text)):
d = dict(re.findall('\\s(.*?)="(.*?)"',f))
if d.has_key('data-id'):
old = p.replace('(.*?)',f)
url = d['data-id']
ild = getInternalLinkDict(self,url)
for k in ild.keys():
d[{'data-url':q}.get(k,k)] = ild[k]
new = p.replace('(.*?)',' '.join(['']+map(lambda x:'%s="%s"'%(x,d[x]),d.keys())))
if old != new:
text = text.replace(old,new)
return text
# ----------------------------------------------------------------------------
# ZReferableItem.validateLinkObj:
#
# Validates internal links.
# ----------------------------------------------------------------------------
def validateLinkObj(self, url):
if not int(self.getConfProperty('ZReferableItem.validateLinkObj',1)): return url
if isInternalLink(url):
if not url.startswith('{$__'):
ild = getInternalLinkDict(self,url)
url = ild['data-id']
return url
# ----------------------------------------------------------------------------
# ZReferableItem.getLinkObj:
#
# Resolves internal/external links and returns Object.
# ----------------------------------------------------------------------------
def getLinkObj(self, url, REQUEST=None):
ob = None
if isInternalLink(url):
def default(*args, **kwargs):
self = args[0]
url = args[1]['url']
ob = None
if not url.startswith('{$__'):
# Find document-element.
zmspath = url[2:-1].replace('@','/content/')
l = zmspath.split('/')
ob = self
try:
for id in filter(lambda x:len(x)>0,l):
new_ob = getattr(ob,id,None)
if new_ob is None:
new_ob = ob
while new_ob is not None and new_ob.id != id:
new_ob = new_ob.aq_parent
ob = new_ob
except:
pass
return ob
# Params.
ref_params = {}
if url.find(';') > 0:
ref_params = dict(re.findall(';(\w*)=(\w*)',url[url.find(';'):-1]))
url = '{$%s}'%url[2:url.find(';')]
# Get object.
ob = self.evalExtensionPoint('ExtensionPoint.ZReferableItem.getLinkObj',default,url=url)
# Prepare request
if ob is not None and ob.id not in self.getPhysicalPath():
request = self.REQUEST
ob.set_request_context(request,ref_params)
return ob
# ----------------------------------------------------------------------------
# ZReferableItem.getLinkUrl:
#
# Resolves internal/external links and returns URL.
# ----------------------------------------------------------------------------
def getLinkUrl( self, url, REQUEST=None):
request = self.REQUEST
if isInternalLink(url):
# Params.
ref_params = {}
if url.find(';') > 0:
ref_params = dict(re.findall(';(\w*)=(\w*)',url[url.find(';'):-1]))
url = '{$%s}'%url[2:url.find(';')]
# Anchor.
ref_anchor = ''
if url.find('#') > 0:
ref_anchor = url[url.find('#'):-1]
# Prepare request.
bak_params = {}
for key in ref_params.keys():
bak_params[key] = request.get(key,None)
request.set(key,ref_params[key])
# Get index_html.
ref_obj = self.getLinkObj(url)
index_html = getInternalLinkUrl(self,url,ref_obj)
# Unprepare request.
for key in bak_params.keys():
request.set(key,bak_params[key])
# Return index_html.
url = index_html + ref_anchor
elif isMailLink (url):
prefix = 'mailto:'
url = 'javascript:window.location.href=\''+prefix+'\'+atob(\''+base64.b64encode(url[len(prefix):].encode()).decode()+'\')'
return url
# ----------------------------------------------------------------------------
# ZReferableItem.tal_anchor:
#
# @param href
# @param target
# @param attrs
# @param content
# @return
# ----------------------------------------------------------------------------
def tal_anchor(self, href, target='', attrs={}, content=''):
filtered_attrs_keys = filter(lambda x: len(x)>0, attrs.keys())
str_attrs = ' '.join( map(lambda x:str(x)+'=\042'+str(attrs[x]+'\042'), filtered_attrs_keys) )
return '<a href="%s" %s %s>%s</a>'%(href,['',' target="%s"'%target][int(len(target)>0)],str_attrs,content)
################################################################################