summaryrefslogtreecommitdiffstats
path: root/JTrackerIssue.py
blob: b698cc9e82025336e1f4a10aba2b1a9a31256151 (plain)
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
##############################################################################
#
# Copyright (c) 2002-2008 Jens Vagelpohl and Contributors. All Rights Reserved.
#
# This software is subject to the provisions of the Zope Public License,
# Version 2.1 (ZPL).  A copy of the ZPL should accompany this distribution.
# THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS
# FOR A PARTICULAR PURPOSE.
#
##############################################################################
""" JTrackerIssue: Support issue class for the JTracker issue tracker

$Id$
"""

# General Python imports
import os, string, random

# Zope imports
from Acquisition import aq_base
from Acquisition import aq_inner
from Acquisition import aq_parent
from AccessControl.Permissions import access_contents_information
from AccessControl.Permissions import view
from OFS.SimpleItem import SimpleItem
from OFS.Image import File
from OFS.PropertyManager import PropertyManager
from BTrees.OOBTree import OOBTree
from DateTime import DateTime
from AccessControl import ClassSecurityInfo
from Globals import InitializeClass
from Globals import package_home
from Globals import PersistentMapping
from Products.PageTemplates.PageTemplateFile import PageTemplateFile
from AccessControl.SecurityManagement import getSecurityManager
from zExceptions import Unauthorized

# JTracker package imports
from Permissions import ManageJTracker
from Permissions import SubmitJTrackerIssues
from Permissions import SupportJTrackerIssues

_wwwdir = os.path.join(package_home(globals()), 'www')
addJTrackerIssueForm = PageTemplateFile('addJTrackerIssue.pt', _wwwdir)


def _generateIssueId(container):
    """ Generate an ID for JTracker issues """
    if hasattr(container, '_count'):
        # This is a BTreeFolder
        ob_count = container._count()
    else:
        # Dealing with a normal folder
        ob_count = len(container._objects)

    if ob_count == 0:
        return 'issue_00001'

    # Starting point is the highest ID possible given the
    # number of objects in the JTracker
    good_id = None
    found_ob = None

    while good_id is None:
        try_id = 'issue_%s' % string.zfill(str(ob_count), 5)

        if ( container._getOb(try_id, None) is None and
             container._getOb('issue_%i' % ob_count, None) is None ):

            if found_ob is not None:
                # First non-used ID after hitting an object, this is the one
                good_id = try_id
            else:
                if try_id == 'issue_00001':
                    # Need to special-case the first ID
                    good_id = try_id
                else:
                    # Go down
                    ob_count -= 1
        else:
            # Go up
            found_ob = 1
            ob_count += 1

    return good_id

def _encodeSecret():
    """ Generate a secret token """
    token = ''
    pool = '%s%s%s' % ( string.uppercase[:26]
                      , string.digits
                      , string.lowercase[:26]
                      )

    for i in range(5):
        token = '%s%s' % (token, random.choice(pool))

    return token


