-
Notifications
You must be signed in to change notification settings - Fork 0
/
web_ui.py
1913 lines (1713 loc) · 84.6 KB
/
web_ui.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
# -*- coding: utf-8 -*-
#
# Copyright (C) 2003-2009 Edgewall Software
# Copyright (C) 2003-2005 Jonas Borgström <jonas@edgewall.com>
# All rights reserved.
#
# This software is licensed as described in the file COPYING, which
# you should have received as part of this distribution. The terms
# are also available at http://trac.edgewall.org/wiki/TracLicense.
#
# This software consists of voluntary contributions made by many
# individuals. For the exact contribution history, see the revision
# history and logs, available at http://trac.edgewall.org/log/.
#
# Author: Jonas Borgström <jonas@edgewall.com>
import csv
from datetime import datetime
from functools import partial
import pkg_resources
import re
from StringIO import StringIO
from genshi.core import Markup
from genshi.builder import tag
from trac.attachment import AttachmentModule
from trac.config import BoolOption, Option, IntOption
from trac.core import *
from trac.mimeview.api import Mimeview, IContentConverter
from trac.notification.api import NotificationSystem
from trac.resource import (
Resource, ResourceNotFound, get_resource_url, render_resource_link,
get_resource_shortname
)
from trac.search import ISearchSource, search_to_sql, shorten_result
from trac.ticket.api import TicketSystem, ITicketManipulator
from trac.ticket.model import Milestone, Ticket
from trac.ticket.notification import TicketChangeEvent
from trac.ticket.roadmap import group_milestones
from trac.timeline.api import ITimelineEventProvider
from trac.util import as_bool, as_int, get_reporter_id, lazy
from trac.util.datefmt import (
format_date_or_datetime, from_utimestamp, get_date_format_hint,
get_datetime_format_hint, parse_date, to_utimestamp, user_time, utc
)
from trac.util.html import to_fragment
from trac.util.text import (
exception_to_unicode, empty, is_obfuscated, shorten_line
)
from trac.util.presentation import separated
from trac.util.translation import _, tag_, tagn_, N_, ngettext
from trac.versioncontrol.diff import get_diff_options, diff_blocks
from trac.web.api import IRequestHandler, arg_list_to_args, parse_arg_list
from trac.web.chrome import (
Chrome, INavigationContributor, ITemplateProvider,
add_ctxtnav, add_link, add_notice, add_script, add_script_data,
add_stylesheet, add_warning, auth_link, chrome_info_script, prevnext_nav,
web_context
)
from trac.wiki.formatter import format_to, format_to_html
class InvalidTicket(TracError):
"""Exception raised when a ticket fails validation."""
title = N_("Invalid Ticket")
class TicketModule(Component):
implements(IContentConverter, INavigationContributor, IRequestHandler,
ISearchSource, ITemplateProvider, ITimelineEventProvider)
ticket_manipulators = ExtensionPoint(ITicketManipulator)
realm = TicketSystem.realm
timeline_details = BoolOption('timeline', 'ticket_show_details', 'false',
"""Enable the display of all ticket changes in the timeline, not only
open / close operations.""")
timeline_component = BoolOption('timeline', 'ticket_show_component',
'false',
"""Enable the display of component of tickets in the timeline.
(''since 1.1.1'')""")
max_description_size = IntOption('ticket', 'max_description_size', 262144,
"""Maximum allowed description size in characters.""")
max_comment_size = IntOption('ticket', 'max_comment_size', 262144,
"""Maximum allowed comment size in characters.""")
max_summary_size = IntOption('ticket', 'max_summary_size', 262144,
"""Maximum allowed summary size in characters. (//since 1.0.2//)""")
timeline_newticket_formatter = Option('timeline', 'newticket_formatter',
'oneliner',
"""Which formatter flavor (e.g. 'html' or 'oneliner') should be
used when presenting the description for new tickets.
If 'oneliner', the [timeline] abbreviated_messages option applies.
""")
preserve_newlines = Option('ticket', 'preserve_newlines', 'default',
"""Whether Wiki formatter should respect the new lines present
in the Wiki text.
If set to 'default', this is equivalent to 'yes' for new environments
but keeps the old behavior for upgraded environments (i.e. 'no').
""")
ticketlink_query = Option('query', 'ticketlink_query',
default='?status=!closed',
doc="""The base query to be used when linkifying values of ticket
fields. The query is a URL query
string starting with `?` as used in `query:`
[TracQuery#UsingTracLinks Trac links].
(''since 0.12'')""")
ticket_path_re = re.compile(r'/ticket/([0-9]+)$')
def __init__(self):
self._warn_for_default_attr = set()
@lazy
def must_preserve_newlines(self):
preserve_newlines = self.preserve_newlines
if preserve_newlines == 'default':
preserve_newlines = self.env.database_initial_version >= 21 # 0.11
return as_bool(preserve_newlines)
# IContentConverter methods
def get_supported_conversions(self):
yield ('csv', _("Comma-delimited Text"), 'csv',
'trac.ticket.Ticket', 'text/csv', 8)
yield ('tab', _("Tab-delimited Text"), 'tsv',
'trac.ticket.Ticket', 'text/tab-separated-values', 8)
yield ('rss', _("RSS Feed"), 'xml',
'trac.ticket.Ticket', 'application/rss+xml', 8)
def convert_content(self, req, mimetype, ticket, key):
if key == 'csv':
return self.export_csv(req, ticket, mimetype='text/csv')
elif key == 'tab':
return self.export_csv(req, ticket, sep='\t',
mimetype='text/tab-separated-values')
elif key == 'rss':
return self._export_rss(req, ticket)
# INavigationContributor methods
def get_active_navigation_item(self, req):
if self.ticket_path_re.match(req.path_info):
return 'tickets'
return 'newticket'
def get_navigation_items(self, req):
if 'TICKET_CREATE' in req.perm:
yield ('mainnav', 'newticket',
tag.a(_("New Ticket"), href=req.href.newticket(),
accesskey=7))
# IRequestHandler methods
def match_request(self, req):
match = self.ticket_path_re.match(req.path_info)
if match:
req.args['id'] = match.group(1)
return True
if req.path_info == '/newticket':
return True
def process_request(self, req):
if 'id' in req.args:
if req.path_info == '/newticket':
raise TracError(_("id can't be set for a new ticket request."))
return self._process_ticket_request(req)
return self._process_newticket_request(req)
# ITemplateProvider methods
def get_htdocs_dirs(self):
return []
def get_templates_dirs(self):
return [pkg_resources.resource_filename('trac.ticket', 'templates')]
# ISearchSource methods
def get_search_filters(self, req):
if 'TICKET_VIEW' in req.perm:
yield ('ticket', _("Tickets"))
def get_search_results(self, req, terms, filters):
if 'ticket' not in filters:
return
ticket_realm = Resource(self.realm)
with self.env.db_query as db:
sql, args = search_to_sql(db, ['summary', 'keywords',
'description', 'reporter', 'cc',
db.cast('id', 'text')], terms)
sql2, args2 = search_to_sql(db, ['newvalue'], terms)
sql3, args3 = search_to_sql(db, ['value'], terms)
ticketsystem = TicketSystem(self.env)
for summary, desc, author, type, tid, ts, status, resolution in \
db("""SELECT summary, description, reporter, type, id,
time, status, resolution
FROM ticket
WHERE id IN (
SELECT id FROM ticket WHERE %s
UNION
SELECT ticket FROM ticket_change
WHERE field='comment' AND %s
UNION
SELECT ticket FROM ticket_custom WHERE %s
)
""" % (sql, sql2, sql3),
args + args2 + args3):
t = ticket_realm(id=tid)
if 'TICKET_VIEW' in req.perm(t):
yield (req.href.ticket(tid),
tag_("%(title)s: %(message)s",
title=tag.span(
get_resource_shortname(self.env, t),
class_=status),
message=ticketsystem.format_summary(
summary, status, resolution, type)),
from_utimestamp(ts), author,
shorten_result(desc, terms))
# Attachments
for result in AttachmentModule(self.env).get_search_results(
req, ticket_realm, terms):
yield result
# ITimelineEventProvider methods
def get_timeline_filters(self, req):
if 'TICKET_VIEW' in req.perm:
yield ('ticket', _("Tickets opened and closed"))
if self.timeline_details:
yield ('ticket_details', _("Ticket updates"), False)
def get_timeline_events(self, req, start, stop, filters):
ts_start = to_utimestamp(start)
ts_stop = to_utimestamp(stop)
status_map = {'new': ('newticket', 'created'),
'reopened': ('reopenedticket', 'reopened'),
'closed': ('closedticket', 'closed'),
'edit': ('editedticket', 'updated')}
ticket_realm = Resource(self.realm)
field_labels = TicketSystem(self.env).get_ticket_field_labels()
def produce_event((id, ts, author, type, summary, description,
component),
status, fields, comment, cid):
ticket = ticket_realm(id=id)
if 'TICKET_VIEW' not in req.perm(ticket):
return None
resolution = fields.get('resolution')
info = ''
if status == 'edit':
if 'ticket_details' in filters:
if len(fields) > 0:
labels = [tag.i(field_labels.get(k, k.capitalize()))
for k in fields.keys()]
info = tagn_("%(labels)s changed",
"%(labels)s changed", len(labels),
labels=separated(labels, ', ')) + tag.br()
else:
return None
elif 'ticket' in filters:
if status == 'closed' and resolution:
if resolution and comment:
info = _("%(title)s: %(message)s", title=resolution,
message='') # typographical translation (fr)
else:
info = resolution
else:
return None
kind, verb = status_map[status]
return (kind, from_utimestamp(ts), author,
(ticket, verb, info, summary, status, resolution, type,
description, component, comment, cid))
def produce_ticket_change_events(db):
data = None
for (id, t, author, type, summary,
component, field, oldvalue, newvalue) in db("""
SELECT t.id, tc.time, tc.author, t.type, t.summary,
t.component, tc.field, tc.oldvalue, tc.newvalue
FROM ticket_change tc
INNER JOIN ticket t ON t.id = tc.ticket
AND tc.time>=%s AND tc.time<=%s
ORDER BY tc.time, tc.ticket
""" % (ts_start, ts_stop)):
if not (oldvalue or newvalue):
# ignore empty change corresponding to custom field
# created (None -> '') or deleted ('' -> None)
continue
if not data or (id, t) != data[:2]:
if data:
ev = produce_event(data, status, fields, comment,
cid)
if ev:
yield (ev, data[1])
status, fields, comment, cid = 'edit', {}, '', None
data = (id, t, author, type, summary, None, component)
if field == 'comment':
comment = newvalue
cid = oldvalue and oldvalue.split('.')[-1]
# Always use the author from the comment field
data = data[:2] + (author,) + data[3:]
elif field == 'status' and \
newvalue in ('reopened', 'closed'):
status = newvalue
elif field[0] != '_':
# properties like _comment{n} are hidden
fields[field] = newvalue
if data:
ev = produce_event(data, status, fields, comment, cid)
if ev:
yield (ev, data[1])
# Ticket changes
with self.env.db_query as db:
if 'ticket' in filters or 'ticket_details' in filters:
prev_t = None
prev_ev = None
batch_ev = None
for ev, t in produce_ticket_change_events(db):
if batch_ev:
if prev_t == t:
ticket = ev[3][0]
batch_ev[3][0].append(ticket.id)
else:
yield batch_ev
prev_ev = ev
prev_t = t
batch_ev = None
elif prev_t and prev_t == t:
prev_ticket = prev_ev[3][0]
ticket = ev[3][0]
tickets = [prev_ticket.id, ticket.id]
batch_data = (tickets,) + ev[3][1:]
batch_ev = ('batchmodify', ev[1], ev[2], batch_data)
else:
if prev_ev:
yield prev_ev
prev_ev = ev
prev_t = t
if batch_ev:
yield batch_ev
elif prev_ev:
yield prev_ev
# New tickets
if 'ticket' in filters:
for row in db("""SELECT id, time, reporter, type, summary,
description, component
FROM ticket WHERE time>=%s AND time<=%s
""", (ts_start, ts_stop)):
ev = produce_event(row, 'new', {}, None, None)
if ev:
yield ev
# Attachments
if 'ticket_details' in filters:
for event in AttachmentModule(self.env).get_timeline_events(
req, ticket_realm, start, stop):
yield event
def render_timeline_event(self, context, field, event):
kind = event[0]
if kind == 'batchmodify':
return self._render_batched_timeline_event(context, field, event)
ticket, verb, info, summary, status, resolution, type, \
description, component, comment, cid = event[3]
if field == 'url':
href = context.href.ticket(ticket.id)
if cid:
href += '#comment:' + cid
return href
elif field == 'title':
title = TicketSystem(self.env).format_summary(summary, status,
resolution, type)
message = {
'created': N_("Ticket %(ticketref)s (%(summary)s) created"),
'reopened': N_("Ticket %(ticketref)s (%(summary)s) reopened"),
'closed': N_("Ticket %(ticketref)s (%(summary)s) closed"),
'updated': N_("Ticket %(ticketref)s (%(summary)s) updated"),
}[verb]
# Add component as prefix to summary if enabled and available
component_prefix = ''
if self.timeline_component and component:
component_prefix = component + ' - '
summary_complete = component_prefix + shorten_line(summary)
return tag_(message,
ticketref=tag.em('#', ticket.id, title=title),
summary=summary_complete)
elif field == 'description':
descr = message = ''
if status == 'new':
message = description
else:
descr = info
message = comment
t_context = context.child(resource=ticket)
t_context.set_hints(preserve_newlines=self.must_preserve_newlines)
if status == 'new' and \
context.get_hint('wiki_flavor') == 'oneliner':
flavor = self.timeline_newticket_formatter
t_context.set_hints(wiki_flavor=flavor,
shorten_lines=flavor == 'oneliner')
return descr + format_to(self.env, None, t_context, message)
def _render_batched_timeline_event(self, context, field, event):
tickets, verb, info, summary, status, resolution, type, \
description, component, comment, cid = event[3]
tickets = sorted(tickets)
if field == 'url':
return context.href.query(id=','.join(str(t) for t in tickets))
elif field == 'title':
ticketids = u',\u200b'.join(str(t) for t in tickets)
title = _("Tickets %(ticketids)s", ticketids=ticketids)
return tag_("Tickets %(ticketlist)s batch updated",
ticketlist=tag.em('#', ticketids, title=title))
elif field == 'description':
t_context = context()
t_context.set_hints(preserve_newlines=self.must_preserve_newlines)
return info + format_to(self.env, None, t_context, comment)
# Internal methods
def _get_action_controls(self, req, ticket):
# action_controls is an ordered list of "renders" tuples, where
# renders is a list of (action_key, label, widgets, hints)
# representing the user interface for each action
action_controls = []
sorted_actions = TicketSystem(self.env).get_available_actions(req,
ticket)
for action in sorted_actions:
first_label = None
hints = []
widgets = []
for controller in self._get_action_controllers(req, ticket,
action):
label, widget, hint = controller.render_ticket_action_control(
req, ticket, action)
if not first_label:
first_label = label
widgets.append(widget)
hints.append(hint)
action_controls.append((action, first_label, tag(widgets), hints))
# The default action is the first in the action_controls list.
selected_action = req.args.get('action')
if not selected_action and action_controls:
selected_action = action_controls[0][0]
return action_controls, selected_action
def _get_action_controllers(self, req, ticket, action):
"""Generator yielding the controllers handling the given `action`"""
for controller in TicketSystem(self.env).action_controllers:
actions = [a for w, a in
controller.get_ticket_actions(req, ticket) or []]
if action in actions:
yield controller
def _process_newticket_request(self, req):
req.perm(self.realm).require('TICKET_CREATE')
ticket = Ticket(self.env)
plain_fields = True # support for /newticket?version=0.11 GETs
field_reporter = 'reporter'
if req.method == 'POST':
plain_fields = False
field_reporter = 'field_reporter'
self._populate(req, ticket, plain_fields)
reporter_id = req.args.get(field_reporter) or \
get_reporter_id(req, 'author')
ticket['reporter'] = reporter_id
preview = 'preview' in req.args
if preview or req.method == 'POST':
actions = TicketSystem(self.env) \
.get_available_actions(req, ticket)
default_action = actions[0] if len(actions) > 0 else None
action = req.args.get('action', default_action)
valid = True
# Do any action on the ticket?
if action not in actions:
valid = False
add_warning(req, _('The action "%(name)s" is not available.',
name=action))
field_changes, problems = self.get_ticket_changes(req, ticket,
action)
if problems:
valid = False
for problem in problems:
add_warning(req, problem)
add_warning(req,
tag_("Please review your configuration, "
"probably starting with %(section)s "
"in your %(tracini)s.",
section=tag.pre('[ticket]', tag.br(),
'workflow = ...'),
tracini=tag.code('trac.ini')))
# Apply changes made by the workflow
self._apply_ticket_changes(ticket, field_changes)
valid = valid and self._validate_ticket(req, ticket)
if not preview and req.method == 'POST':
if valid:
# redirects on success
self._do_create(req, ticket, action)
# else fall through in a preview
req.args['preview'] = True
action_controls, selected_action = \
self._get_action_controls(req, ticket)
# Preview a new ticket
data = self._prepare_data(req, ticket)
data.update({
'author_id': reporter_id,
'actions': [],
'version': None,
'description_change': None,
'action_controls': action_controls,
'action': selected_action,
})
fields = self._prepare_fields(req, ticket)
data['fields'] = fields
data['fields_map'] = dict((field['name'], i)
for i, field in enumerate(fields))
if req.is_xhr:
data['preview_mode'] = True
data['chrome_info_script'] = chrome_info_script
return 'ticket_box.html', data, None
add_stylesheet(req, 'common/css/ticket.css')
add_script(req, 'common/js/folding.js')
chrome = Chrome(self.env)
chrome.add_wiki_toolbars(req)
chrome.add_auto_preview(req)
chrome.add_jquery_ui(req)
return 'ticket.html', data, None
def _process_ticket_request(self, req):
id = int(req.args.get('id'))
version = as_int(req.args.get('version'), None)
if req.is_xhr and 'preview_comment' in req.args:
context = web_context(req, self.realm, id, version)
escape_newlines = self.must_preserve_newlines
rendered = format_to_html(self.env, context,
req.args.get('edited_comment', ''),
escape_newlines=escape_newlines) + \
chrome_info_script(req)
req.send(rendered.encode('utf-8'))
req.perm(self.realm, id, version).require('TICKET_VIEW')
ticket = Ticket(self.env, id, version=version)
action = req.args.get('action', ('history' in req.args and 'history' or
'view'))
data = self._prepare_data(req, ticket)
if action in ('history', 'diff'):
field = req.args.get('field')
if field:
text_fields = [field]
else:
text_fields = [field['name'] for field in ticket.fields if
field['type'] == 'textarea']
if action == 'history':
return self._render_history(req, ticket, data, text_fields)
elif action == 'diff':
return self._render_diff(req, ticket, data, text_fields)
elif action == 'comment-history':
try:
cnum = int(req.args.get('cnum'))
except (TypeError, ValueError):
raise TracError(_("Invalid request arguments."))
return self._render_comment_history(req, ticket, data, cnum)
elif action == 'comment-diff':
try:
cnum = int(req.args.get('cnum'))
except (TypeError, ValueError):
raise TracError(_("Invalid request arguments."))
return self._render_comment_diff(req, ticket, data, cnum)
elif 'preview_comment' in req.args:
field_changes = {}
data.update({'action': None,
'reassign_owner': req.authname,
'resolve_resolution': None,
'start_time': ticket['changetime']})
elif req.method == 'POST':
if 'cancel_comment' in req.args:
req.redirect(req.href.ticket(ticket.id))
elif 'edit_comment' in req.args:
comment = req.args.get('edited_comment', '')
cnum = int(req.args['cnum_edit'])
change = ticket.get_change(cnum)
if not (req.authname and req.authname != 'anonymous'
and change and change['author'] == req.authname):
req.perm(ticket.resource).require('TICKET_EDIT_COMMENT')
ticket.modify_comment(change['date'], req.authname, comment)
req.redirect(req.href.ticket(ticket.id) + '#comment:%d' % cnum)
valid = True
# Do any action on the ticket?
actions = TicketSystem(self.env).get_available_actions(req, ticket)
if action not in actions:
valid = False
add_warning(req, _('The action "%(name)s" is not available.',
name=action))
# We have a bit of a problem. There are two sources of changes to
# the ticket: the user, and the workflow. We need to show all the
# changes that are proposed, but we need to be able to drop the
# workflow changes if the user changes the action they want to do
# from one preview to the next.
#
# the _populate() call pulls all the changes from the webpage; but
# the webpage includes both changes by the user and changes by the
# workflow... so we aren't able to differentiate them clearly.
self._populate(req, ticket) # Apply changes made by the user
field_changes, problems = self.get_ticket_changes(req, ticket,
action)
if problems:
valid = False
for problem in problems:
add_warning(req, problem)
add_warning(req,
tag_("Please review your configuration, "
"probably starting with %(section)s "
"in your %(tracini)s.",
section=tag.pre('[ticket]', tag.br(),
'workflow = ...'),
tracini=tag.code('trac.ini')))
# Apply changes made by the workflow
self._apply_ticket_changes(ticket, field_changes)
# Unconditionally run the validation so that the user gets
# information any and all problems. But it's only valid if it
# validates and there were no problems with the workflow side of
# things.
valid = self._validate_ticket(req, ticket, not valid) and valid
if 'submit' in req.args:
if valid:
# redirected if successful
self._do_save(req, ticket, action)
# else fall through in a preview
req.args['preview'] = True
# Preview an existing ticket (after a Preview or a failed Save)
start_time = from_utimestamp(long(req.args.get('start_time', 0)))
data.update({
'action': action, 'start_time': start_time,
'reassign_owner': (req.args.get('reassign_choice')
or req.authname),
'resolve_resolution': req.args.get('resolve_choice'),
})
else: # simply 'View'ing the ticket
field_changes = {}
data.update({'action': None,
'reassign_owner': req.authname,
'resolve_resolution': None,
# Store a timestamp for detecting "mid air collisions"
'start_time': ticket['changetime']})
data.update({'comment': req.args.get('comment'),
'cnum_edit': req.args.get('cnum_edit'),
'edited_comment': req.args.get('edited_comment'),
'cnum_hist': req.args.get('cnum_hist'),
'cversion': req.args.get('cversion')})
self._insert_ticket_data(req, ticket, data,
get_reporter_id(req, 'author'), field_changes)
if req.is_xhr:
data['preview_mode'] = bool(data['change_preview']['fields'])
data['chrome_info_script'] = chrome_info_script
return 'ticket_preview.html', data, None
mime = Mimeview(self.env)
format = req.args.get('format')
if format:
# FIXME: mime.send_converted(context, ticket, 'ticket_x') (#3332)
filename = 't%d' % ticket.id if format != 'rss' else None
mime.send_converted(req, 'trac.ticket.Ticket', ticket,
format, filename=filename)
def add_ticket_link(css_class, id):
t = ticket.resource(id=id, version=None)
if t:
add_link(req, css_class, req.href.ticket(id),
_("Ticket #%(id)s", id=id))
global_sequence = True
# If the ticket is being shown in the context of a query, add
# links to help navigate in the query result set
if 'query_tickets' in req.session:
tickets = req.session['query_tickets'].split()
if str(ticket.id) in tickets:
idx = tickets.index(str(ticket.id))
if idx > 0:
add_ticket_link('first', tickets[0])
add_ticket_link('prev', tickets[idx - 1])
if idx < len(tickets) - 1:
add_ticket_link('next', tickets[idx + 1])
add_ticket_link('last', tickets[-1])
add_link(req, 'up', req.session['query_href'])
global_sequence = False
if global_sequence:
with self.env.db_query as db:
for min_id, max_id in db(
"SELECT min(id), max(id) FROM ticket"):
min_id = int(min_id)
max_id = int(max_id)
if min_id < ticket.id:
add_ticket_link('first', min_id)
for prev_id, in db(
"SELECT max(id) FROM ticket WHERE id < %s",
(ticket.id,)):
add_ticket_link('prev', int(prev_id))
if ticket.id < max_id:
add_ticket_link('last', max_id)
for next_id, in db(
"SELECT min(id) FROM ticket WHERE %s < id",
(ticket.id,)):
add_ticket_link('next', int(next_id))
break
add_script_data(req, {'comments_prefs': self._get_prefs(req)})
add_stylesheet(req, 'common/css/ticket.css')
add_script(req, 'common/js/folding.js')
chrome = Chrome(self.env)
chrome.add_wiki_toolbars(req)
chrome.add_auto_preview(req)
chrome.add_jquery_ui(req)
# Add registered converters
for conversion in mime.get_supported_conversions('trac.ticket.Ticket'):
format = conversion.key
conversion_href = get_resource_url(self.env, ticket.resource,
req.href, format=format)
if format == 'rss':
conversion_href = auth_link(req, conversion_href)
add_link(req, 'alternate', conversion_href, conversion.name,
conversion.out_mimetype, format)
prevnext_nav(req, _("Previous Ticket"), _("Next Ticket"),
_("Back to Query"))
return 'ticket.html', data, None
def _get_prefs(self, req):
return {'comments_order': req.session.get('ticket_comments_order',
'oldest'),
'comments_only': req.session.get('ticket_comments_only',
'false')}
def _prepare_data(self, req, ticket, absurls=False):
return {'ticket': ticket, 'to_utimestamp': to_utimestamp,
'context': web_context(req, ticket.resource, absurls=absurls),
'preserve_newlines': self.must_preserve_newlines,
'emtpy': empty}
def _cc_list(self, cc):
return Chrome(self.env).cc_list(cc)
def _toggle_cc(self, req, cc):
"""Return an (action, recipient) tuple corresponding to a change
of CC status for this user relative to the current `cc_list`."""
entries = []
email = req.session.get('email', '').strip()
if email:
entries.append(email)
if req.authname != 'anonymous':
entries.append(req.authname)
else:
author = get_reporter_id(req, 'author').strip()
if author and author != 'anonymous':
email = author.split()[-1]
if (email[0], email[-1]) == ('<', '>'):
email = email[1:-1]
entries.append(email)
add = []
remove = []
cc_list = self._cc_list(cc)
for entry in entries:
if entry in cc_list:
remove.append(entry)
else:
add.append(entry)
action = entry = None
if remove:
action, entry = ('remove', remove[0])
elif add:
action, entry = ('add', add[0])
return action, entry, cc_list
def _populate(self, req, ticket, plain_fields=False):
if not plain_fields:
fields = dict((k[6:], v) for k, v in req.args.iteritems()
if k.startswith('field_')
and 'revert_' + k[6:] not in req.args)
# Handle revert of checkboxes (in particular, revert to 1)
for k in list(fields):
if k.startswith('checkbox_'):
k = k[9:]
if 'revert_' + k in req.args:
fields[k] = ticket[k]
else:
fields = req.args.copy()
# Prevent direct changes to protected fields (status and resolution are
# set in the workflow, in get_ticket_changes())
for each in Ticket.protected_fields:
fields.pop(each, None)
fields.pop('checkbox_' + each, None) # See Ticket.populate()
for field, value in fields.iteritems():
if field in ticket.time_fields:
try:
fields[field] = user_time(req, parse_date, value) \
if value else None
except TracError as e:
# Handle bad user input for custom time fields gracefully.
if field in ticket.custom_fields:
# Leave it to _validate_ticket() to complain.
fields[field] = value
else:
raise TracError(e)
ticket.populate(fields)
# special case for updating the Cc: field
if 'cc_update' in req.args and 'revert_cc' not in req.args:
cc_action, cc_entry, cc_list = self._toggle_cc(req, ticket['cc'])
if cc_action == 'remove':
cc_list.remove(cc_entry)
elif cc_action == 'add':
cc_list.append(cc_entry)
ticket['cc'] = ', '.join(cc_list)
def _get_history(self, req, ticket):
history = []
for change in self.rendered_changelog_entries(req, ticket):
if change['permanent']:
change['version'] = change['cnum']
history.append(change)
return history
def _render_history(self, req, ticket, data, text_fields):
"""Extract the history for a ticket description."""
req.perm(ticket.resource).require('TICKET_VIEW')
history = self._get_history(req, ticket)
history.reverse()
history = [c for c in history if any(f in text_fields
for f in c['fields'])]
history.append({'version': 0, 'comment': "''Initial version''",
'date': ticket['time'],
'author': ticket['reporter'] # not 100% accurate...
})
data.update({'title': _("Ticket History"),
'resource': ticket.resource,
'history': history})
add_ctxtnav(req, _("Back to Ticket #%(num)s", num=ticket.id),
req.href.ticket(ticket.id))
return 'history_view.html', data, None
def _render_diff(self, req, ticket, data, text_fields):
"""Show differences between two versions of a ticket description.
`text_fields` is optionally a list of fields of interest, that are
considered for jumping to the next change.
"""
new_version = int(req.args.get('version', 1))
old_version = int(req.args.get('old_version', new_version))
if old_version > new_version:
old_version, new_version = new_version, old_version
# get the list of versions having a description change
history = self._get_history(req, ticket)
changes = {}
descriptions = []
old_idx = new_idx = -1 # indexes in descriptions
for change in history:
version = change['version']
changes[version] = change
if any(f in text_fields for f in change['fields']):
if old_version and version <= old_version:
old_idx = len(descriptions)
if new_idx == -1 and new_version and version >= new_version:
new_idx = len(descriptions)
descriptions.append((version, change))
# determine precisely old and new versions
if old_version == new_version:
if new_idx >= 0:
old_idx = new_idx - 1
if old_idx >= 0:
old_version, old_change = descriptions[old_idx]
else:
old_version, old_change = 0, None
num_changes = new_idx - old_idx
if new_idx >= 0:
new_version, new_change = descriptions[new_idx]
else:
raise TracError(_("No differences to show"))
tnew = ticket.resource(version=new_version)
told = ticket.resource(version=old_version)
req.perm(tnew).require('TICKET_VIEW')
req.perm(told).require('TICKET_VIEW')
# determine prev and next versions
prev_version = old_version
next_version = None
if new_idx < len(descriptions) - 1:
next_version = descriptions[new_idx+1][0]
# -- old properties (old_ticket) and new properties (new_ticket)
# assume a linear sequence of change numbers, starting at 1, with gaps
def replay_changes(values, old_values, from_version, to_version):
for version in range(from_version, to_version+1):
if version in changes:
for k, v in changes[version]['fields'].iteritems():
values[k] = v['new']
if old_values is not None and k not in old_values:
old_values[k] = v['old']
old_ticket = {}
if old_version:
replay_changes(old_ticket, None, 1, old_version)
new_ticket = dict(old_ticket)
replay_changes(new_ticket, old_ticket, old_version+1, new_version)
field_labels = TicketSystem(self.env).get_ticket_field_labels()
changes = []
def version_info(t, field=None):
path = _("Ticket #%(id)s", id=ticket.id)
# TODO: field info should probably be part of the Resource as well
if field:
path = tag(path, Markup(' – '),
field_labels.get(field, field.capitalize()))
if t.version:
rev = _("Version %(num)s", num=t.version)
shortrev = 'v%d' % t.version
else:
rev, shortrev = _("Initial Version"), _("initial")
return {'path': path, 'rev': rev, 'shortrev': shortrev,
'href': get_resource_url(self.env, t, req.href)}
# -- prop changes
props = []
for k, v in new_ticket.iteritems():
if k not in text_fields:
old, new = old_ticket[k], new_ticket[k]
if old != new:
label = field_labels.get(k, k.capitalize())
prop = {'name': label, 'field': k,
'old': {'name': label, 'value': old},
'new': {'name': label, 'value': new}}
rendered = self._render_property_diff(req, ticket, k,
old, new, tnew)
if rendered:
prop['diff'] = tag.li(
tag_("Property %(label)s %(rendered)s",
label=tag.strong(label), rendered=rendered))
props.append(prop)
changes.append({'props': props, 'diffs': [],
'new': version_info(tnew),
'old': version_info(told)})
# -- text diffs
diff_style, diff_options, diff_data = get_diff_options(req)
diff_context = 3
for option in diff_options:
if option.startswith('-U'):