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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
|
# Copyright 2009-2011 Canonical Ltd. This software is licensed under the
# GNU Affero General Public License version 3 (see the file LICENSE).
"""IBug related view classes."""
__metaclass__ = type
__all__ = [
'BugContextMenu',
'BugEditView',
'BugFacets',
'BugMarkAsAffectingUserView',
'BugMarkAsDuplicateView',
'BugNavigation',
'BugSecrecyEditView',
'BugSetNavigation',
'BugTextView',
'BugURL',
'BugView',
'BugViewMixin',
'BugWithoutContextView',
'DeprecatedAssignedBugsView',
'MaloneView',
]
from datetime import (
datetime,
timedelta,
)
from email.MIMEMultipart import MIMEMultipart
from email.MIMEText import MIMEText
import re
from lazr.enum import (
EnumeratedType,
Item,
)
from lazr.lifecycle.event import ObjectModifiedEvent
from lazr.lifecycle.snapshot import Snapshot
import pytz
from zope import formlib
from zope.app.form.browser import TextWidget
from zope.component import getUtility
from zope.event import notify
from zope.interface import (
implements,
Interface,
providedBy,
)
from zope.schema import (
Bool,
Choice,
)
from zope.security.interfaces import Unauthorized
from canonical.launchpad import _
from canonical.launchpad.browser.librarian import ProxiedLibraryFileAlias
from canonical.launchpad.mailnotification import MailWrapper
from canonical.launchpad.searchbuilder import (
any,
greater_than,
)
from canonical.launchpad.webapp import (
canonical_url,
ContextMenu,
LaunchpadView,
Link,
Navigation,
StandardLaunchpadFacets,
stepthrough,
structured,
)
from canonical.launchpad.webapp.authorization import check_permission
from canonical.launchpad.webapp.interfaces import (
ICanonicalUrlData,
ILaunchBag,
)
from lp.app.browser.launchpadform import (
action,
custom_widget,
LaunchpadEditFormView,
LaunchpadFormView,
)
from lp.app.errors import NotFoundError
from lp.app.widgets.itemswidgets import LaunchpadRadioWidgetWithDescription
from lp.app.widgets.project import ProjectScopeWidget
from lp.bugs.browser.widgets.bug import BugTagsWidget
from lp.bugs.interfaces.bug import (
IBug,
IBugSet,
)
from lp.bugs.interfaces.bugattachment import (
BugAttachmentType,
IBugAttachmentSet,
)
from lp.bugs.interfaces.bugnomination import IBugNominationSet
from lp.bugs.interfaces.bugtask import (
BugTaskSearchParams,
BugTaskStatus,
IFrontPageBugTaskSearch,
)
from lp.bugs.interfaces.bugwatch import IBugWatchSet
from lp.bugs.interfaces.cve import ICveSet
from lp.bugs.mail.bugnotificationbuilder import format_rfc2822_date
from lp.services import features
from lp.services.fields import DuplicateBug
from lp.services.propertycache import cachedproperty
class BugNavigation(Navigation):
"""Navigation for the `IBug`."""
# It would be easier, since there is no per-bug sequence for a BugWatch
# and we have to leak the BugWatch.id anyway, to hang bugwatches off a
# global /bugwatchs/nnnn
# However, we want in future to have them at /bugs/nnn/+watch/p where p
# is not the BugWatch.id but instead a per-bug sequence number (1, 2,
# 3...) for the 1st, 2nd and 3rd watches added for this bug,
# respectively. So we are going ahead and hanging this off the bug to
# which it belongs as a first step towards getting the basic URL schema
# correct.
usedfor = IBug
@stepthrough('+watch')
def traverse_watches(self, name):
"""Retrieve a BugWatch by name."""
if name.isdigit():
# in future this should look up by (bug.id, watch.seqnum)
return getUtility(IBugWatchSet)[name]
@stepthrough('+subscription')
def traverse_subscriptions(self, person_name):
"""Retrieve a BugSubscription by person name."""
for subscription in self.context.subscriptions:
if subscription.person.name == person_name:
return subscription
@stepthrough('attachments')
def traverse_attachments(self, name):
"""Retrieve a BugAttachment by ID.
If an attachment is found, redirect to its canonical URL.
"""
if name.isdigit():
attachment = getUtility(IBugAttachmentSet)[name]
if attachment is not None and attachment.bug == self.context:
return self.redirectSubTree(
canonical_url(attachment), status=301)
@stepthrough('+attachment')
def traverse_attachment(self, name):
"""Retrieve a BugAttachment by ID.
Only return a attachment if it is related to this bug.
"""
if name.isdigit():
attachment = getUtility(IBugAttachmentSet)[name]
if attachment is not None and attachment.bug == self.context:
return attachment
@stepthrough('nominations')
def traverse_nominations(self, nomination_id):
"""Traverse to a nomination by id."""
if nomination_id.isdigit():
try:
return getUtility(IBugNominationSet).get(nomination_id)
except NotFoundError:
return None
class BugFacets(StandardLaunchpadFacets):
"""The links that will appear in the facet menu for an `IBug`.
However, we never show this, but it does apply to things like
bug nominations, by 'acquisition'.
"""
usedfor = IBug
enable_only = []
class BugSetNavigation(Navigation):
"""Navigation for the IBugSet."""
usedfor = IBugSet
@stepthrough('+text')
def text(self, name):
"""Retrieve a bug by name."""
try:
return getUtility(IBugSet).getByNameOrID(name)
except (NotFoundError, ValueError):
return None
class BugContextMenu(ContextMenu):
"""Context menu of actions that can be performed upon a Bug."""
usedfor = IBug
links = [
'editdescription', 'markduplicate', 'visibility', 'addupstream',
'adddistro', 'subscription', 'addsubscriber', 'editsubscriptions',
'addcomment', 'nominate', 'addbranch', 'linktocve', 'unlinkcve',
'createquestion', 'mute_subscription', 'removequestion',
'activitylog', 'affectsmetoo']
def __init__(self, context):
# Always force the context to be the current bugtask, so that we don't
# have to duplicate menu code.
ContextMenu.__init__(self, getUtility(ILaunchBag).bugtask)
@cachedproperty
def _use_advanced_features(self):
"""Return True if advanced subscriptions features are enabled."""
return features.getFeatureFlag(
'malone.advanced-subscriptions.enabled')
def editdescription(self):
"""Return the 'Edit description/tags' Link."""
text = 'Update description / tags'
return Link('+edit', text, icon='edit')
def visibility(self):
"""Return the 'Set privacy/security' Link."""
text = 'Change privacy/security'
return Link('+secrecy', text)
def markduplicate(self):
"""Return the 'Mark as duplicate' Link."""
return Link('+duplicate', 'Mark as duplicate')
def addupstream(self):
"""Return the 'lso affects project' Link."""
text = 'Also affects project'
return Link('+choose-affected-product', text, icon='add')
def adddistro(self):
"""Return the 'Also affects distribution' Link."""
text = 'Also affects distribution'
return Link('+distrotask', text, icon='add')
def subscription(self):
"""Return the 'Subscribe/Unsubscribe' Link."""
user = getUtility(ILaunchBag).user
if user is None:
text = 'Subscribe/Unsubscribe'
icon = 'edit'
elif user is not None and (
self.context.bug.isSubscribed(user) or
self.context.bug.isSubscribedToDupes(user)):
if self._use_advanced_features:
if self.context.bug.isMuted(user):
text = 'Subscribe'
icon = 'add'
else:
text = 'Edit subscription'
icon = 'edit'
else:
text = 'Unsubscribe'
icon = 'remove'
else:
text = 'Subscribe'
icon = 'add'
return Link('+subscribe', text, icon=icon, summary=(
'When you are subscribed, Launchpad will email you each time '
'this bug changes'))
def addsubscriber(self):
"""Return the 'Subscribe someone else' Link."""
text = 'Subscribe someone else'
return Link(
'+addsubscriber', text, icon='add', summary=(
'Launchpad will email that person whenever this bugs '
'changes'))
def editsubscriptions(self):
"""Return the 'Edit subscriptions' Link."""
text = 'Edit bug mail'
return Link(
'+subscriptions', text, icon='edit', summary=(
'View and change your subscriptions to this bug'))
def mute_subscription(self):
"""Return the 'Mute subscription' Link."""
user = getUtility(ILaunchBag).user
if self.context.bug.isMuted(user):
text = "Unmute bug mail"
link = "+subscribe"
else:
text = "Mute bug mail"
link = "+mute"
return Link(
link, text, icon='remove', summary=(
"Mute this bug so that you will not receive emails "
"about it."))
def nominate(self):
"""Return the 'Target/Nominate for series' Link."""
launchbag = getUtility(ILaunchBag)
target = launchbag.product or launchbag.distribution
if check_permission("launchpad.Driver", target):
text = "Target to series"
return Link('+nominate', text, icon='milestone')
elif (check_permission("launchpad.BugSupervisor", target) or
self.user is None):
text = 'Nominate for series'
return Link('+nominate', text, icon='milestone')
else:
return Link('+nominate', '', enabled=False, icon='milestone')
def addcomment(self):
"""Return the 'Comment or attach file' Link."""
text = 'Add attachment or patch'
return Link('+addcomment', text, icon='add')
def addbranch(self):
"""Return the 'Add branch' Link."""
text = 'Link a related branch'
return Link('+addbranch', text, icon='add')
def linktocve(self):
"""Return the 'Link to CVE' Link."""
text = structured(
'Link to '
'<abbr title="Common Vulnerabilities and Exposures Index">'
'CVE'
'</abbr>')
return Link('+linkcve', text, icon='add')
def unlinkcve(self):
"""Return 'Remove CVE link' Link."""
enabled = self.context.bug.has_cves
text = 'Remove CVE link'
return Link('+unlinkcve', text, icon='remove', enabled=enabled)
@property
def _bug_question(self):
return self.context.bug.getQuestionCreatedFromBug()
def createquestion(self):
"""Create a question from this bug."""
text = 'Convert to a question'
enabled = self._bug_question is None
return Link('+create-question', text, enabled=enabled, icon='add')
def removequestion(self):
"""Remove the created question from this bug."""
text = 'Convert back to a bug'
enabled = self._bug_question is not None
return Link('+remove-question', text, enabled=enabled, icon='remove')
def activitylog(self):
"""Return the 'Activity log' Link."""
text = 'See full activity log'
return Link('+activity', text)
def affectsmetoo(self):
"""Return the 'This bug affects me too' link."""
enabled = getUtility(ILaunchBag).user is not None
return Link('+affectsmetoo', 'change', enabled=enabled)
class MaloneView(LaunchpadFormView):
"""The Bugs front page."""
custom_widget('searchtext', TextWidget, displayWidth=50)
custom_widget('scope', ProjectScopeWidget)
schema = IFrontPageBugTaskSearch
field_names = ['searchtext', 'scope']
# Test: standalone/xx-slash-malone-slash-bugs.txt
error_message = None
page_title = 'Launchpad Bugs'
@property
def target_css_class(self):
"""The CSS class for used in the target widget."""
if self.target_error:
return 'error'
else:
return None
@property
def target_error(self):
"""The error message for the target widget."""
return self.getFieldError('scope')
def initialize(self):
"""Initialize the view to handle the request."""
LaunchpadFormView.initialize(self)
bug_id = self.request.form.get("id")
if bug_id:
self._redirectToBug(bug_id)
elif self.widgets['scope'].hasInput():
self._validate(action=None, data={})
def _redirectToBug(self, bug_id):
"""Redirect to the specified bug id."""
if not isinstance(bug_id, basestring):
self.error_message = "Bug %r is not registered." % bug_id
return
if bug_id.startswith("#"):
# Be nice to users and chop off leading hashes
bug_id = bug_id[1:]
try:
bug = getUtility(IBugSet).getByNameOrID(bug_id)
except NotFoundError:
self.error_message = "Bug %r is not registered." % bug_id
else:
return self.request.response.redirect(canonical_url(bug))
def getMostRecentlyFixedBugs(self, limit=5, when=None):
"""Return the ten most recently fixed bugs."""
if when is None:
when = datetime.now(pytz.timezone('UTC'))
date_closed_limits = [
timedelta(days=1),
timedelta(days=7),
timedelta(days=30),
None,
]
for date_closed_limit in date_closed_limits:
fixed_bugs = []
search_params = BugTaskSearchParams(
self.user, status=BugTaskStatus.FIXRELEASED,
orderby='-date_closed')
if date_closed_limit is not None:
search_params.date_closed = greater_than(
when - date_closed_limit)
fixed_bugtasks = self.context.searchTasks(search_params)
# XXX: Bjorn Tillenius 2006-12-13:
# We might end up returning less than :limit: bugs, but in
# most cases we won't, and '4*limit' is here to prevent
# this page from timing out in production. Later I'll fix
# this properly by selecting bugs instead of bugtasks.
# If fixed_bugtasks isn't sliced, it will take a long time
# to iterate over it, even over just 10, because
# Transaction.iterSelect() listifies the result.
for bugtask in fixed_bugtasks[:4 * limit]:
if bugtask.bug not in fixed_bugs:
fixed_bugs.append(bugtask.bug)
if len(fixed_bugs) >= limit:
return fixed_bugs
return fixed_bugs
def getCveBugLinkCount(self):
"""Return the number of links between bugs and CVEs there are."""
return getUtility(ICveSet).getBugCveCount()
class BugViewMixin:
"""Mix-in class to share methods between bug and portlet views."""
@cachedproperty
def subscription_info(self):
return IBug(self.context).getSubscriptionInfo()
@property
def direct_subscribers(self):
"""Return the list of direct subscribers."""
return self.subscription_info.direct_subscriptions.subscribers
@property
def duplicate_subscribers(self):
"""Return the list of subscribers from duplicates.
This includes all subscribers who are also direct or indirect
subscribers.
"""
return self.subscription_info.duplicate_subscriptions.subscribers
@cachedproperty
def subscriber_ids(self):
"""Return a dictionary mapping a css_name to user name."""
subscribers = set().union(
self.direct_subscribers,
self.duplicate_subscribers)
# The current user has to be in subscribers_id so
# in case the id is needed for a new subscription.
user = getUtility(ILaunchBag).user
if user is not None:
subscribers.add(user)
ids = {}
for sub in subscribers:
ids[sub.name] = 'subscriber-%s' % sub.id
return ids
def getSubscriptionClassForUser(self, subscribed_person):
"""Return a set of CSS class names based on subscription status.
For example, "subscribed-false dup-subscribed-true".
"""
if subscribed_person in self.duplicate_subscribers:
dup_class = 'dup-subscribed-true'
else:
dup_class = 'dup-subscribed-false'
if subscribed_person in self.direct_subscribers:
return 'subscribed-true %s' % dup_class
else:
return 'subscribed-false %s' % dup_class
@property
def current_user_subscription_class(self):
bug = self.context
if bug.personIsSubscribedToDuplicate(self.user):
dup_class = 'dup-subscribed-true'
else:
dup_class = 'dup-subscribed-false'
if (bug.personIsDirectSubscriber(self.user) and not
bug.isMuted(self.user)):
return 'subscribed-true %s' % dup_class
else:
return 'subscribed-false %s' % dup_class
@property
def current_user_mute_class(self):
bug = self.context
subscription_class = self.current_user_subscription_class
if self.user_should_see_mute_link:
visibility_class = ''
else:
visibility_class = 'hidden'
if bug.isMuted(self.user):
return 'muted-true %s %s' % (subscription_class, visibility_class)
else:
return 'muted-false %s %s' % (
subscription_class, visibility_class)
@cachedproperty
def user_should_see_mute_link(self):
"""Return True if the user should see the Mute link."""
if features.getFeatureFlag('malone.advanced-subscriptions.enabled'):
user_is_subscribed = (
self.context.isMuted(self.user) or
self.context.isSubscribed(self.user) or
self.context.isSubscribedToDupes(self.user) or
self.context.personIsAlsoNotifiedSubscriber(self.user))
return user_is_subscribed
else:
return False
@cachedproperty
def _bug_attachments(self):
"""Get a dict of attachment type -> attachments list."""
# Note that this is duplicated with get_comments_for_bugtask
# if you are looking to consolidate things.
result = {
BugAttachmentType.PATCH: [],
'other': [],
}
for attachment in self.context.attachments_unpopulated:
info = {
'attachment': attachment,
'file': ProxiedLibraryFileAlias(
attachment.libraryfile, attachment),
}
if attachment.type == BugAttachmentType.PATCH:
key = attachment.type
else:
key = 'other'
result[key].append(info)
return result
@property
def regular_attachments(self):
"""The list of bug attachments that are not patches."""
return self._bug_attachments['other']
@property
def patches(self):
"""The list of bug attachments that are patches."""
return self._bug_attachments[BugAttachmentType.PATCH]
class BugView(LaunchpadView, BugViewMixin):
"""View class for presenting information about an `IBug`.
Since all bug pages are registered on IBugTask, the context will be
adapted to IBug in order to make the security declarations work
properly. This has the effect that the context in the pagetemplate
changes as well, so the bugtask (which is often used in the pages)
is available as `current_bugtask`. This may not be all that pretty,
but it was the best solution we came up with when deciding to hang
all the pages off IBugTask instead of IBug.
"""
@property
def current_bugtask(self):
"""Return the current `IBugTask`.
'current' is determined by simply looking in the ILaunchBag utility.
"""
return getUtility(ILaunchBag).bugtask
@property
def subscription(self):
"""Return whether the current user is subscribed."""
user = self.user
if user is None:
return False
return self.context.isSubscribed(user)
def duplicates(self):
"""Return a list of dicts of duplicates.
Each dict contains the title that should be shown and the bug
object itself. This allows us to protect private bugs using a
title like 'Private Bug'.
"""
duplicate_bugs = list(self.context.duplicates)
current_task = self.current_bugtask
dupes_in_current_context = dict(
(bugtask.bug, bugtask)
for bugtask in current_task.target.searchTasks(
BugTaskSearchParams(self.user, bug=any(*duplicate_bugs))))
dupes = []
for bug in duplicate_bugs:
dupe = {}
try:
dupe['title'] = bug.title
except Unauthorized:
dupe['title'] = 'Private Bug'
dupe['id'] = bug.id
# If the dupe has the same context as the one we're in, link
# to that bug task directly.
if bug in dupes_in_current_context:
dupe['url'] = canonical_url(dupes_in_current_context[bug])
else:
dupe['url'] = canonical_url(bug)
dupes.append(dupe)
return dupes
def proxiedUrlForLibraryFile(self, attachment):
"""Return the proxied download URL for a Librarian file."""
return ProxiedLibraryFileAlias(
attachment.libraryfile, attachment).http_url
class BugWithoutContextView:
"""View that redirects to the new bug page.
The user is redirected, to the oldest IBugTask ('oldest' being
defined as the IBugTask with the smallest ID.)
"""
# XXX: BradCrittenden 2009-04-28 This class can go away since the
# publisher now takes care of the redirection to a bug task.
def redirectToNewBugPage(self):
"""Redirect the user to the 'first' report of this bug."""
# An example of practicality beating purity.
self.request.response.redirect(
canonical_url(self.context.default_bugtask))
class BugEditViewBase(LaunchpadEditFormView):
"""Base class for all bug edit pages."""
schema = IBug
def setUpWidgets(self):
"""Set up the widgets using the bug as the context."""
LaunchpadEditFormView.setUpWidgets(self, context=self.context.bug)
def updateBugFromData(self, data):
"""Update the bug using the values in the data dictionary."""
LaunchpadEditFormView.updateContextFromData(
self, data, context=self.context.bug)
@property
def next_url(self):
"""Return the next URL to call when this call completes."""
return canonical_url(self.context)
class BugEditView(BugEditViewBase):
"""The view for the edit bug page."""
field_names = ['title', 'description', 'tags']
custom_widget('title', TextWidget, displayWidth=30)
custom_widget('tags', BugTagsWidget)
next_url = None
_confirm_new_tags = False
def __init__(self, context, request):
"""context is always an IBugTask."""
BugEditViewBase.__init__(self, context, request)
self.notifications = []
@property
def label(self):
"""The form label."""
return 'Edit details for bug #%d' % self.context.bug.id
@property
def page_title(self):
"""The page title."""
return self.label
@property
def cancel_url(self):
"""See `LaunchpadFormView`."""
return canonical_url(self.context)
def validate(self, data):
"""Make sure new tags are confirmed."""
if 'tags' not in data:
return
confirm_action = self.confirm_tag_action
if confirm_action.submitted():
# Validation is needed only for the change action.
return
bugtarget = self.context.target
newly_defined_tags = set(data['tags']).difference(
bugtarget.getUsedBugTags() + bugtarget.official_bug_tags)
# Display the confirm button in a notification message. We want
# it to be slightly smaller than usual, so we can't simply let
# it render itself.
confirm_button = (
'<input style="font-size: smaller" type="submit"'
' value="%s" name="%s" />' % (
confirm_action.label, confirm_action.__name__))
for new_tag in newly_defined_tags:
self.notifications.append(
'The tag "%s" hasn\'t been used by %s before. %s' % (
new_tag, bugtarget.bugtargetdisplayname, confirm_button))
self._confirm_new_tags = True
@action('Change', name='change')
def edit_bug_action(self, action, data):
"""Update the bug with submitted changes."""
if not self._confirm_new_tags:
self.updateBugFromData(data)
self.next_url = canonical_url(self.context)
@action('Create the new tag', name='confirm_tag')
def confirm_tag_action(self, action, data):
"""Define a new tag."""
self.actions['field.actions.change'].success(data)
def render(self):
"""Render the page with only one submit button."""
# The confirmation button shouldn't be rendered automatically.
self.actions = [self.edit_bug_action]
return BugEditViewBase.render(self)
class BugMarkAsDuplicateView(BugEditViewBase):
"""Page for marking a bug as a duplicate."""
field_names = ['duplicateof']
label = "Mark bug report as a duplicate"
def setUpFields(self):
"""Make the readonly version of duplicateof available."""
super(BugMarkAsDuplicateView, self).setUpFields()
duplicateof_field = DuplicateBug(
__name__='duplicateof', title=_('Duplicate Of'), required=False)
self.form_fields = self.form_fields.omit('duplicateof')
self.form_fields = formlib.form.Fields(duplicateof_field)
@property
def initial_values(self):
"""See `LaunchpadFormView.`"""
return {'duplicateof': self.context.bug.duplicateof}
@action('Change', name='change')
def change_action(self, action, data):
"""Update the bug."""
data = dict(data)
# We handle duplicate changes by hand instead of leaving it to
# the usual machinery because we must use bug.markAsDuplicate().
bug = self.context.bug
bug_before_modification = Snapshot(
bug, providing=providedBy(bug))
duplicateof = data.pop('duplicateof')
bug.markAsDuplicate(duplicateof)
notify(
ObjectModifiedEvent(bug, bug_before_modification, 'duplicateof'))
# Apply other changes.
self.updateBugFromData(data)
class BugSecrecyEditView(BugEditViewBase):
"""Page for marking a bug as a private/public."""
field_names = ['private', 'security_related']
@property
def label(self):
return 'Bug #%i - Set visibility and security' % self.context.bug.id
page_title = label
def setUpFields(self):
"""Make the read-only version of the form fields writable."""
private_field = Bool(
__name__='private',
title=_("This bug report should be private"),
required=False,
description=_("Private bug reports are visible only to "
"their subscribers."),
default=False)
security_related_field = Bool(
__name__='security_related',
title=_("This bug is a security vulnerability"),
required=False, default=False)
super(BugSecrecyEditView, self).setUpFields()
self.form_fields = self.form_fields.omit('private')
self.form_fields = self.form_fields.omit('security_related')
self.form_fields = (
formlib.form.Fields(private_field) +
formlib.form.Fields(security_related_field))
@property
def initial_values(self):
"""See `LaunchpadFormView.`"""
return {'private': self.context.bug.private,
'security_related': self.context.bug.security_related}
@action('Change', name='change')
def change_action(self, action, data):
"""Update the bug."""
# We will modify data later, so take a copy now.
data = dict(data)
# We handle privacy changes by hand instead of leaving it to
# the usual machinery because we must use bug.setPrivate() to
# ensure auditing information is recorded.
bug = self.context.bug
bug_before_modification = Snapshot(
bug, providing=providedBy(bug))
private = data.pop('private')
security_related = data.pop('security_related')
private_changed = bug.setPrivate(
private, getUtility(ILaunchBag).user)
security_related_changed = bug.setSecurityRelated(security_related)
if private_changed or security_related_changed:
changed_fields = []
if private_changed:
changed_fields.append('private')
if security_related_changed:
changed_fields.append('security_related')
notify(ObjectModifiedEvent(
bug, bug_before_modification, changed_fields))
# Apply other changes.
self.updateBugFromData(data)
class DeprecatedAssignedBugsView:
"""Deprecate the /malone/assigned namespace.
It's important to ensure that this namespace continues to work, to
prevent linkrot, but since FOAF seems to be a more natural place
to put the assigned bugs report, we'll redirect to the appropriate
FOAF URL.
"""
def __init__(self, context, request):
self.context = context
self.request = request
def redirect_to_assignedbugs(self):
"""Redirect the user to their assigned bugs report."""
self.request.response.redirect(
canonical_url(getUtility(ILaunchBag).user) +
"/+assignedbugs")
normalize_mime_type = re.compile(r'\s+')
class BugTextView(LaunchpadView):
"""View for simple text page displaying information for a bug."""
@cachedproperty
def bugtasks(self):
"""Cache bugtasks and avoid hitting the DB twice."""
return list(self.context.bugtasks)
def bug_text(self):
"""Return the bug information for text display."""
bug = self.context
text = []
text.append('bug: %d' % bug.id)
text.append('title: %s' % bug.title)
text.append('date-reported: %s' %
format_rfc2822_date(bug.datecreated))
text.append('date-updated: %s' %
format_rfc2822_date(bug.date_last_updated))
text.append('reporter: %s' % bug.owner.unique_displayname)
if bug.duplicateof:
text.append('duplicate-of: %d' % bug.duplicateof.id)
else:
text.append('duplicate-of: ')
if bug.duplicates:
dupes = ' '.join(str(dupe.id) for dupe in bug.duplicates)
text.append('duplicates: %s' % dupes)
else:
text.append('duplicates: ')
if bug.private:
# XXX kiko 2007-10-31: this could include date_made_private and
# who_made_private but Bjorn doesn't let me.
text.append('private: yes')
if bug.security_related:
text.append('security: yes')
patches = []
text.append('attachments: ')
for attachment in bug.attachments_unpopulated:
if attachment.type != BugAttachmentType.PATCH:
text.append(' %s' % self.attachment_text(attachment))
else:
patches.append(attachment)
text.append('patches: ')
for attachment in patches:
text.append(' %s' % self.attachment_text(attachment))
text.append('tags: %s' % ' '.join(bug.tags))
text.append('subscribers: ')
for subscription in bug.subscriptions:
text.append(' %s' % subscription.person.unique_displayname)
return ''.join(line + '\n' for line in text)
def bugtask_text(self, task):
"""Return a BugTask for text display."""
text = []
text.append('task: %s' % task.bugtargetname)
text.append('status: %s' % task.status.title)
text.append('date-created: %s' %
format_rfc2822_date(task.datecreated))
for status in ["left_new", "confirmed", "triaged", "assigned",
"inprogress", "closed", "incomplete",
"fix_committed", "fix_released", "left_closed"]:
date = getattr(task, "date_%s" % status)
if date:
text.append("date-%s: %s" % (
status.replace('_', '-'), format_rfc2822_date(date)))
text.append('reporter: %s' % task.owner.unique_displayname)
if task.bugwatch:
text.append('watch: %s' % task.bugwatch.url)
text.append('importance: %s' % task.importance.title)
component = task.getPackageComponent()
if component:
text.append('component: %s' % component.name)
if task.assignee:
text.append('assignee: %s' % task.assignee.unique_displayname)
else:
text.append('assignee: ')
if task.milestone:
text.append('milestone: %s' % task.milestone.name)
else:
text.append('milestone: ')
return ''.join(line + '\n' for line in text)
def attachment_text(self, attachment):
"""Return a text representation of a bug attachment."""
mime_type = normalize_mime_type.sub(
' ', attachment.libraryfile.mimetype)
download_url = ProxiedLibraryFileAlias(
attachment.libraryfile, attachment).http_url
return "%s %s" % (download_url, mime_type)
def comment_text(self):
"""Return a text representation of bug comments."""
def build_message(text):
mailwrapper = MailWrapper(width=72)
text = mailwrapper.format(text)
message = MIMEText(text.encode('utf-8'),
'plain', 'utf-8')
# This is redundant and makes the template noisy
del message['MIME-Version']
return message
from lp.bugs.browser.bugtask import (
get_visible_comments, get_comments_for_bugtask)
# XXX: kiko 2007-10-31: for some reason, get_comments_for_bugtask
# takes a task, not a bug. For now live with it.
first_task = self.bugtasks[0]
all_comments = get_comments_for_bugtask(first_task)
comments = get_visible_comments(all_comments[1:])
comment_mime = MIMEMultipart()
message = build_message(self.context.description)
comment_mime.attach(message)
for comment in comments:
message = build_message(comment.text_for_display)
message['Author'] = comment.owner.unique_displayname.encode(
'utf-8')
message['Date'] = format_rfc2822_date(comment.datecreated)
message['Message-Id'] = comment.rfc822msgid
comment_mime.attach(message)
return comment_mime.as_string().decode('utf-8')
def render(self):
"""Return a text representation of the bug."""
self.request.response.setHeader('Content-type', 'text/plain')
texts = [self.bug_text()]
texts.extend(self.bugtask_text(task) for task in self.bugtasks)
texts.append(self.comment_text())
return "\n".join(texts)
class BugURL:
"""Bug URL creation rules."""
implements(ICanonicalUrlData)
inside = None
rootsite = 'bugs'
def __init__(self, context):
self.context = context
@property
def path(self):
"""Return the path component of the URL."""
return u"bugs/%d" % self.context.id
class BugAffectingUserChoice(EnumeratedType):
"""The choices for a bug affecting a user."""
YES = Item("""
Yes
This bug affects me.
""")
NO = Item("""
No
This bug doesn't affect me.
""")
class BugMarkAsAffectingUserForm(Interface):
"""Form schema for marking the bug as affecting the user."""
affects = Choice(
title=_('Does this bug affect you?'),
vocabulary=BugAffectingUserChoice)
class BugMarkAsAffectingUserView(LaunchpadFormView):
"""Page for marking a bug as affecting the user."""
schema = BugMarkAsAffectingUserForm
field_names = ['affects']
label = "Does this bug affect you?"
custom_widget('affects', LaunchpadRadioWidgetWithDescription)
@property
def initial_values(self):
"""See `LaunchpadFormView.`"""
affected = self.context.bug.isUserAffected(self.user)
if affected or affected is None:
affects = BugAffectingUserChoice.YES
else:
affects = BugAffectingUserChoice.NO
return {'affects': affects}
@action('Change', name='change')
def change_action(self, action, data):
"""Mark the bug according to the selection."""
self.context.bug.markUserAffected(
self.user, data['affects'] == BugAffectingUserChoice.YES)
self.request.response.redirect(canonical_url(self.context.bug))
|