/
views.py
executable file
·703 lines (571 loc) · 24.8 KB
/
views.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
import re
import json
from plone.app.layout.viewlets.common import FooterViewlet
from plone.app.layout.viewlets.common import ViewletBase
from Products.Five import BrowserView
from AccessControl import getSecurityManager
from Products.CMFPlone.PloneBatch import Batch
from Products.CMFCore.permissions import ModifyPortalContent
from Products.CMFCore.utils import getToolByName
from Products.Five.browser.pagetemplatefile import ViewPageTemplateFile
from plone.app.portlets.interfaces import IColumn
from zope.interface import Interface
from plone.portlets.interfaces import IPortletManager
from plone.memoize.instance import memoize
from zope.component import getMultiAdapter
from collective.portletpage.browser.portletpage import TwoColumns
from plone.portlet.collection import collection as base
from plone.app.search.browser import Search
from plone.app.layout.viewlets.common import GlobalSectionsViewlet
from plone.app.i18n.locales.browser.selector import LanguageSelector
from zope.component import queryAdapter
from plone.multilingual.interfaces import ITG
from plone.multilingual.interfaces import NOTG
from plone.app.multilingual.browser.selector import getPostPath, addQuery
from plone.app.portlets.browser.manage import ManageContextualPortlets
from collective.portletpage.browser.interfaces import IManagePortletPagePortletsView
from zope.component import getUtility
from plone.registry.interfaces import IRegistry
from collective.leadmedia.interfaces import ICanContainMedia
from zope.interface import implements
from plone.app.uuid.utils import uuidToCatalogBrain, uuidToObject
from z3c.relationfield.interfaces import IRelationValue
SHOP_AVAILABLE = True
try:
from bda.plone.cart import get_item_data_provider
from bda.plone.shop.interfaces import IBuyable
except ImportError:
SHOP_AVAILABLE = False
from decimal import Decimal
try:
from Products.PloneGetPaid.interfaces import IBuyableMarker
from Products.PloneGetPaid.interfaces import PayableMarkerMap
from Products.PloneGetPaid.interfaces import IPayableMarker
GETPAID_EXISTS = True
except ImportError:
GETPAID_EXISTS = False
class CommonBrowserView(BrowserView):
"""
Common utilities for all the other views
"""
nxt = None
prv = None
def showManageButton(self):
secman = getSecurityManager()
if not secman.checkPermission('Portlets: Manage portlets', self.context):
return False
else:
return True
def addPaypalButton(self, label, name, price):
return """
<form action="https://www.paypal.com/cgi-bin/webscr" method="post" onSubmit="return Arnolfini.trackEcommerce('%(name)s', '%(price).2f', 'Book')">
<input name="business" type="hidden" value="general@intk.com" />
<input name="amount" type="hidden" value="%(price).2f" />
<input name="item_name" type="hidden" value="%(name)s" />
<input name="no-shipping" type="hidden" value="1" />
<input name="currency_code" type="hidden" value="GBP" />
<input name="cpp_header_image" type="hidden" value="http://new.arnolfini.org.uk/++resource++plonetheme.arnolfini.images/arnolfiniLogo.png" />
<input name="return" type="hidden" value="http://www.arnolfini.org.uk/purchase/thank-you/" />
<input name="cmd" type="hidden" value="_xclick" />
<input type="submit" value="%(label)s" />
</form>
"""%{"price": price, "name": name, "label": label}
def payable(self, item):
"""Return the payable (shippable) version of the context.
"""
if GETPAID_EXISTS:
iface = PayableMarkerMap.get(IBuyableMarker, None)
if iface is None:
print("Something is badly wrong here.")
return None
return iface( item )
else:
return none
def checkPermission(self, item, permission):
secman = getSecurityManager()
return secman.checkPermission(permission, item)
def getTagsAsClass(self, item):
classes = []
for tag in item.Subject:
classes.append("tag_%s"%tag.replace(" ", "_"))
return " ".join(classes)
def hasVideoTag(self, item):
classes = []
if not hasattr(item, 'getURL'):
uuid = item.UID()
item = uuidToCatalogBrain(uuid)
for tag in item.Subject:
if tag == "video":
return True
return False
def slideshow(self, parent):
"""
Creates a slideshow with the media from parent
"""
parentURL = parent.absolute_url()
structure = """
<div class="embededMediaShow">
<a href="%s?recursive=true">slideshow</a>
</div>
"""%parentURL
return structure
def checkYoutubeLink(self, link):
"""
Check if a URL is a youtube video
"""
isYoutube = link.find("youtube") != -1
youtubeId = ""
amp = link.find("&")
if isYoutube and amp != -1:
youtubeId = link[link.find("?v=")+3:amp]
elif isYoutube and amp == -1:
youtubeId = link[link.find("?v=")+3:]
return isYoutube, youtubeId
def checkVimeoLink(self, link):
"""
Check if URL is a vimeo video
"""
isVimeo = link.find("vimeo") != -1
vimeoId = ""
if isVimeo:
vimeoId = link.split("vimeo.com/")[1]
return isVimeo, vimeoId
def getLeadMediaTag(self, item, scale="large"):
if item.portal_type == 'Link':
isYoutube, youtubeId = self.checkYoutubeLink(item.getRemoteUrl)
isVimeo, vimeoId = self.checkVimeoLink(item.getRemoteUrl)
embed = ""
if isYoutube:
return '<iframe id="'+youtubeId+'" width="100%" height="393" src="http://www.youtube.com/embed/'+youtubeId+'?rel=0&enablejsapi=1" frameborder="0" allowfullscreen></iframe>'
elif isVimeo:
return '<iframe src="http://player.vimeo.com/video/'+vimeoId+'?title=0&byline=0&portrait=0" width="100%" height="393" frameborder="0"></iframe>'
if item.portal_type == 'Image':
if hasattr(item, 'getURL'):
lead = item.getURL()
else:
lead = item.absolute_url()
elif hasattr(item, 'leadMedia'):
leadUID = item.leadMedia
leadBrain = uuidToCatalogBrain(leadUID)
if leadBrain:
lead = leadBrain.getURL()
else:
lead = None
else:
brains = uuidToCatalogBrain(item.UID())
if brains:
leadUID = brains.leadMedia
leadBrain = uuidToCatalogBrain(leadUID)
if leadBrain:
lead = leadBrain.getURL()
else:
lead = None
else:
lead = None
if lead is not None:
crop = ""
if hasattr(item, 'getURL'):
return '<img src="%(url)s" alt="%(title)s" title="%(title)s" />%(crop)s'%{'url': "%s/@@images/image/%s"%(lead, scale), 'title':item.Title(), 'crop':crop}
else:
return '<img src="%(url)s" alt="%(title)s" title="%(title)s" />%(crop)s'%{'url': "%s/@@images/image/%s"%(lead, scale), 'title':item.Title(), 'crop':crop}
def containsMedia(self, item):
if item.portal_type == "Collection":
return len(self.getCollectionMedia(item)) > 0
if hasattr(item, 'leadMedia'):
return item.leadMedia != None
else:
uuid = item.UID()
brains = uuidToCatalogBrain(uuid)
if brains:
return brains.leadMedia != None
else:
return False
def getPressKit(self, item):
if item.restrictedTraverse('@@plone').isStructuralFolder():
catalog = getToolByName(self.context, 'portal_catalog')
plone_utils = getToolByName(self.context, 'plone_utils')
path = '/'.join(item.getPhysicalPath())
sm = getSecurityManager()
results = catalog.searchResults(path = {'query' : path}, portal_type = 'Press Kit')
for result in results:
if sm.checkPermission('View', result):
return result
return None
else:
return None
def trimText(self, text, limit, strip=False):
if text != None:
if strip:
text = self.stripTags(text)
if len(text) > limit:
res = text[0:limit]
lastspace = res.rfind(" ")
res = res[0:lastspace] + " ..."
return res
else:
return text
else:
return ""
def stripTags(self, text):
return re.sub('<[^<]+?>', '', text)
def getTwoWayRelatedContent(self):
"""
Gets all the manually related content both related items of the current context and items where the current context is marked as related.
"""
filtered = []
related = []
related = self.context.getRefs()
backRelated = self.context.getBRefs()
related.extend(backRelated)
result = self._uniq(related);
for res in result:
if self.checkPermission(res, 'View'):
filtered.append(res)
return filtered
def getContentAsLinks(self, content):
"""
A commodity, this formats a content list as an HTML structure of titles with links. Comma separated. Used to list the artists related to an exhibition.
"""
result = []
workflow = getToolByName(self.context,'portal_workflow')
sortedContent = sorted(content, key=lambda res: res.portal_type == 'Media Person' and self._normalizePersonName(res.title) or res.title)
for res in sortedContent:
if self.checkPermission(res, 'View'):
if res.portal_type == 'Media Person':
result.append('<a href="%(link)s" class="%(state_class)s">%(title)s</a>'%{'link':res.absolute_url(), 'title':self._normalizePersonName(res.title), 'state_class': 'state-' + queryUtility(IIDNormalizer).normalize(workflow.getInfoFor(res,'review_state'))})
else:
result.append('<a href="%(link)s" class="%(state_class)s">%(title)s</a>'%{'link':res.absolute_url(), 'title':res.title, 'state_class': 'state-' + queryUtility(IIDNormalizer).normalize(workflow.getInfoFor(res,'review_state'))})
return ", ".join(result)
def getTwoWayRelatedContentOfType(self, typeList):
result = []
for res in self.getTwoWayRelatedContent():
if res.portal_type in typeList:
result.append(res)
return result
def _normalizePersonName(self, person):
names = person.split(",")
if len(names) == 2:
return "%s %s"%(names[1], names[0])
else:
return person
def isEventPast(self, event):
"""
Checks if the event is already past
"""
if event.portal_type != 'Event' and event.portal_type != 'Media Event':
return False
else:
t = DateTime(time.time())
if event.end() is not None:
end = DateTime(event.end())
return end.year() < t.year() or (end.year() == t.year() and end.month() < t.month()) or(end.year() == t.year() and end.month() == t.month() and end.day() < t.day())
else:
start = DateTime(event.start())
return start.year() < t.year() or (start.year() == t.year() and start.month() < t.month()) or(start.year() == t.year() and start.month() == t.month() and start.day() < t.day())
def getCurrentTime(self):
"""
Utility, returns a current DateTime object.
"""
return DateTime()
def getFormattedEventDate(self, event):
"""
Formats the start and end dates properly and marks the event as past or future
"""
if event.portal_type != 'Event' and event.portal_type != 'Media Event':
return ""
if event.start() is None or event.end() is None:
if event.start() is None and event.end() is None:
return ""
else:
samedate = True
else:
samedate = event.start().strftime('%d - %m - %Y') == event.end().strftime('%d - %m - %Y')
exceptions = ""
if hasattr(event, 'exceptions'):
exceptions = event.exceptions
finalDatesFmt = '<div class="dates %(class)s"><span class="dateText">%(dates)s%(hours)s %(exceptions)s</span></div>'
dates = "%s"%(samedate and (event.start() is not None and event.start().strftime('%A %d %B %Y') or event.end().strftime('%A %d %B %Y')) or "%s to %s"%(event.start().strftime('%A %d %B %Y'), event.end().strftime('%A %d %B %Y')))
openingHour = event.start() is not None and event.start().strftime('%H:%M') or ""
closingHour = event.end() is not None and event.end().strftime('to %H:%M') or ""
hoursExist = 'to %s'%openingHour != closingHour
hours = hoursExist and '<span class="hours">, %s %s</span>'%(openingHour, closingHour) or '<span class="hours">, %s</span>'%openingHour
finalDates = finalDatesFmt%{'class': self.isEventPast(event) and 'past' or 'future', 'dates': dates, 'hours': hours, 'exceptions':exceptions}
return finalDates
def isBuyable(self, item):
"""
Check if an item is buyable with PloneGetPaid
"""
if not GETPAID_EXISTS:
return False
else:
return IBuyableMarker.providedBy(item)
def getEventBookingLink(self, event):
"""
Check if the booking information is a link or just a code. return a full url
"""
if not event.getBooking():
return ""
else:
if event.getLink().find("http://") != -1:
return event.getLink()
else:
return 'http://purchase.tickets.com/buy/TicketPurchase?agency=ARNOLFINI&organ_val=26385&schedule=list&event_val=%s'%event.getLink()
def _uniq(self, alist): # Fastest order preserving
set = {}
return [set.setdefault(e,e) for e in alist if e not in set]
class SearchView(CommonBrowserView, Search):
"""
Adding to Search view
"""
def getItemTitle(self, item):
title = item.Title()
brain = item._brain
sm = getSecurityManager()
if not sm.checkPermission(ModifyPortalContent, self.context):
return title
if brain.portal_type == "Object":
obj = brain.getObject()
if obj.identification_identification_objectNumber:
title = "%s - %s" %(obj.identification_identification_objectNumber, title)
return title
def checkUserPermission(self):
sm = getSecurityManager()
if sm.checkPermission(ModifyPortalContent, self.context):
return True
return False
def getSearchFilters(self):
searchFilters = []
registry = getUtility(IRegistry)
searchFiltersRecord = registry['searchfilters.folders']
filters = list(searchFiltersRecord)
catalog = getToolByName(self.context, 'portal_catalog')
for uid in filters:
item = uuidToObject(uid)
if item:
searchFilters.append({"name": item.Title(), "path": '/'.join(item.getPhysicalPath())})
return searchFilters
class PagePortletView(ViewletBase):
"""
helper classes for pagePortlet
"""
def showManageButton(self):
secman = getSecurityManager()
if not secman.checkPermission('Portlets: Manage portlets', self.context):
return False
else:
return True
class FooterView(FooterViewlet):
"""
helper classes for footer
"""
def showManageButton(self):
secman = getSecurityManager()
if not secman.checkPermission('Portlets: Manage portlets', self.context):
return False
else:
return True
class FolderListing(CommonBrowserView):
"""'
Override of folder_listing view
"""
def results(self, batch=True, b_start = 0, pagesize=33, sort_on='sortable_title', only_documented=False):
results = []
if self.context.portal_type == 'Collection':
results = self.context.results(batch=batch, b_size=pagesize, sort_on=sort_on, b_start=b_start)
return results
elif self.context.portal_type in ['Folder', 'Press Kit']:
brains = self.context.getFolderContents()
if only_documented:
final_res = []
for res in brains:
if res.leadMedia:
final_res.append(res)
else:
final_res = list(brains)
if batch:
results = Batch(final_res, pagesize, start=b_start)
else:
return final_res
return results
def getPrice(self, item):
if SHOP_AVAILABLE:
item_data = get_item_data_provider(item)
net_price = Decimal(item_data.net)
vat = item_data.vat
if vat % 2 != 0:
item_vat = Decimal(vat).quantize(Decimal('1.0'))
else:
item_vat = Decimal(vat)
gross_price = net_price + net_price / Decimal(100) * item_vat
return gross_price
else:
return float(0.0)
def isBuyable(self, item):
if SHOP_AVAILABLE:
return IBuyable.providedBy(item)
else:
return False
def getItemTitle(self, item):
if item.title != "" and item.title != None:
return item.title
if hasattr(item, 'identification_taxonomy'):
if len(item.identification_taxonomy) > 0:
taxonomy = item.identification_taxonomy[0]
common_name = taxonomy['common_name']
if common_name != "" and common_name != None:
return common_name
scientific_name = taxonomy['scientific_name']
if scientific_name != "" and scientific_name != None:
return scientific_name
if hasattr(item, 'identification_identification_objectNumber'):
return item.identification_identification_objectNumber
return ""
def getImageObject(self, item):
if item.portal_type == "Image":
return item.getObject()
if item.leadMedia != None:
uuid = item.leadMedia
media_object = uuidToObject(uuid)
if media_object:
return media_object
class CollectionPortlet(base.Renderer, FolderListing):
"""
Extend portlet base renderer
"""
_template = ViewPageTemplateFile("alternative_templates/portletcollection.pt")
render = _template
class ContentView(BrowserView):
def getFBdetails(self):
item = self.context
state = getMultiAdapter(
(item, self.request),
name=u'plone_context_state')
obj = ICanContainMedia(item)
details = {}
details["title"] = item.Title()
details["type"] = "article"
details["site_name"] = "Teylers Museum"
details["url"] = item.absolute_url()
details["description"] = item.Description()
details["double_image"] = ""
details["image"] = ""
image = obj.getLeadMedia()
if image != None:
details["image"] = image.absolute_url()+'/@@images/image/large'
else:
details["image"] = ""
return details
def showManageButton(self):
secman = getSecurityManager()
if not secman.checkPermission('Portlets: Manage portlets', self.context):
return False
else:
return True
class NumberOfResults(CommonBrowserView):
"""
Called by AJAX to know how many results in the collection. Returns JSON.
"""
def getJSON(self):
callback = hasattr(self.request, 'callback') and 'json' + self.request['callback'] or None
only_documented = not hasattr(self.request, 'only_documented')
result = None
if self.context.portal_type == 'Collection':
brains = self.context.queryCatalog(batch=False)
if only_documented:
result = []
for res in brains:
if res.leadMedia:
result.append(res)
if result is not None:
jsonStr = json.dumps(len(result))
else:
jsonStr = json.dumps(result)
if callback is not None:
return callback +'(' + jsonStr + ')'
else:
return jsonStr
class get_image_resolution(BrowserView):
"""
Called by AJAX to know original resolution of image.
"""
def get_image_resolution(self):
result = {"success": False}
if self.context.portal_type == "Image":
ob = self.context
if ob.image != None:
result["success"] = True
w, h = ob.image.getImageSize()
result["w"] = w
result["h"] = h
jsonStr = json.dumps(result)
return jsonStr
class CustomManagePortlets(ManageContextualPortlets):
"""View used for the edit screen
"""
implements(IManagePortletPagePortletsView)
def __init__(self, context, request):
# Skip past the main parent constructor, since it sets disable_border
super(ManageContextualPortlets, self).__init__(context, request)
class TableView(BrowserView):
index = ViewPageTemplateFile('templates/table_view.pt')
def getYear(self, item):
obj = item.getObject()
if hasattr(obj, 'titleAuthorImprintCollation_imprint_year'):
year = obj.titleAuthorImprintCollation_imprint_year
return year
else:
return None
def getAuthor(self, context_author, item):
fieldnames = {
"Book":"titleAuthorImprintCollation_titleAuthor_author",
"Audiovisual":"titleAuthorImprintCollation_titleAuthor_author",
"Article":"titleAuthorSource_titleAuthor_author",
"Serial":"titleAuthorImprintCollation_titleAuthor_author",
"Resource":"resourceDublinCore_creators"
}
obj = item.getObject()
obj_portal_type = obj.portal_type;
author_field = ""
if obj_portal_type in fieldnames:
author_field = fieldnames[obj_portal_type]
if author_field:
if hasattr(obj, author_field):
authors = getattr(obj, author_field, "")
if authors:
author = authors[0]
if obj_portal_type == "Resource":
authors_list = author
else:
if 'authors' in author:
authors_list = author['authors']
else:
authors_list = None
if authors_list:
if obj_portal_type == "Resource":
author_person = authors_list
else:
author_person = authors_list[0]
portal_type = getattr(author_person, 'portal_type', '')
author_url = ""
author_name = ""
if IRelationValue.providedBy(author_person):
person = author_person.to_object
author_url = person.absolute_url()
author_name = getattr(person, 'title', '')
elif portal_type == "PersonOrInstitution":
author_url = author_person.absolute_url()
author_name = getattr(author_person, 'title', '')
final_author = "<a href='%s'>%s</a>" %(author_url, author_name)
return final_author
else:
return ""
else:
return ""
else:
return context_author.get('name_or_id', None)
else:
return context_author.get('name_or_id', None)
def render(self):
return self.index()
def __call__(self):
return self.render()