class JTrackerIssue(PropertyManager, SimpleItem):
    """ A supprt issue """
    security = ClassSecurityInfo()
    meta_type = 'JTracker Issue'
    _views = { 'index_html' :   { 'view_label' : 'Default View'
                                , 'view_id'    : 'index_html'
                                }
             , 'addReplyForm' : { 'view_label' : 'Add Reply Form'
                                , 'view_id'    : 'addReplyForm'
                                }
             }

    _properties = ( { 'id'   : 'title'
                    , 'type' : 'string'
                    , 'mode' : 'w'
                    }
                  , { 'id'   : 'description'
                    , 'type' : 'text'
                    , 'mode' : 'w'
                    }
                  , { 'id'   : 'component'
                    , 'type' : 'string'
                    , 'mode' : 'w'
                    }
                  , { 'id'   : 'request_type'
                    , 'type' : 'string'
                    , 'mode' : 'w'
                    }
                  , { 'id'   : 'requester_name'
                    , 'type' : 'string'
                    , 'mode' : 'w'
                    }
                  , { 'id'   : 'requester_email'
                    , 'type' : 'string'
                    , 'mode' : 'w'
                    }
                  , { 'id'   : 'request_date'
                    , 'type' : 'date'
                    , 'mode' : 'r'
                    }
                  , { 'id'   : 'stage'
                    , 'type' : 'string'
                    , 'mode' : 'w'
                    }
                  , { 'id'   : 'supporter'
                    , 'type' : 'string'
                    , 'mode' : 'w'
                    }
                  , { 'id'   : 'subscribers'
                    , 'type' : 'lines'
                    , 'mode' : 'w'
                    }
                  )

    security.declareProtected(ManageJTracker, 'manage_replies')
    manage_replies = PageTemplateFile('editJTrackerIssueReplies.pt', _wwwdir)

    index_html = PageTemplateFile('viewJTrackerIssue.pt', _wwwdir)

    security.declareProtected(SubmitJTrackerIssues, 'addReplyForm')
    addReplyForm = PageTemplateFile('addJTrackerIssueReplyForm.pt', _wwwdir)

    manage_main = PropertyManager.manage_propertiesForm
    manage_main._setName('manage_main')

    manage_options = ( PropertyManager.manage_options
                     + ( {'label' : 'Replies', 'action' : 'manage_replies'}
                       , {'label' : 'View', 'action' : ''}
                       )
                     + SimpleItem.manage_options
                     )


    def __init__( self
                , id
                , title=''
                , description=''
                , component=''
                , request_type=''
                , requester_name=''
                , requester_email=''
                , subscribers=()
                ):
        """ Instantiate a new JTrackerIssue object """
        self.id = id
        self.title = title
        self._replies = OOBTree()
        self._files = OOBTree()
        self.description = description
        self.component = component
        self.request_type = request_type
        self.requester_email = requester_email
        self.request_date = DateTime()
        self.stage = 'Pending'
        self.supporter = ''
        self.subscribers = list(subscribers)
        self._secret = _encodeSecret()
        
        user = getSecurityManager().getUser()
        anon_user = 'Anonymous User'
        if ( ( user.getUserName() == anon_user and
               requester_name == anon_user ) or
             not requester_name ):
            self.requester_name = 'Anonymous'
        else:
            self.requester_name = requester_name


    security.declarePrivate('indexObject')
    def indexObject(self):
        """ Handle indexing 
        
        Indexing only happens if the object is not private
        """
        if self.stage != 'Private':
            cat = getattr(self, 'catalog')
            url = '/'.join(self.getPhysicalPath())
            cat.catalog_object(self, url)


    security.declarePrivate('unindexObject')
    def unindexObject(self):
        """ Handle unindexing """
        cat = getattr(self, 'catalog')
        url = '/'.join(self.getPhysicalPath())
        cat.uncatalog_object(url)


    security.declareProtected(SubmitJTrackerIssues, 'manage_afterAdd')
    def manage_afterAdd(self, item, container):
        """ What to do after an issue has been added """
        jt = self.getTracker()
        jt_email = jt.getProperty('admin_email')
        jt_name = jt.getProperty('admin_name')
        
        if jt_email:
            jtadmin_email = '"%s" <%s>' % (jt_name, jt_email)
            subscribers = list(self.getProperty('subscribers', []))

            if jtadmin_email not in subscribers:
                subscribers.append(jtadmin_email)
                self._updateProperty('subscribers', filter(None, subscribers))

        # If a review policy is in place, set our stage to 'private'
        # This affects the cataloging below. We're also applying
        # strict access controls to prevent public viewing.
        if ( jt.getProperty('review_issues') is True and
             self.getProperty('requester_email', '') != jt_email ):
            self.stage = 'Private'

            for p in (view, access_contents_information):
                roles = list(self.rolesOfPermission(p))

                if 'Anonymous' in roles:
                    roles.remove('Anonymous')
                if 'Manager' not in roles:
                    roles.append('Manager')
                if 'JTracker Supporter' not in roles:
                    roles.append('JTracker Supporter')
                
                self.manage_permission(p, roles, acquire=0)
        else:
            self.stage = 'Pending'

        self.indexObject()


    security.declareProtected(ManageJTracker, 'manage_beforeDelete')
    def manage_beforeDelete(self, item, container):
        """ Cleanup before an issue gets deleted """
        self.unindexObject()


    security.declarePublic('SearchableText')
    def SearchableText(self):
        """ Catalog text search helper """
        s_text = '%s %s' % (self.title, self.description)

        for reply in self.getReplies(force_hide_invisible=True):
            s_text = '%s %s' % (s_text, reply.get('description', ''))

        return s_text


    security.declarePublic('getTracker')
    def getTracker(self):
        """ return the tracker this issue is situated in """
        return aq_parent(aq_inner(self))


    security.declarePublic('date')
    def date(self):
        """ Catalog helper to return request date representation """
        return self.request_date.Date()


    security.declareProtected(ManageJTracker, 'manage_editProperties')
    def manage_editProperties(self, REQUEST):
        """ Overridden to make sure recataloging is done and permissions
        are reset if needed
        """
        new_stage = REQUEST.get('stage', '')

        if new_stage and new_stage != self.stage and self.stage == 'Private':
            # This item is being "unrestricted" after it has been reviewed
            for p in (view, access_contents_information):
                self.manage_permission(p, [], acquire=1)       
        
        for prop in self._propertyMap():
            name=prop['id']
            if 'w' in prop.get('mode', 'wd'):
                value=REQUEST.get(name, '')
                self._updateProperty(name, value)

        self.indexObject()

        msg = 'Saved changes.'
        return self.manage_propertiesForm(manage_tabs_message=msg)


    security.declarePrivate('_generateReplyId')
    def _generateReplyId(self):
        """ Generate a suitable reply_id """
        num_replies = self.followups()

        return 'entry_%i' % (num_replies + 1)


    security.declarePrivate('_storeFile')
    def _storeFile(self, reply_id, file, respect_limit=1):
        """ Store a file """
        if respect_limit:
            tracker = self.getTracker()
            filesize_limit = int(tracker.getProperty('filesize_limit'))

            if filesize_limit == 0:
                del file
                return None

            file.seek(0,2)
            kb_size = file.tell()/1024

            if kb_size > filesize_limit:
                del file
                return None
        
        fn = file.filename
        if fn.find('\\') != -1: # Windoze browsers are dumb, they send full paths
            path_comps = fn.split('\\')
            fn = path_comps[-1]

        file_ob = File(fn, fn, file)

        self._files[fn] = { 'reply_id' : reply_id
                          , 'file_id'  : fn
                          , 'file'     : file_ob
                          }

        return fn


    security.declareProtected(SubmitJTrackerIssues, 'getFile')
    def getFile(self, file_id):
        """ Return file in the right context """
        file_info = self._files.get(file_id, None)

        if file_info is not None:
            file = file_info['file'].__of__(self)
        else:
            file = None

        return file


    security.declareProtected(SubmitJTrackerIssues, 'addReply')
    def addReply( self
                , reply_type=''
                , description=''
                , requester_name=''
                , requester_email=''
                , file=None
                , send_email=1
                , request_date=None
                , unrestricted=0
                , REQUEST=None
                ):
        """ Add a followup/reply to a JTracker issue """
        jt = self.getTracker()
        admin_email = jt.getProperty('admin_email')
        restrictive_policy = ( jt.getProperty('review_issues') is True and
                               requester_email != admin_email )
        error = ''
        missing_input = []

        if jt._test_for_spam('', requester_email, description):
            raise Unauthorized

        if request_date is None:
            request_date = DateTime()

        for key, val in { reply_type : 'Reply Type'
                        , description : 'Reply body'
                        , requester_email : 'Email address'
                        }.items():
            if not key:
                missing_input.append(val)

        user = getSecurityManager().getUser()
        anon_user = 'Anonymous User'
        if ( ( user.getUserName() == anon_user and
               requester_name == anon_user ) or
             not requester_name ):
            requester_name = 'Anonymous'

        if missing_input:
            error = 'Missing input: %s' % ', '.join(missing_input)

        if requester_email.find('@') == -1 or requester_email.find('.') == -1:
            error = 'Invalid email address'

        if unrestricted == 0 and reply_type not in self.getReplyTypes():
            error = 'You are not authorized to %s this issue' % reply_type

        reply_id = self._generateReplyId()

        if file is not None and getattr(file, 'filename', '') != '':
            upload_result = self._storeFile(reply_id, file)

            if upload_result is None:
                limit = int(jt.getProperty('filesize_limit'))
                error = 'File size too large, limit is %i KB' % limit
        else:
            upload_result = None

        if error:
            if REQUEST is not None:
                form = self.__bobo_traverse__(REQUEST, 'addReplyForm')
                return form(error_msg=error)
            else:
                raise ValueError, error

        new_reply = { 'reply_id' : reply_id
                    , 'reply_type' : reply_type
                    , 'description' : description
                    , 'requester_name' : requester_name
                    , 'requester_email' : requester_email
                    , 'reply_date' : request_date
                    , 'file_name' : upload_result
                    , 'visible' : not restrictive_policy
                    }
        self._replies[reply_id] = new_reply

        if reply_type == 'Accept':
            self.stage = 'Accepted'
        elif reply_type == 'Resolve':
            self.stage = 'Resolved'
        elif reply_type == 'Reject':
            self.stage = 'Rejected'
        elif reply_type == 'Defer':
            self.stage = 'Deferred'

        if not self._is_subscribed(requester_email) and not restrictive_policy:
            req_addr = '"%s" <%s>' % (requester_name, requester_email)
            subscribers = list(self.getProperty('subscribers', []))
            subscribers.append(req_addr)
            self._updateProperty('subscribers', filter(None, subscribers))

        if restrictive_policy is False:
            # Only index a followup if we don't care about reviewing it
            self.indexObject()

        if send_email:
            jt_url = jt.absolute_url()
            
            if restrictive_policy:
                mt_name = 'restricted_reply_template'
            else:
                mt_name = 'reply_template'

            mailtemplate = jt.getMailtemplateByName(mt_name)

            msg = mailtemplate % { 'requester_name' : requester_name
                                 , 'requester_email' : requester_email
                                 , 'component' : self.component
                                 , 'request_type' : jt.translate(reply_type)
                                 , 'request_url' : self.absolute_url()
                                 , 'title' : self.title
                                 , 'description' : description
                                 , 'jtracker_title' : jt.title
                                 , 'jtracker_url' : jt_url
                                 }
            subject = '%s %s: "%s" (%s)' % ( self.component
                                           , jt.translate('followup')
                                           , self.title
                                           , self.getId()
                                           )


            if restrictive_policy:
                adm_tmp = jt.getMailtemplateByName('reply_adminlinks')
                adm_links = adm_tmp % { 'request_url' : self.absolute_url()
                                      , 'reply_id' : reply_id
                                      }
                subscribers = ( '"%s" <%s>' % (requester_name, requester_email)
                              , '"%s" <%s>' % (jt.admin_name, jt.admin_email)
                              )  
            else:
                adm_links = ''
                subscribers = filter(None, self.getProperty('subscribers') or ())

            for subscriber in subscribers:
                if subscriber.find(jt.getProperty('admin_email')) != -1:
                    jt.sendMail(subscriber, subject, msg + adm_links)
                else:
                    jt.sendMail(subscriber, subject, msg)

        if REQUEST is not None:
            if restrictive_policy:
                qs = 'err_msg=Your post will become visible after review.'
                goto = '%s?%s' % (self.absolute_url(), qs)
            else:
                goto = self.absolute_url()

            REQUEST.RESPONSE.redirect(goto)


    security.declareProtected(ManageJTracker, 'deleteReply')
    def deleteReply(self, reply_id, REQUEST=None):
        """ Remove a reply entirely """
        if reply_id in self._replies.keys():
            reply = self._replies[reply_id]
            file_name = reply.get('file_name', '')

            if file_name and file_name in self._files.keys():
                del self._files[file_name]
                
            del self._replies[reply_id]

            msg = 'Reply "%s" deleted.' % reply_id
        else:
            msg = 'No such reply "%s".' % reply_id

        self.indexObject()

        if REQUEST is not None:
            return self.manage_replies(manage_tabs_message=msg)


    security.declareProtected(ManageJTracker, 'deleteFile')
    def deleteFile(self, reply_id, REQUEST=None):
        """ Remove a file that is attached to an entry """
        if reply_id in self._replies.keys():
            reply = self._replies[reply_id]
            file_name = reply.get('file_name', '')

            if file_name and file_name in self._files.keys():
                reply['file_name'] = ''
                self._replies[reply_id] = reply
                del self._files[file_name]

            msg = 'File attachment on reply "%s" deleted.' % reply_id
        else:
            msg = 'No such reply "%s".' % reply_id

        if REQUEST is not None:
            return self.manage_replies(manage_tabs_message=msg)


    security.declareProtected(ManageJTracker, 'addFile')
    def addFile(self, reply_id, file, REQUEST=None):
        """ Add a file to an entry """
        if reply_id in self._replies.keys():
            reply = self._replies[reply_id]
            file_name = reply.get('file_name', '')

            if file_name:
                msg = 'Reply "%s" already has a file. Delete it first.' % reply_id
            else:
                file_id = self._storeFile(reply_id, file, respect_limit=0)
                reply['file_name'] = file_id
                self._replies[reply_id] = reply

                msg = 'Added file to reply "%s"' % reply_id

        if REQUEST is not None:
            return self.manage_replies(manage_tabs_message=msg)


    security.declareProtected(ManageJTracker, 'editReply')
    def editReply(self, reply_id, description, REQUEST=None):
        """ Edit a reply """
        if reply_id in self._replies.keys():
            reply = self._replies.get(reply_id)
            reply['description'] = description
            self._replies[reply_id] = reply

            msg = 'Reply "%s" edited.' % reply_id
        else:
            msg = 'No such reply "%s".' % reply_id

        self.indexObject()

        if REQUEST is not None:
            return self.manage_replies(manage_tabs_message=msg)


    security.declareProtected(ManageJTracker, 'unrestrictReply')
    def unrestrictReply(self, reply_id, REQUEST=None):
        """ Make a reply visible
        """
        if reply_id in self._replies.keys():
            jt = self.getTracker()
            reply = self._replies.get(reply_id)
            reply['visible'] = 1
            self._replies[reply_id] = reply

            requester = '"%s" <%s>' % ( reply['requester_name']
                                      , reply['requester_email']
                                      )
            subscribers = list(self.getProperty('subscribers'))
            if requester not in subscribers:
                subscribers.append(requester)
                self._updateProperty('subscribers', filter(None, subscribers))

            mailtemplate = jt.getMailtemplateByName('reply_template')
            reply_type = jt.translate(reply['reply_type'])

            msg = mailtemplate % { 'requester_name' : reply['requester_name']
                                 , 'requester_email' : reply['requester_email']
                                 , 'component' : self.component
                                 , 'request_type' : reply_type
                                 , 'request_url' : self.absolute_url()
                                 , 'title' : self.title
                                 , 'description' : reply['description']
                                 , 'jtracker_title' : jt.title
                                 , 'jtracker_url' : jt.absolute_url()
                                 }
            subject = '%s %s: "%s" (%s)' % ( self.component
                                           , jt.translate('followup')
                                           , self.title
                                           , self.getId()
                                           )

            for subscriber in subscribers:
                if ( subscriber.find(jt.getProperty('admin_email')) == -1 and
                     subscriber.find(reply['requester_email']) == -1 ):
                    jt.sendMail(subscriber, subject, msg)

            msg = 'Reply "%s" unrestricted.' % reply_id
        else:
            msg = 'No such reply "%s".' % reply_id

        self.indexObject()

        if REQUEST is not None:
            return self.manage_replies(manage_tabs_message=msg)


    security.declareProtected(SubmitJTrackerIssues, 'getReplyTypes')
    def getReplyTypes(self, unrestricted=0):
        """ Return the possible types of reply depending on permission """
        reply_types = ['Comment']
        privileged_reply_types = ['Accept', 'Resolve', 'Reject', 'Defer']

        if unrestricted == 0:
            user = getSecurityManager().getUser()

            if not self._replies and user.has_permission(SubmitJTrackerIssues, self):
                reply_types.append('Initial Request')

            if user.has_permission(SupportJTrackerIssues, self):
                reply_types.extend(privileged_reply_types)

        else:
            reply_types.extend(privileged_reply_types)

        return tuple(reply_types)


    security.declarePublic('getReplies')
    def getReplies(self, force_hide_invisible=False):
        """ Return the replies 
        
        If we have a strict review policy and the current user does not
        have the supporter permission then we hide invisibles.
        """
        replies = []
        reply_ids = list(self._replies.keys())
        reply_numbers = [int(x.split('_')[1]) for x in reply_ids]
        reply_numbers.sort()
        reply_numbers.reverse()

        for number in reply_numbers:
            replies.append(self._replies.get('entry_%i' % number))

        jt = self.getTracker()
        if ( jt.getProperty('review_issues') is True and
             not force_hide_invisible ):
            user = getSecurityManager().getUser()

            if not user.has_permission(SupportJTrackerIssues, self):
                replies = [x for x in replies if x.get('visible', True)]

        return tuple(replies)


    security.declarePublic('getReply')
    def getReply(self, reply_id):
        """ return a reply by its ID 
        
        If we have a strict review policy and the current user does not
        have the supporter permission then we hide invisibles.
        """
        reply = self._replies.get(reply_id, None)

        if not reply:
            return None
        
        jt = self.getTracker()

        if ( jt.getProperty('review_issues') is True and 
             reply.get('visible', True) ):
            return reply


    security.declarePublic('manage_subscribe')
    def manage_subscribe(self, email='', REQUEST=None):
        """ Subscribe to this issue """
        if not email or email.find('@') == -1 or email.find('.') == -1:
            msg = 'Invalid email address'
        else:
            email = email.strip()

            if not self._is_subscribed(email):
                subscribers = list(self.getProperty('subscribers', []))
                subscribers.append(email)
                self._updateProperty('subscribers', filter(None, subscribers))
                msg = 'Added subscriber %s' % email
            else:
                msg = '%s is already subscribed' % email

        if REQUEST is not None:
            ret_url = '%s?error_msg=%s' % (self.absolute_url(), msg)
            REQUEST.RESPONSE.redirect(ret_url)


    security.declarePublic('followups')
    def followups(self):
        """ How many followups have been posted? """
        return len(self._replies)


    def _is_subscribed(self, email):
        """ Check to see if the given email address is already subscribed """
        already_subscribed = 0
        subscribers = self.getProperty('subscribers', [])

        for subscriber in subscribers:
            if subscriber.find(email) != -1:
                already_subscribed = 1
                break

        return already_subscribed


    def __bobo_traverse__(self, REQUEST, name):
        """traverse trickery"""
        if name in self._views.keys():
            view_data = self._views.get(name)
            default_view = getattr(self, view_data.get('view_id'))
            vm = getattr(self, 'views_manager', None)

            if vm is None:
                return default_view

            view_ob = vm.getViewObject(self, view_data.get('view_label'))

            if view_ob is None:
                return default_view
            else:
                return view_ob

        try:
            return getattr(self, name)
        except AttributeError:
            pass

        if name in self._files.keys():
            file_ob = self._files.get(name)['file']
            return file_ob.__of__(self)

        method=REQUEST.get('REQUEST_METHOD', 'GET')
        if not method in ('GET', 'POST'):
            return NullResource(self, name, REQUEST).__of__(self)

        REQUEST.RESPONSE.notFoundError(name)


    security.declareProtected(SupportJTrackerIssues, 'tracker_deleteReply')
    def tracker_deleteReply(self, REQUEST):
        """ Helper for admin links in emails
        """
        self.deleteReply(REQUEST.get('reply_id', ''))

        qs = 'err_msg=Reply deleted.'
        REQUEST.RESPONSE.redirect('%s?%s' % (self.absolute_url(), qs))

    security.declareProtected(SupportJTrackerIssues, 'tracker_unrestrictReply')
    def tracker_unrestrictReply(self, REQUEST):
        """ Helper for admin links in emails
        """
        self.unrestrictReply(REQUEST.get('reply_id', ''))

        qs = 'err_msg=Reply now visible.'
        REQUEST.RESPONSE.redirect('%s?%s' % (self.absolute_url(), qs))

def manage_addJTrackerIssue( self
                           , title=''
                           , description=''
                           , component=''
                           , request_type=''
                           , requester_name=''
                           , requester_email=''
                           , file=None
                           , subscribers=()
                           , REQUEST=None
                           ):
    """ Add a new issue """
    id = _generateIssueId(self.this())
    jti = JTrackerIssue( id
                       , title
                       , description
                       , component
                       , request_type
                       , requester_name
                       , requester_email
                       , subscribers
                       )
    self._setObject(id, jti)

    jti = getattr(self, id)
    jti.addReply( reply_type='Initial Request'
                , description=description
                , requester_name=requester_name
                , requester_email=requester_email
                , file=file
                , send_email=0
                , REQUEST=REQUEST
                )

    if REQUEST is not None:
        ret_url = '%s/manage_main' % REQUEST['URL1']
        msg = 'Issue+Added'
        REQUEST.RESPONSE.redirect('%s?manage_tabs_message=%s' % (ret_url, msg))
    else:
        return id


InitializeClass(JTrackerIssue)