-
Notifications
You must be signed in to change notification settings - Fork 3
/
item_tags.py
1905 lines (1722 loc) · 94.9 KB
/
item_tags.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
#TODO completely clean up code
from django.core.urlresolvers import reverse
from django import template
from django.db.models import Q
from django.db import models
from cms.models import *
from cms.permissions import all_possible_item_abilities, all_possible_item_and_global_abilities
from cms.base_viewer import all_viewer_classes
from django.utils.http import urlquote
from django.utils.html import escape, urlize
from django.utils.encoding import force_unicode
from django.core.exceptions import ObjectDoesNotExist
from django.conf import settings
from django.utils.translation import ugettext_lazy as _
from django.utils.timesince import timesince
from django.utils.text import capfirst, truncate_words
from django.utils import simplejson
from django.utils.safestring import mark_safe
from urlparse import urljoin
import os
import itertools
register = template.Library()
###############################################################################
# Helper functions
###############################################################################
def agentcan_global_helper(context, ability, wildcard_suffix=False):
"""
Return a boolean for whether the logged in agent has the specified global
ability. If wildcard_suffix=True, then return True if the agent has **any**
global ability whose first word is the specified ability.
"""
agent = context['cur_agent']
permission_cache = context['_viewer'].permission_cache
if wildcard_suffix:
global_abilities = permission_cache.global_abilities()
return any(x.startswith(ability) for x in global_abilities)
else:
return permission_cache.agent_can_global(ability)
def agentcan_helper(context, ability, item, wildcard_suffix=False):
"""
Return a boolean for whether the logged in agent has the specified ability.
If wildcard_suffix=True, then return True if the agent has **any** ability
whose first word is the specified ability.
"""
agent = context['cur_agent']
permission_cache = context['_viewer'].permission_cache
if wildcard_suffix:
abilities_for_item = permission_cache.item_abilities(item)
return any(x.startswith(ability) for x in abilities_for_item)
else:
return permission_cache.agent_can(ability, item)
def get_viewable_name(context, item):
"""
If the logged in agent can view the item's name, return the item's name.
Otherwise, return a string like "GroupAgent 51".
"""
can_view_name_field = agentcan_helper(context, 'view Item.name', item)
return item.display_name(can_view_name_field)
def get_item_link_tag(context, item, version_number=None):
"""
Return an <a> tag for the item with its name as the text, using
get_viewable_name to calculate the name.
"""
url = escape(item.get_absolute_url())
name = escape(get_viewable_name(context, item))
if version_number is None:
return '<a href="%s">%s</a>' % (url, name)
else:
return '<a href="%s?version=%d">%s</a>' % (url, version_number, name)
def is_method_defined_and_not_inherited_in_class(method_name, class_object):
my_fn = getattr(getattr(class_object, method_name, None), 'im_func', None)
parent_fn = getattr(getattr(class_object.__base__, method_name, None), 'im_func', None)
return my_fn is not None and my_fn is not parent_fn
###############################################################################
# Filters and templates
###############################################################################
#TODO this should be a tag, not a filter
@register.filter
def icon_url(item_type, size=32):
"""
Return a URL for an icon for the item type, size x size pixels.
The item_type can either be a string for the name of the item type, or it
can be a class. If nothing matches, return the generic Item icon.
Special strings, such as "error" and "history", are set to specific icons.
Not all sizes are available (look at static/crystal_project).
"""
item_type_to_icon = {
'error': 'apps/error',
'checkbox': 'apps/clean',
'new': 'apps/easymoblog',
'copy': 'apps/easymoblog',
'history': 'apps/cal',
'subscribe': 'apps/knewsticker',
'relationships': 'apps/proxy',
'permissions': 'apps/ksysv',
'edit': 'apps/kedit',
'delete': 'filesystems/trashcan_empty',
Agent: 'apps/personal',
AuthenticationMethod: 'apps/password',
ContactMethod: 'apps/kontact',
CustomUrl: 'mimetypes/message',
Comment: 'apps/filetypes',
DemeSetting: 'apps/advancedsettings',
Document: 'mimetypes/empty',
DjangoTemplateDocument: 'mimetypes/html',
EmailContactMethod: 'apps/kmail',
Excerpt: 'mimetypes/shellscript',
FileDocument: 'mimetypes/misc',
Folio: 'apps/kfm',
Group: 'apps/Login%20Manager',
Item: 'apps/kblackbox',
Collection: 'filesystems/folder_blue',
Membership: 'filesystems/folder_documents',
Person: 'apps/access',
Site: 'devices/nfs_unmount',
Subscription: 'apps/knewsticker',
TextDocument: 'mimetypes/txt',
Transclusion: 'apps/knotes',
ViewerRequest: 'mimetypes/message',
}
if isinstance(item_type, basestring):
if item_type not in item_type_to_icon:
item_type = get_item_type_with_name(item_type)
if item_type:
return icon_url(item_type, size)
elif isinstance(item_type, Item):
return icon_url(item_type.actual_item_type(), size)
elif isinstance(item_type, type) and issubclass(item_type, Item):
if item_type not in item_type_to_icon:
return icon_url(item_type.__base__, size)
else:
item_type = Item
icon = item_type_to_icon.get(item_type, item_type_to_icon[Item])
return urljoin(settings.MEDIA_URL, "crystal_project/%dx%d/%s.png" % (size, size, icon))
@register.simple_tag
def item_type_verbose_name(item_type):
if isinstance(item_type, basestring):
item_type = get_item_type_with_name(item_type)
elif isinstance(item_type, Item):
item_type = item_type.actual_item_type()
return item_type._meta.verbose_name
@register.simple_tag
def media_url(path):
fs_path = os.path.join(settings.MEDIA_ROOT, path)
if os.path.exists(fs_path):
return urljoin(settings.MEDIA_URL, path)
else:
if settings.DEBUG:
return "[Couldn't find path %s on filesystem]" % path
else:
return '' # Fail silently for invalid paths.
@register.simple_tag
def module_media_url(module_name, path):
fs_path = os.path.join(settings.MODULES_DIR, module_name, 'static', path)
if os.path.exists(fs_path):
path = 'modules/%s/%s' % (module_name, path)
return urljoin(settings.MEDIA_URL, path)
else:
if settings.DEBUG:
return "[Couldn't find path %s on filesystem]" % fs_path
else:
return '' # Fail silently for invalid paths.
class UniversalEditButton(template.Node):
def __init__(self):
pass
def __repr__(self):
return "<UniversalEditButtonNode>"
def render(self, context):
item = context['item']
if item and agentcan_helper(context, 'edit ', item, wildcard_suffix=True):
edit_url = reverse('item_url', kwargs={'viewer': item.get_default_viewer(), 'noun': item.pk, 'action': 'edit'}) + '?version=%s' % item.version_number
return '<link rel="alternate" type="application/wiki" title="Edit" href="%s" />' % escape(edit_url)
else:
return ''
@register.tag
def universal_edit_button(parser, token):
bits = list(token.split_contents())
if len(bits) != 1:
raise template.TemplateSyntaxError, "%r takes no arguments" % bits[0]
return UniversalEditButton()
class IfAgentCan(template.Node):
def __init__(self, ability, item, nodelist_true, nodelist_false):
self.ability = template.Variable(ability)
self.item = template.Variable(item)
self.nodelist_true, self.nodelist_false = nodelist_true, nodelist_false
def __repr__(self):
return "<IfAgentCanNode>"
def render(self, context):
agent = context['cur_agent']
try:
item = self.item.resolve(context)
except template.VariableDoesNotExist:
if settings.DEBUG:
return "[Couldn't resolve item variable]"
else:
return '' # Fail silently for invalid variables.
try:
ability = self.ability.resolve(context)
except template.VariableDoesNotExist:
if settings.DEBUG:
return "[Couldn't resolve ability variable]"
else:
return '' # Fail silently for invalid variables.
if agentcan_helper(context, ability, item):
return self.nodelist_true.render(context)
else:
return self.nodelist_false.render(context)
@register.tag
def ifagentcan(parser, token):
bits = list(token.split_contents())
if len(bits) != 3:
raise template.TemplateSyntaxError, "%r takes two arguments" % bits[0]
end_tag = 'end' + bits[0]
nodelist_true = parser.parse(('else', end_tag))
token = parser.next_token()
if token.contents == 'else':
nodelist_false = parser.parse((end_tag,))
parser.delete_first_token()
else:
nodelist_false = template.NodeList()
return IfAgentCan(bits[1], bits[2], nodelist_true, nodelist_false)
class IfAgentCanGlobal(template.Node):
def __init__(self, ability, nodelist_true, nodelist_false):
self.ability = template.Variable(ability)
self.nodelist_true, self.nodelist_false = nodelist_true, nodelist_false
def __repr__(self):
return "<IfAgentCanNode>"
def render(self, context):
agent = context['cur_agent']
try:
ability = self.ability.resolve(context)
except template.VariableDoesNotExist:
if settings.DEBUG:
return "[Couldn't resolve ability variable]"
else:
return '' # Fail silently for invalid variables.
if agentcan_global_helper(context, ability):
return self.nodelist_true.render(context)
else:
return self.nodelist_false.render(context)
@register.tag
def ifagentcanglobal(parser, token):
bits = list(token.split_contents())
if len(bits) != 2:
raise template.TemplateSyntaxError, "%r takes two arguments" % bits[0]
end_tag = 'end' + bits[0]
nodelist_true = parser.parse(('else', end_tag))
token = parser.next_token()
if token.contents == 'else':
nodelist_false = parser.parse((end_tag,))
parser.delete_first_token()
else:
nodelist_false = template.NodeList()
return IfAgentCanGlobal(bits[1], nodelist_true, nodelist_false)
# remember this includes inactive comments, which should be displayed differently after calling this
def comment_dicts_for_item(item, version_number, context, include_recursive_collection_comments):
permission_cache = context['_viewer'].permission_cache
comment_subclasses = [TextComment]
comments = []
if include_recursive_collection_comments:
if agentcan_global_helper(context, 'do_anything'):
recursive_filter = None
else:
visible_memberships = permission_cache.filter_items('view Membership.item', Membership.objects)
recursive_filter = Q(child_memberships__in=visible_memberships.values('pk').query)
members_and_me_pks_query = Item.objects.filter(active=True).filter(Q(pk=item.pk) | Q(pk__in=item.all_contained_collection_members(recursive_filter).values('pk').query)).values('pk').query
comment_pks = RecursiveComment.objects.filter(parent__in=members_and_me_pks_query).values_list('child', flat=True)
else:
comment_pks = RecursiveComment.objects.filter(parent=item).values_list('child', flat=True)
if comment_pks:
permission_cache.filter_items('view Item.created_at', Comment.objects.filter(pk__in=comment_pks))
permission_cache.filter_items('view Item.creator', Comment.objects.filter(pk__in=comment_pks))
permission_cache.filter_items('view Item.name', Agent.objects.filter(pk__in=Comment.objects.filter(pk__in=comment_pks).values('creator_id').query))
for comment_subclass in comment_subclasses:
new_comments = comment_subclass.objects.filter(pk__in=comment_pks)
related_fields = ['creator']
if include_recursive_collection_comments:
related_fields.extend(['item'])
#TODO the following line breaks on Django 1.2.5 due to https://code.djangoproject.com/ticket/13781 . Uncomment it when fixed, for improved performance of displaying comments
#new_comments = new_comments.select_related(*related_fields)
comments.extend(new_comments)
comments.sort(key=lambda x: x.created_at)
pk_to_comment_info = {}
for comment in comments:
comment_info = {'comment': comment, 'subcomments': []}
pk_to_comment_info[comment.pk] = comment_info
comment_dicts = []
for comment in comments:
child = pk_to_comment_info[comment.pk]
parent = pk_to_comment_info.get(comment.item_id)
if parent:
parent['subcomments'].append(child)
else:
comment_dicts.append(child)
return comment_dicts, len(comments)
class ItemToolbar(template.Node):
def __init__(self):
pass
def __repr__(self):
return "<ItemToolbarNode>"
def render(self, context):
item = context['item']
item_name = get_viewable_name(context, item)
version_number = item.version_number
cur_item_type = context['_viewer'].accepted_item_type
item_type_inheritance = []
while issubclass(cur_item_type, Item):
item_type_inheritance.insert(0, cur_item_type)
cur_item_type = cur_item_type.__base__
result = []
subscribe_url = reverse('item_type_url', kwargs={'viewer': 'subscription', 'action': 'new'}) + '?populate_item=%s' % item.pk
edit_url = reverse('item_url', kwargs={'viewer': item.get_default_viewer(), 'noun': item.pk, 'action': 'edit'}) + '?version=%s' % version_number
copy_url = reverse('item_url', kwargs={'viewer': item.get_default_viewer(), 'noun': item.pk, 'action': 'copy'}) + '?version=%s' % version_number
deactivate_url = reverse('item_url', kwargs={'viewer': item.get_default_viewer(), 'noun': item.pk, 'action': 'deactivate'}) + '?redirect=%s' % urlquote(context['full_path'])
reactivate_url = reverse('item_url', kwargs={'viewer': item.get_default_viewer(), 'noun': item.pk, 'action': 'reactivate'}) + '?redirect=%s' % urlquote(context['full_path'])
destroy_url = reverse('item_url', kwargs={'viewer': item.get_default_viewer(), 'noun': item.pk, 'action': 'destroy'})
add_authentication_method_url = reverse('item_type_url', kwargs={'viewer': 'authenticationmethod', 'action': 'new'}) + '?populate_agent=%s' % item.pk
add_contact_method_url = reverse('item_type_url', kwargs={'viewer': 'contactmethod', 'action': 'new'}) + '?populate_agent=%s' % item.pk
#result.append('<div class="fg-toolbar ui-widget-header ui-corner-all ui-helper-clearfix">')
result.append('<div class="ui-helper-clearfix" style="font-size: 85%;">')
result.append('<div class="fg-buttonset ui-helper-clearfix">')
from cms.forms import AjaxModelChoiceField
result.append("""
<div id="subscribe_dialog" style="display: none;" title="Subscribe to '%s'">
<div style="font-size: 9pt;">Subscriptions send emails to the email contact method specified below for every new notification on this item</div>
<br>
<form method="post" action="%s?redirect=%s">
<input type="hidden" name="item" value="%s" />
Contact Method: %s
<a href="%s" style="float: right; font-size: 9pt;" >Advanced</a>
<input type="submit" value="Submit" />
</form>
</div>
""" % (item_name, reverse('item_type_url', kwargs={'viewer':'subscription', 'action':'dialogcreate'}), context['full_path'], item.pk, AjaxModelChoiceField(EmailContactMethod.objects, permission_cache=context['_viewer'].permission_cache, required_abilities=['add_subscription']).widget.render('email', None, {'id':'memberajaxfield'}), subscribe_url))
if isinstance(item, Agent):
if agentcan_helper(context, 'add_authentication_method', item):
result.append('<a href="%s" class="fg-button ui-state-default fg-button-icon-left ui-corner-all"><span class="ui-icon ui-icon-circle-plus"></span>Add authentication method</a>' % add_authentication_method_url)
if agentcan_helper(context, 'add_contact_method', item):
result.append('<a href="%s" class="fg-button ui-state-default fg-button-icon-left ui-corner-all"><span class="ui-icon ui-icon-circle-plus"></span>Add contact method</a>' % add_contact_method_url)
if not context['cur_agent'].is_anonymous():
result.append("""<a href="#" onclick="openCommentDialog('subscribe_dialog'); return false;" class="fg-button ui-state-default fg-button-icon-left ui-corner-all"><span class="ui-icon ui-icon-mail-closed"></span>Subscribe</a>""")
if agentcan_helper(context, 'edit ', item, wildcard_suffix=True):
result.append('<a href="%s" class="fg-button ui-state-default fg-button-icon-left ui-corner-all"><span class="ui-icon ui-icon-pencil"></span>Edit</a>' % edit_url)
if agentcan_global_helper(context, 'create %s' % item.item_type_string):
result.append('<a href="%s" class="fg-button ui-state-default fg-button-icon-left ui-corner-all"><span class="ui-icon ui-icon-copy"></span>Copy</a>' % copy_url)
if agentcan_global_helper(context, 'create Membership'):
result.append("""<a href="#" onclick="openCommentDialog('additemtocollection%s'); return false;" class="fg-button ui-state-default fg-button-icon-left ui-corner-all"><span class="ui-icon ui-icon-circle-plus"></span>Add this item to collection</a>""" % (item.pk))
result.append( """
<div style="display: none;" id="additemtocollection%(item.pk)s">
<form method="post" action="%(create_url)s?redirect=%(full_path)s">
Collection: %(ajax_field)s
<input type="hidden" name="item" value="%(item.pk)s" /><br><br>
<a href="#" style="float: right; font-size: 9pt;" onclick="displayHiddenDiv('advancedaddtocollection%(item.pk)s'); return false;" >Advanced</a>
<div style="display: none;" id="advancedaddtocollection%(item.pk)s">
Action Summary: <input name="actionsummary" type="text" size="25" maxlength="255" /><br>
Permission Enabled: <input name="permissionenabled" type="checkbox" />
<div style="float: top; font-size: 7pt;">Enable this if you want collection-wide permissions to apply to this child item</div>
</div>
<input type="submit" value="Submit" />
</form>
</div> """ %
{
'item.pk': item.pk,
'full_path': context['full_path'],
'create_url': reverse('item_type_url', kwargs={'viewer':'membership', 'action':'itemmembercreate'}),
'ajax_field': AjaxModelChoiceField(Collection.objects, permission_cache=context['_viewer'].permission_cache, required_abilities=[]).widget.render('collection', None, {'id':'memberajaxfield'}),
})
if item.can_be_deleted() and agentcan_helper(context, 'delete', item):
if item.active:
result.append("""
<script type="text/javascript">
$(function() {
$("#deactivate_dialog").dialog({
autoOpen: false,
bgiframe: true,
modal: true,
buttons: {
'Deactivate': function(){$(this).dialog('close'); $('#deactivate_dialog form').submit()},
'Cancel': function(){$(this).dialog('close')}
}
});
});
</script>
<div id="deactivate_dialog" title="Deactivate this item?" style="display: none;">
<form method="post" action="%s" onsubmit="$('#deactivate_dialog').dialog('close');">
<p><span class="ui-icon ui-icon-alert" style="float:left; margin:0 7px 20px 0;"></span>Are you sure you want to deactivate this item?</p>
<label for="deactivate_reason">Reason</label>
<input type="text" id="deactivate_reason" name="action_summary" />
</form>
</div>
<a href="#" onclick="$('#deactivate_dialog').dialog('open'); return false;" class="fg-button ui-state-default fg-button-icon-solo ui-corner-all" title="Deactivate"><span class="ui-icon ui-icon-trash"></span> Deactivate</a>
""" % deactivate_url)
else:
result.append("""
<script type="text/javascript">
$(function() {
$("#reactivate_dialog").dialog({
autoOpen: false,
bgiframe: true,
modal: true,
buttons: {
'Reactivate': function(){$(this).dialog('close'); $('#reactivate_dialog form').submit()},
'Cancel': function(){$(this).dialog('close')}
}
});
});
</script>
<div id="reactivate_dialog" title="Reactivate this item?" style="display: none;">
<form method="post" action="%s" onsubmit="$('#reactivate_dialog').dialog('close');">
<p><span class="ui-icon ui-icon-alert" style="float:left; margin:0 7px 20px 0;"></span>Are you sure you want to reactivate this item?</p>
<label for="reactivate_reason">Reason</label>
<input type="text" id="reactivate_reason" name="action_summary" />
</form>
</div>
<a href="#" onclick="$('#reactivate_dialog').dialog('open'); return false;" class="fg-button ui-state-default fg-button-icon-left ui-corner-all" title="Reactivate"><span class="ui-icon ui-icon-trash"></span>Reactivate</a>
""" % reactivate_url)
result.append("""
<script type="text/javascript">
$(function() {
$("#destroy_dialog").dialog({
autoOpen: false,
bgiframe: true,
modal: true,
buttons: {
'Destroy': function(){$(this).dialog('close'); $('#destroy_dialog form').submit()},
'Cancel': function(){$(this).dialog('close')}
}
});
});
</script>
<div id="destroy_dialog" title="Destroy this item?" style="display: none;">
<form method="post" action="%s" onsubmit="$('#destroy_dialog').dialog('close');">
<p><span class="ui-icon ui-icon-alert" style="float:left; margin:0 7px 20px 0;"></span>Are you sure you want to destroy this item?</p>
<label for="destroy_reason">Reason</label>
<input type="text" id="destroy_reason" name="action_summary" />
</form>
</div>
<a href="#" onclick="$('#destroy_dialog').dialog('open'); return false;" class="fg-button ui-state-default fg-button-icon-left ui-corner-all" title="Destroy"><span class="ui-icon ui-icon-trash"></span>Destroy</a>
""" % destroy_url)
result.append('</div>')
result.append('</div>')
return '\n'.join(result)
@register.tag
def itemtoolbar(parser, token):
bits = list(token.split_contents())
if len(bits) != 1:
raise template.TemplateSyntaxError, "%r takes zero arguments" % bits[0]
return ItemToolbar()
class ItemDetails(template.Node):
def __init__(self):
pass
def __repr__(self):
return "<ItemDetailsNode>"
def render(self, context):
item = context['item']
result = []
result.append('<table class="twocol" cellspacing="0" style="font-size: 85%;">')
if agentcan_helper(context, 'view Item.name', item) and item.name:
result.append('<tr>')
result.append('<th>Item Name:</th>')
result.append('<td>')
result.append(escape(item.name))
result.append('</td>')
result.append('</tr>')
if agentcan_helper(context, 'view Item.description', item) and item.description:
result.append('<tr>')
result.append('<th>Preface:</th>')
result.append('<td>')
result.append(escape(item.description))
result.append('</td>')
result.append('</tr>')
result.append('<tr>')
result.append('<th>Item type:</th>')
result.append('<td>')
result.append(u'%s' % capfirst(item.actual_item_type()._meta.verbose_name))
result.append('</td>')
result.append('</tr>')
result.append('<tr>')
result.append('<th>Status:</th>')
result.append('<td>')
if item.destroyed:
result.append('<span style="color: #c00;">Destroyed</span>')
elif not item.active:
result.append('<span style="color: #c00;">Inactive</span>')
else:
result.append('<span style="color: #070;">Active</span>')
result.append('</td>')
result.append('</tr>')
if agentcan_helper(context, 'view Item.created_at', item):
result.append('<tr>')
result.append('<th>Created:</th>')
result.append('<td>')
result.append('<span title="%s">%s ago</span>' % (item.created_at.strftime("%Y-%m-%d %H:%M:%S"), timesince(item.created_at)))
result.append('</td>')
result.append('</tr>')
if agentcan_helper(context, 'view Item.creator', item):
result.append('<tr>')
result.append('<th>Creator:</th>')
result.append('<td>')
result.append(get_item_link_tag(context, item.creator))
result.append('</td>')
result.append('</tr>')
for edit_action_notice in EditActionNotice.objects.filter(action_item=item, action_item_version_number=item.version_number)[0:1]:
if agentcan_helper(context, 'view Item.created_at', item):
result.append('<tr>')
result.append('<th>Updated:</th>')
result.append('<td>')
result.append('<span title="%s">%s ago</span>' % (edit_action_notice.action_time.strftime("%Y-%m-%d %H:%M:%S"), timesince(edit_action_notice.action_time)))
result.append('</td>')
result.append('</tr>')
if agentcan_helper(context, 'view Item.creator', item):
result.append('<tr>')
result.append('<th>Updater:</th>')
result.append('<td>')
result.append(get_item_link_tag(context, edit_action_notice.action_agent))
result.append('</td>')
result.append('</tr>')
result.append('</table>')
return '\n'.join(result)
@register.tag
def itemdetails(parser, token):
bits = list(token.split_contents())
if len(bits) != 1:
raise template.TemplateSyntaxError, "%r takes zero arguments" % bits[0]
return ItemDetails()
@register.simple_tag
def display_body_with_inline_transclusions(item, is_html):
#TODO permissions? you should be able to see any Transclusion, but maybe not the id of the comment it refers to
#TODO don't insert these in bad places, like inside a tag <img <a href="....> />
#TODO when you insert a transclusion in the middle of a tag like <b>hi <COMMENT></b> then it gets the style, this is bad
if is_html:
format = lambda text: text
else:
format = lambda text: urlize(escape(text)).replace('\n', '<br />')
transclusions = Transclusion.objects.filter(from_item=item, from_item_version_number=item.version_number, active=True, to_item__active=True).order_by('-from_item_index')
result = []
last_i = None
for transclusion in transclusions:
i = transclusion.from_item_index
result.insert(0, format(item.body[i:last_i]))
result.insert(0, '<a href="%s" class="commentref">%s</a>' % (transclusion.to_item.get_absolute_url(), escape(transclusion.to_item.display_name())))
last_i = i
result.insert(0, format(item.body[0:last_i]))
return ''.join(result)
@register.tag
def newmemberdialog(parser, token):
bits = list(token.split_contents())
if len(bits) != 1:
raise template.TemplateSyntaxError, "%r takes no arguments" % bits[0]
return NewMemberDialog()
class NewMemberDialog(template.Node):
def __init__(self):
pass
def __repr__(self):
return "<NewMemberDialogNode>"
def render(self, context):
from cms.forms import AjaxModelChoiceField
item = context['item']
full_path = context['full_path']
result = []
result.append( """
<div style="display: none;" id="addmember%(item.pk)s">
<form method="post" action="%(create_url)s?redirect=%(full_path)s">
Item: %(ajax_field)s
<input type="hidden" name="collection" value="%(item.pk)s" /><br><br>
<a href="#" style="float: right; font-size: 9pt;" onclick="displayHiddenDiv('advancedaddmember%(item.pk)s'); return false;" >Advanced</a>
<div style="display: none;" id="advancedaddmember%(item.pk)s">
Action Summary: <input name="actionsummary" type="text" size="25" maxlength="255" /><br>
Permission Enabled: <input name="permissionenabled" type="checkbox" />
<div style="float: top; font-size: 7pt;">Enable this if you want collection-wide permissions to apply to this child item</div>
</div>
<input type="submit" value="Submit" />
</form>
</div> """ %
{
'item.pk': item.pk,
'full_path': full_path,
'create_url': reverse('item_type_url', kwargs={'viewer':'membership', 'action':'collectioncreate'}),
'ajax_field': AjaxModelChoiceField(Item.objects, permission_cache=context['_viewer'].permission_cache, required_abilities=[]).widget.render('item', None, {'id':'memberajaxfield'}),
})
return mark_safe('\n'.join(result))
class CalculateComments(template.Node):
def __init__(self):
pass
def __repr__(self):
return "<CalculateCommentsNode>"
def render(self, context):
from cms.forms import CaptchaField
from cms.forms import AjaxModelChoiceField
item = context['item']
version_number = item.version_number
full_path = context['full_path']
try:
default_from_contact_method_pk = EmailContactMethod.objects.filter(agent=context['cur_agent'])[:1].get().pk
except ObjectDoesNotExist:
default_from_contact_method_pk = None
result = []
result.append(u'<div class="comment_box">')
result.append(u'<div class="comment_box_header">')
if agentcan_helper(context, 'comment_on', item):
result.append(u'<button href="#" onclick="openCommentDialog(\'comment%s\'); return false;">[+] Add Comment</button>' % (item.pk))
result.append(u'<div id="comment%s" style="display: none;"><form method="post" action="%s?redirect=%s">'% (item.pk, reverse('item_type_url', kwargs={'viewer': 'textcomment', 'action': 'accordioncreate'}), urlquote(full_path)))
result.append(u'<p>Comment Title: <input name="title" type="text" size="25" maxlength="255" /></p><p>Body: <br><textarea name="body" style="height: 200px; width: 250px;"></textarea> ')
if context['cur_agent'].is_anonymous():
result.append(u'To verify you are not a spammer, please enter in "abc123" <input name="simple_captcha" type="text" size="25" />')
result.append(u'<div id="advancedcomment%s" style="display: none;">Action Summary: <input name="actionsummary" type="text" size="25" maxlength="255" /><br> From Contact Method: %s</div><br> ' % (item.pk, AjaxModelChoiceField(ContactMethod.objects, permission_cache=context['_viewer'].permission_cache, required_abilities=[]).widget.render('new_from_contact_method', default_from_contact_method_pk, {'id':'commentajaxfield'})))
result.append(u' <input type="submit" value="Submit" /> <input type="hidden" name="item" value="%s" /><input type="hidden" name="item_version_number" value="%s" /> ' % (item.pk, item.version_number))
result.append(u'<a href="#" style="float: right; font-size: 9pt;" onclick="displayHiddenDiv(\'advancedcomment%s\'); return false;" >Advanced</a> ' % (item.pk))
result.append(u'</form></div>')
result.append(u'</div>')
else:
result.append("</div>")
def add_comments_to_div(comments, nesting_level=0):
for comment_info in comments:
comment = comment_info['comment']
result.append(u'<div id="comment%s" style="display: none;"><form method="post" action="%s?redirect=%s">'% (comment.pk, reverse('item_type_url', kwargs={'viewer': 'textcomment', 'action': 'accordioncreate'}), urlquote(full_path)))
result.append(u'<input name="title" type="hidden" value="Re: %s" /><p>Body: <br><textarea name="body" style="height: 200px; width: 250px;"></textarea> </p> ' % (comment.name))
if context['cur_agent'].is_anonymous():
result.append(u'To verify you are not a spammer, please enter in "abc123" <input name="simple_captcha" type="text" size="25" />')
result.append(u'<div id="advancedcomment%s" style="display: none;">Action Summary: <input name="actionsummary" type="text" size="25" maxlength="255" /><br> From Contact Method: %s</div><br> ' % (comment.pk, AjaxModelChoiceField(ContactMethod.objects, permission_cache=context['_viewer'].permission_cache, required_abilities=[]).widget.render('new_from_contact_method', default_from_contact_method_pk)))
result.append(u' <input type="submit" value="Submit" /> <input type="hidden" name="item" value="%s" /><input type="hidden" name="item_version_number" value="%s" /> ' % (comment.pk, comment.version_number))
result.append(u'<a href="#" style="float: right; font-size: 9pt;" onclick="displayHiddenDiv(\'advancedcomment%s\'); return false;" >Advanced</a> ' % (comment.pk))
result.append(u'</form></div>')
result.append(u'<div class="comment_outer%s">' % (' comment_outer_toplevel' if nesting_level == 0 else '',))
result.append(u'<div class="comment_header">')
result.append(u'<div style="float: right;"><a href="#" onclick="openCommentDialog(\'comment%s\'); return false;">[+] Respond</a></div>' % (comment.pk))
if issubclass(comment.item.actual_item_type(), Comment):
if agentcan_helper(context, 'view TextDocument.body', comment):
comment_name = escape(truncate_words(comment.display_name(), 4))
else:
comment_name = comment.display_name(can_view_name_field=False)
else:
comment_name = escape(get_viewable_name(context, comment))
result.append(u'<a href="%s">%s</a>' % (comment.get_absolute_url(), comment_name))
if agentcan_helper(context, 'view Item.creator', comment):
result.append('by %s' % get_item_link_tag(context, comment.creator))
if item.pk != comment.item_id and nesting_level == 0:
result.append('for %s' % get_item_link_tag(context, comment.item))
if agentcan_helper(context, 'view Item.created_at', comment):
result.append('<span title="%s">%s ago</span>' % (comment.created_at.strftime("%Y-%m-%d %H:%M:%S"), timesince(comment.created_at)))
result.append("</div>")
if comment.active:
if isinstance(comment, TextComment):
if agentcan_helper(context, 'view TextDocument.body', comment):
comment_body = escape(comment.body).replace('\n', '<br />')
else:
comment_body = ''
else:
comment_body = ''
else:
comment_body = '[INACTIVE]'
result.append(u'<div class="comment_body" style="display: none;">%s</div>' % comment_body)
add_comments_to_div(comment_info['subcomments'], nesting_level + 1)
result.append("</div>")
comment_dicts, n_comments = comment_dicts_for_item(item, version_number, context, isinstance(item, Collection))
add_comments_to_div(comment_dicts)
result.append("</div>")
context['comment_box'] = mark_safe('\n'.join(result))
context['n_comments'] = n_comments
return ''
@register.tag
def calculatecomments(parser, token):
bits = list(token.split_contents())
if len(bits) != 1:
raise template.TemplateSyntaxError, "%r takes no arguments" % bits[0]
return CalculateComments()
class PermissionsBox(template.Node):
def __init__(self):
pass
def __repr__(self):
return "<PermissionsBoxNode>"
def render(self, context):
permission_cache = context['_viewer'].permission_cache
item = context['item']
cur_agent = context['cur_agent']
abilities = permission_cache.item_abilities(item)
result = []
if agentcan_helper(context, 'view_permissions', item):
if agentcan_helper(context, 'do_anything', item):
item_permissions_name = 'Modify permissions'
else:
item_permissions_name = 'View permissions'
item_permissions_url = reverse('item_url', kwargs={'viewer': item.get_default_viewer(), 'noun': item.pk, 'action': 'itempermissions'})
result.append("""<div><a href="%s" class="fg-button ui-state-default fg-button-icon-left ui-corner-all"><span class="ui-icon ui-icon-locked"></span>%s</a></div>""" % (item_permissions_url, item_permissions_name))
if issubclass(item.actual_item_type(), Collection):
if agentcan_helper(context, 'do_anything', item):
collection_permissions_name = 'Modify collection permissions'
else:
collection_permissions_name = 'View collection permissions'
collection_permissions_url = reverse('item_url', kwargs={'viewer': item.get_default_viewer(), 'noun': item.pk, 'action': 'collectionpermissions'})
result.append("""<div><a href="%s" class="fg-button ui-state-default fg-button-icon-left ui-corner-all"><span class="ui-icon ui-icon-locked"></span>%s</a></div>""" % (collection_permissions_url, collection_permissions_name))
if agentcan_helper(context, 'modify_privacy_settings', item) and not agentcan_helper(context, 'do_anything', item):
modify_privacy_url = reverse('item_url', kwargs={'viewer': item.get_default_viewer(), 'noun': item.pk, 'action': 'privacy'})
result.append("""<div><a href="%s" class="fg-button ui-state-default fg-button-icon-left ui-corner-all"><span class="ui-icon ui-icon-locked"></span>Modify privacy</a></div>""" % modify_privacy_url)
result.append("<div>As user %s, you can:</div>" % get_item_link_tag(context, cur_agent))
result.append("<ul>")
friendly_names = [x[1] for x in POSSIBLE_ITEM_AND_GLOBAL_ABILITIES if x[0] in abilities]
for friendly_name in friendly_names:
result.append("<li>%s</li>" % escape(capfirst(friendly_name)))
result.append("</ul>")
return '\n'.join(result)
@register.tag
def permissions_box(parser, token):
bits = list(token.split_contents())
if len(bits) != 1:
raise template.TemplateSyntaxError, "%r takes no arguments" % bits[0]
return PermissionsBox()
class CalculateRelationships(template.Node):
def __init__(self):
pass
def __repr__(self):
return "<CalculateRelationshipsNode>"
def render(self, context):
permission_cache = context['_viewer'].permission_cache
item = context['item']
cur_agent = context['cur_agent']
relationship_sets = []
all_pks = []
for name in sorted(item._meta.get_all_field_names()):
field, model, direct, m2m = item._meta.get_field_by_name(name)
if not isinstance(field, models.related.RelatedObject):
continue
if not isinstance(field.field, models.ForeignKey):
continue
if isinstance(field.field, models.OneToOneField):
continue
if not issubclass(field.model, Item):
continue
manager = getattr(item, name)
relationship_set = {}
relationship_set['name'] = name
relationship_set['field'] = field
viewable_items = manager.filter(active=True)
if viewable_items.count() == 0:
continue
if viewable_items.count() > 500:
context['relationships_box'] = 'Too many related items to render'
context['n_relationships'] = viewable_items.count()
return ''
viewable_items = permission_cache.filter_items('view %s.%s' % (field.model.__name__, field.field.name), viewable_items, cache_results=False)
if field.field.name in field.model.dyadic_relations:
target_field_name, relation_name = field.model.dyadic_relations[field.field.name]
target_field = field.model._meta.get_field_by_name(target_field_name)[0]
target_model = target_field.rel.to
viewable_items = permission_cache.filter_items('view %s.%s' % (field.model.__name__, target_field_name), viewable_items, cache_results=False)
filter_dict = {target_field.rel.related_name + "__in": list(viewable_items), 'active': True}
viewable_items = target_model.objects.filter(**filter_dict)
relationship_set['name'] = relation_name
#TODO set relationship_set['field'] (or just set list_url) so it's correct for this dyadic relation
for related_item in viewable_items:
all_pks.append(item.pk)
relationship_set['items'] = viewable_items
relationship_sets.append(relationship_set)
permission_cache.filter_items('view Item.name', Item.objects.filter(pk__in=all_pks))
result = []
memberOf = []
for relationship_set in relationship_sets:
friendly_name = capfirst(relationship_set['name']).replace('_', ' ')
field = relationship_set['field']
list_url = '%s?filter=%s.%d' % (reverse('item_type_url', kwargs={'viewer': field.model.__name__.lower()}), field.field.name, item.pk)
result.append('<div><a href="%s"><b>%s</b></a></div>' % (list_url, friendly_name))
for related_item in relationship_set['items']:
result.append('<div>%s</div>' % get_item_link_tag(context, related_item))
if friendly_name == "Member of":
memberOf.append('<div>%s</div>' % get_item_link_tag(context, related_item))
context['relationships_box'] = mark_safe('\n'.join(result))
context['memberOf_box'] = mark_safe('\n'.join(memberOf))
context['n_relationships'] = sum(len(x['items']) for x in relationship_sets)
return ''
@register.tag
def calculaterelationships(parser, token):
bits = list(token.split_contents())
if len(bits) != 1:
raise template.TemplateSyntaxError, "%r takes no arguments" % bits[0]
return CalculateRelationships()
class CalculateHistory(template.Node):
def __init__(self):
pass
def __repr__(self):
return "<CalculateHistoryNode>"
def render(self, context):
item = context['item']
result = []
versions = item.versions.all()
edit_action_notices = EditActionNotice.objects.filter(action_item=item)
create_action_notices = CreateActionNotice.objects.filter(action_item=item)
action_notices = itertools.chain(edit_action_notices, create_action_notices)
action_notice_map = {}
for action_notice in action_notices:
action_notice_map[action_notice.action_item_version_number] = action_notice
for version in itertools.chain(versions, [item]):
action_notice = action_notice_map[version.version_number]
version_url = reverse('item_url', kwargs={'viewer': context['viewer_name'], 'action': 'show', 'noun': item.pk}) + '?version=%s' % version.version_number
version_name = u'Version %d' % version.version_number
version_text = u'<a href="%s">%s</a>' % (version_url, version_name)
diff_url = reverse('item_url', kwargs={'viewer': context['viewer_name'], 'action': 'diff', 'noun': item.pk}) + '?version=%s&reference_version=%s' % (version.version_number, version.version_number - 1)
diff_text = u'<a href="%s">(Diff)</a>' % diff_url if version.version_number > 1 else ''
time_text = u'<span title="%s">[%s ago]</span><br />' % (action_notice.action_time.strftime("%Y-%m-%d %H:%M:%S"), timesince(action_notice.action_time))
agent_text = u'by %s' % get_item_link_tag(context, action_notice.action_agent)
result.append(u'<div style="font-size: 85%%; margin-bottom: 5px;">')
if agentcan_helper(context, 'view Item.created_at', item):
result.append(time_text)
result.append(version_text)
result.append(diff_text)
if agentcan_helper(context, 'view Item.creator', item):
result.append(agent_text)
result.append(u'</div>')
context['history_box'] = mark_safe(u'\n'.join(result))
context['n_versions'] = len(versions) + 1
return ''
@register.tag
def calculatehistory(parser, token):
bits = list(token.split_contents())
if len(bits) != 1:
raise template.TemplateSyntaxError, "%r takes no arguments" % bits[0]
return CalculateHistory()
class CalculateActionNotices(template.Node):
def __init__(self):
pass
def __repr__(self):
return "<CalculateActionNoticesNode>"
def render(self, context):
item = context['item']
context['n_action_notices'] = 0
result = []
if agentcan_helper(context, 'view Item.action_notices', item):
#TODO include recursive threads (comment replies, and items in this collection) of action notices
action_notices = ActionNotice.objects.filter(Q(action_item=item) | Q(action_agent=item)).order_by('action_time')
if action_notices.count() > 500:
context['n_action_notices'] = action_notices.count()
context['action_notice_box'] = 'Too many action notices to render'
return ''
action_notice_pk_to_object_map = {}
for action_notice_subclass in [RelationActionNotice, DeactivateActionNotice, ReactivateActionNotice, DestroyActionNotice, CreateActionNotice, EditActionNotice]:
select_related_fields = ['action_agent__name', 'action_item__name']
if action_notice_subclass == RelationActionNotice:
select_related_fields.append('from_item__name')
specific_action_notices = action_notice_subclass.objects.filter(pk__in=action_notices.values('pk').query).select_related(*select_related_fields)
if action_notice_subclass == RelationActionNotice:
context['_viewer'].permission_cache.filter_items('view Item.name', Item.objects.filter(Q(pk__in=specific_action_notices.values('from_item').query)))
for action_notice in specific_action_notices:
action_notice_pk_to_object_map[action_notice.pk] = action_notice
context['_viewer'].permission_cache.filter_items('view Item.name', Item.objects.filter(Q(pk__in=action_notices.values('action_item').query) | Q(pk__in=action_notices.values('action_agent').query)))
for action_notice in action_notices:
action_notice = action_notice_pk_to_object_map[action_notice.pk]
if isinstance(action_notice, RelationActionNotice):
if not agentcan_helper(context, 'view %s.%s' % (action_notice.from_field_model, action_notice.from_field_name), action_notice.from_item):
continue
action_time_text = '<span title="%s">[%s ago]</span>' % (action_notice.action_time.strftime("%Y-%m-%d %H:%M:%S"), timesince(action_notice.action_time))
action_agent_text = get_item_link_tag(context, action_notice.action_agent)
if action_notice.action_item.pk == item.pk:
action_item_name = 'this'
else:
action_item_name = get_viewable_name(context, action_notice.action_item)
action_item_text = get_item_link_tag(context, action_notice.action_item, action_notice.action_item_version_number)
if action_notice.action_summary:
action_summary_text = u' (%s)' % escape(action_notice.action_summary)
else:
action_summary_text = ''
if isinstance(action_notice, RelationActionNotice):
from_item_text = get_item_link_tag(context, action_notice.from_item, action_notice.from_item_version_number)
natural_language_representation = action_notice.natural_language_representation(context['_viewer'].permission_cache)
action_sentence_parts = []
action_sentence_parts.append(action_agent_text)
action_sentence_parts.append(u' made it so ')
for part in natural_language_representation:
if isinstance(part, Item):
if part == action_notice.from_item:
action_sentence_parts.append(from_item_text)
elif part == action_notice.action_item:
action_sentence_parts.append(action_item_text)
else:
action_sentence_parts.append(get_item_link_tag(context, part))
else:
action_sentence_parts.append(unicode(part))
action_sentence = u''.join(action_sentence_parts)
else:
if isinstance(action_notice, DeactivateActionNotice):
action_text = 'deactivated'
if isinstance(action_notice, ReactivateActionNotice):
action_text = 'reactivated'
if isinstance(action_notice, DestroyActionNotice):
action_text = 'destroyed'
if isinstance(action_notice, CreateActionNotice):
action_text = 'created'
if isinstance(action_notice, EditActionNotice):
diff_url = reverse('item_url', kwargs={'viewer': context['viewer_name'], 'action': 'diff', 'noun': action_notice.action_item.pk}) + '?version=%s&reference_version=%s' % (action_notice.action_item_version_number, action_notice.action_item_version_number - 1)
action_text = '<a href="%s">edited</a>' % diff_url
action_sentence = '%s %s %s' % (action_agent_text, action_text, action_item_text)
result.append(u'<div style="font-size: 85%; margin-bottom: 5px;">')
result.append(action_time_text)
result.append(u'<br />')
result.append(action_sentence)
result.append(action_summary_text)
result.append(u'</div>')
context['n_action_notices'] += 1
else:
action_notices = []