Code

7205a2fcfd5a275952848d42d87c34743ded61a3
[roundup.git] / doc / customizing.txt
1 ===================
2 Customising Roundup
3 ===================
5 :Version: $Revision: 1.117 $
7 .. This document borrows from the ZopeBook section on ZPT. The original is at:
8    http://www.zope.org/Documentation/Books/ZopeBook/current/ZPT.stx
10 .. contents::
11    :depth: 1
13 What You Can Do
14 ===============
16 Before you get too far, it's probably worth having a quick read of the Roundup
17 `design documentation`_.
19 Customisation of Roundup can take one of six forms:
21 1. `tracker configuration`_ file changes
22 2. database, or `tracker schema`_ changes
23 3. "definition" class `database content`_ changes
24 4. behavioural changes, through detectors_
25 5. `security / access controls`_
26 6. change the `web interface`_
28 The third case is special because it takes two distinctly different forms
29 depending upon whether the tracker has been initialised or not. The other two
30 may be done at any time, before or after tracker initialisation. Yes, this
31 includes adding or removing properties from classes.
34 Trackers in a Nutshell
35 ======================
37 Trackers have the following structure:
39 =================== ========================================================
40 Tracker File        Description
41 =================== ========================================================
42 config.py           Holds the basic `tracker configuration`_                 
43 dbinit.py           Holds the `tracker schema`_                              
44 interfaces.py       Defines the Web and E-Mail interfaces for the tracker    
45 select_db.py        Selects the database back-end for the tracker            
46 db/                 Holds the tracker's database                             
47 db/files/           Holds the tracker's upload files and messages            
48 detectors/          Auditors and reactors for this tracker                   
49 html/               Web interface templates, images and style sheets         
50 =================== ======================================================== 
52 Tracker Configuration
53 =====================
55 The ``config.py`` located in your tracker home contains the basic
56 configuration for the web and e-mail components of roundup's interfaces.
57 As the name suggests, this file is a Python module. This means that any
58 valid python expression may be used in the file. Mostly though, you'll
59 be setting the configuration variables to string values. Python string
60 values must be quoted with either single or double quotes::
62    'this is a string'
63    "this is also a string - use it when the value has 'single quotes'"
64    this is not a string - it's not quoted
66 Python strings may use formatting that's almost identical to C string
67 formatting. The ``%`` operator is used to perform the formatting, like
68 so::
70     'roundup-admin@%s'%MAIL_DOMAIN
72 this will create a string ``'roundup-admin@tracker.domain.example'`` if
73 MAIL_DOMAIN is set to ``'tracker.domain.example'``.
75 You'll also note some values are set to::
77    os.path.join(TRACKER_HOME, 'db')
79 or similar. This creates a new string which holds the path to the
80 ``'db'`` directory in the TRACKER_HOME directory. This is just a
81 convenience so if the TRACKER_HOME changes you don't have to edit
82 multiple valoues.
84 The configuration variables available are:
86 **TRACKER_HOME** - ``os.path.split(__file__)[0]``
87  The tracker home directory. The above default code will automatically
88  determine the tracker home for you, so you can just leave it alone.
90 **MAILHOST** - ``'localhost'``
91  The SMTP mail host that roundup will use to send e-mail.
93 **MAILUSER** - ``()``
94  If your SMTP mail host requires a username and password for access, then
95  specify them here. eg. ``MAILUSER = ('username', 'password')``
97 **MAILHOST_TLS** - ``'no'``
98  If your SMTP mail host provides or requires TLS (Transport Layer
99  Security) then set ``MAILHOST_TLS = 'yes'``
101 **MAILHOST_TLS_KEYFILE** - ``''``
102  If you're using TLS, you may also set MAILHOST_TLS_KEYFILE to the name of
103  a PEM formatted file that contains your private key.
105 **MAILHOST_TLS_CERTFILE** - ``''``
106  If you're using TLS and have specified a MAILHOST_TLS_KEYFILE, you may
107  also set MAILHOST_TLS_CERTFILE to the name of a PEM formatted certificate
108  chain file.
110 **MAIL_DOMAIN** - ``'tracker.domain.example'``
111  The domain name used for email addresses.
113 **DATABASE** - ``os.path.join(TRACKER_HOME, 'db')``
114  This is the directory that the database is going to be stored in. By default
115  it is in the tracker home.
117 **TEMPLATES** - ``os.path.join(TRACKER_HOME, 'html')``
118  This is the directory that the HTML templates reside in. By default they are
119  in the tracker home.
121 **TRACKER_NAME** - ``'Roundup issue tracker'``
122  A descriptive name for your roundup tracker. This is sent out in e-mails and
123  appears in the heading of CGI pages.
125 **TRACKER_EMAIL** - ``'issue_tracker@%s'%MAIL_DOMAIN``
126  The email address that e-mail sent to roundup should go to. Think of it as the
127  tracker's personal e-mail address.
129 **TRACKER_WEB** - ``'http://tracker.example/cgi-bin/roundup.cgi/bugs/'``
130  The web address that the tracker is viewable at. This will be included in
131  information sent to users of the tracker. The URL **must** include the
132  cgi-bin part or anything else that is required to get to the home page of
133  the tracker. You **must** include a trailing '/' in the URL.
135 **ADMIN_EMAIL** - ``'roundup-admin@%s'%MAIL_DOMAIN``
136  The email address that roundup will complain to if it runs into trouble.
138 **EMAIL_FROM_TAG** - ``''``
139  Additional text to include in the "name" part of the ``From:`` address used
140  in nosy messages. If the sending user is "Foo Bar", the ``From:`` line is
141  usually::
143     "Foo Bar" <issue_tracker@tracker.example>
145  The EMAIL_FROM_TAG goes inside the "Foo Bar" quotes like so::
147     "Foo Bar EMAIL_FROM_TAG" <issue_tracker@tracker.example>
149 **MESSAGES_TO_AUTHOR** - ``'new'``, ``'yes'`` or``'no'``
150  Send nosy messages to the author of the message?
151  If 'new' is used, then the author will only be sent the message when the
152  message creates a new issue. If 'yes' then the author will always be sent
153  a copy of the message they wrote.
155 **ADD_AUTHOR_TO_NOSY** - ``'new'``, ``'yes'`` or ``'no'``
156  Does the author of a message get placed on the nosy list automatically?
157  If ``'new'`` is used, then the author will only be added when a message
158  creates a new issue. If ``'yes'``, then the author will be added on followups
159  too. If ``'no'``, they're never added to the nosy.
161 **ADD_RECIPIENTS_TO_NOSY** - ``'new'``, ``'yes'`` or ``'no'``
162  Do the recipients (To:, Cc:) of a message get placed on the nosy list?
163  If ``'new'`` is used, then the recipients will only be added when a message
164  creates a new issue. If ``'yes'``, then the recipients will be added on
165  followups too. If ``'no'``, they're never added to the nosy.
167 **EMAIL_SIGNATURE_POSITION** - ``'top'``, ``'bottom'`` or ``'none'``
168  Where to place the email signature in messages that Roundup generates.
170 **EMAIL_KEEP_QUOTED_TEXT** - ``'yes'`` or ``'no'``
171  Keep email citations. Citations are the part of e-mail which the sender has
172  quoted in their reply to previous e-mail with ``>`` or ``|`` characters at
173  the start of the line.
175 **EMAIL_LEAVE_BODY_UNCHANGED** - ``'no'``
176  Preserve the email body as is. Enabiling this will cause the entire message
177  body to be stored, including all citations, signatures and Outlook-quoted
178  sections (ie. "Original Message" blocks). It should be either ``'yes'``
179  or ``'no'``.
181 **MAIL_DEFAULT_CLASS** - ``'issue'`` or ``''``
182  Default class to use in the mailgw if one isn't supplied in email
183  subjects. To disable, comment out the variable below or leave it blank.
185 **HTML_VERSION** -  ``'html4'`` or ``'xhtml'``
186  HTML version to generate. The templates are html4 by default. If you
187  wish to make them xhtml, then you'll need to change this var to 'xhtml'
188  too so all auto-generated HTML is compliant.
190 **EMAIL_CHARSET** - ``utf-8`` (or ``iso-8859-1`` for Eudora users)
191  Character set to encode email headers with. We use utf-8 by default, as
192  it's the most flexible. Some mail readers (eg. Eudora) can't cope with
193  that, so you might need to specify a more limited character set (eg.
194  'iso-8859-1'.
196 The default config.py is given below - as you
197 can see, the MAIL_DOMAIN must be edited before any interaction with the
198 tracker is attempted.::
200     # roundup home is this package's directory
201     TRACKER_HOME=os.path.split(__file__)[0]
203     # The SMTP mail host that roundup will use to send mail
204     MAILHOST = 'localhost'
206     # The domain name used for email addresses.
207     MAIL_DOMAIN = 'your.tracker.email.domain.example'
209     # This is the directory that the database is going to be stored in
210     DATABASE = os.path.join(TRACKER_HOME, 'db')
212     # This is the directory that the HTML templates reside in
213     TEMPLATES = os.path.join(TRACKER_HOME, 'html')
215     # A descriptive name for your roundup tracker
216     TRACKER_NAME = 'Roundup issue tracker'
218     # The email address that mail to roundup should go to
219     TRACKER_EMAIL = 'issue_tracker@%s'%MAIL_DOMAIN
221     # The web address that the tracker is viewable at. This will be
222     # included in information sent to users of the tracker. The URL MUST
223     # include the cgi-bin part or anything else that is required to get
224     # to the home page of the tracker. You MUST include a trailing '/'
225     # in the URL.
226     TRACKER_WEB = 'http://tracker.example/cgi-bin/roundup.cgi/bugs/'
228     # The email address that roundup will complain to if it runs into
229     # trouble
230     ADMIN_EMAIL = 'roundup-admin@%s'%MAIL_DOMAIN
232     # Additional text to include in the "name" part of the From: address
233     # used in nosy messages. If the sending user is "Foo Bar", the From:
234     # line is usually: "Foo Bar" <issue_tracker@tracker.example>
235     # the EMAIL_FROM_TAG goes inside the "Foo Bar" quotes like so:
236     #    "Foo Bar EMAIL_FROM_TAG" <issue_tracker@tracker.example>
237     EMAIL_FROM_TAG = ""
239     # Send nosy messages to the author of the message
240     MESSAGES_TO_AUTHOR = 'no'           # either 'yes' or 'no'
242     # Does the author of a message get placed on the nosy list
243     # automatically? If 'new' is used, then the author will only be
244     # added when a message creates a new issue. If 'yes', then the
245     # author will be added on followups too. If 'no', they're never
246     # added to the nosy.
247     ADD_AUTHOR_TO_NOSY = 'new'          # one of 'yes', 'no', 'new'
249     # Do the recipients (To:, Cc:) of a message get placed on the nosy
250     # list? If 'new' is used, then the recipients will only be added
251     # when a message creates a new issue. If 'yes', then the recipients
252     # will be added on followups too. If 'no', they're never added to
253     # the nosy.
254     ADD_RECIPIENTS_TO_NOSY = 'new'      # either 'yes', 'no', 'new'
256     # Where to place the email signature
257     EMAIL_SIGNATURE_POSITION = 'bottom' # one of 'top', 'bottom', 'none'
259     # Keep email citations
260     EMAIL_KEEP_QUOTED_TEXT = 'no'       # either 'yes' or 'no'
262     # Preserve the email body as is
263     EMAIL_LEAVE_BODY_UNCHANGED = 'no'   # either 'yes' or 'no'
265     # Default class to use in the mailgw if one isn't supplied in email
266     # subjects. To disable, comment out the variable below or leave it
267     # blank. Examples:
268     MAIL_DEFAULT_CLASS = 'issue'   # use "issue" class by default
269     #MAIL_DEFAULT_CLASS = ''        # disable (or just comment the var out)
271     # HTML version to generate. The templates are html4 by default. If you
272     # wish to make them xhtml, then you'll need to change this var to 'xhtml'
273     # too so all auto-generated HTML is compliant.
274     HTML_VERSION = 'html4'         # either 'html4' or 'xhtml'
276     # Character set to encode email headers with. We use utf-8 by default, as
277     # it's the most flexible. Some mail readers (eg. Eudora) can't cope with
278     # that, so you might need to specify a more limited character set (eg.
279     # 'iso-8859-1'.
280     EMAIL_CHARSET = 'utf-8'
281     #EMAIL_CHARSET = 'iso-8859-1'   # use this instead for Eudora users
283     # 
284     # SECURITY DEFINITIONS
285     #
286     # define the Roles that a user gets when they register with the
287     # tracker these are a comma-separated string of role names (e.g.
288     # 'Admin,User')
289     NEW_WEB_USER_ROLES = 'User'
290     NEW_EMAIL_USER_ROLES = 'User'
292 Tracker Schema
293 ==============
295 Note: if you modify the schema, you'll most likely need to edit the
296       `web interface`_ HTML template files and `detectors`_ to reflect
297       your changes.
299 A tracker schema defines what data is stored in the tracker's database.
300 Schemas are defined using Python code in the ``dbinit.py`` module of your
301 tracker. The "classic" schema looks like this (see below for the meaning
302 of ``'setkey'``)::
304     pri = Class(db, "priority", name=String(), order=String())
305     pri.setkey("name")
307     stat = Class(db, "status", name=String(), order=String())
308     stat.setkey("name")
310     keyword = Class(db, "keyword", name=String())
311     keyword.setkey("name")
313     user = Class(db, "user", username=String(), organisation=String(),
314         password=String(), address=String(), realname=String(),
315         phone=String())
316     user.setkey("username")
318     msg = FileClass(db, "msg", author=Link("user"), summary=String(),
319         date=Date(), recipients=Multilink("user"),
320         files=Multilink("file"))
322     file = FileClass(db, "file", name=String(), type=String())
324     issue = IssueClass(db, "issue", topic=Multilink("keyword"),
325         status=Link("status"), assignedto=Link("user"),
326         priority=Link("priority"))
327     issue.setkey('title')
330 What you can't do to the schema
331 -------------------------------
333 You must never:
335 **Remove the users class**
336   This class is the only *required* class in Roundup. Similarly, its
337   username, password and address properties must never be removed.
339 **Change the type of a property**
340   Property types must *never* be changed - the database simply doesn't take
341   this kind of action into account. Note that you can't just remove a
342   property and re-add it as a new type either. If you wanted to make the
343   assignedto property a Multilink, you'd need to create a new property
344   assignedto_list and remove the old assignedto property.
347 What you can do to the schema
348 -----------------------------
350 Your schema may be changed at any time before or after the tracker has been
351 initialised (or used). You may:
353 **Add new properties to classes, or add whole new classes**
354   This is painless and easy to do - there are generally no repurcussions
355   from adding new information to a tracker's schema.
357 **Remove properties**
358   Removing properties is a little more tricky - you need to make sure that
359   the property is no longer used in the `web interface`_ *or* by the
360   detectors_.
364 Classes and Properties - creating a new information store
365 ---------------------------------------------------------
367 In the tracker above, we've defined 7 classes of information:
369   priority
370       Defines the possible levels of urgency for issues.
372   status
373       Defines the possible states of processing the issue may be in.
375   keyword
376       Initially empty, will hold keywords useful for searching issues.
378   user
379       Initially holding the "admin" user, will eventually have an entry
380       for all users using roundup.
382   msg
383       Initially empty, will hold all e-mail messages sent to or
384       generated by roundup.
386   file
387       Initially empty, will hold all files attached to issues.
389   issue
390       Initially empty, this is where the issue information is stored.
392 We define the "priority" and "status" classes to allow two things:
393 reduction in the amount of information stored on the issue and more
394 powerful, accurate searching of issues by priority and status. By only
395 requiring a link on the issue (which is stored as a single number) we
396 reduce the chance that someone mis-types a priority or status - or
397 simply makes a new one up.
400 Class and Items
401 ~~~~~~~~~~~~~~~
403 A Class defines a particular class (or type) of data that will be stored
404 in the database. A class comprises one or more properties, which gives
405 the information about the class items.
407 The actual data entered into the database, using ``class.create()``, are
408 called items. They have a special immutable property called ``'id'``. We
409 sometimes refer to this as the *itemid*.
412 Properties
413 ~~~~~~~~~~
415 A Class is comprised of one or more properties of the following types:
417 * String properties are for storing arbitrary-length strings.
418 * Password properties are for storing encoded arbitrary-length strings.
419   The default encoding is defined on the ``roundup.password.Password``
420   class.
421 * Date properties store date-and-time stamps. Their values are Timestamp
422   objects.
423 * Number properties store numeric values.
424 * Boolean properties store on/off, yes/no, true/false values.
425 * A Link property refers to a single other item selected from a
426   specified class. The class is part of the property; the value is an
427   integer, the id of the chosen item.
428 * A Multilink property refers to possibly many items in a specified
429   class. The value is a list of integers.
432 FileClass
433 ~~~~~~~~~
435 FileClasses save their "content" attribute off in a separate file from
436 the rest of the database. This reduces the number of large entries in
437 the database, which generally makes databases more efficient, and also
438 allows us to use command-line tools to operate on the files. They are
439 stored in the files sub-directory of the ``'db'`` directory in your
440 tracker.
443 IssueClass
444 ~~~~~~~~~~
446 IssueClasses automatically include the "messages", "files", "nosy", and
447 "superseder" properties.
449 The messages and files properties list the links to the messages and
450 files related to the issue. The nosy property is a list of links to
451 users who wish to be informed of changes to the issue - they get "CC'ed"
452 e-mails when messages are sent to or generated by the issue. The nosy
453 reactor (in the ``'detectors'`` directory) handles this action. The
454 superseder link indicates an issue which has superseded this one.
456 They also have the dynamically generated "creation", "activity" and
457 "creator" properties.
459 The value of the "creation" property is the date when an item was
460 created, and the value of the "activity" property is the date when any
461 property on the item was last edited (equivalently, these are the dates
462 on the first and last records in the item's journal). The "creator"
463 property holds a link to the user that created the issue.
466 setkey(property)
467 ~~~~~~~~~~~~~~~~
469 Select a String property of the class to be the key property. The key
470 property must be unique, and allows references to the items in the class
471 by the content of the key property. That is, we can refer to users by
472 their username: for example, let's say that there's an issue in roundup,
473 issue 23. There's also a user, richard, who happens to be user 2. To
474 assign an issue to him, we could do either of::
476      roundup-admin set issue23 assignedto=2
478 or::
480      roundup-admin set issue23 assignedto=richard
482 Note, the same thing can be done in the web and e-mail interfaces. 
484 If a class does not have an "order" property, the key is also used to
485 sort instances of the class when it is rendered in the user interface.
486 (If a class has no "order" property, sorting is by the labelproperty of
487 the class. This is computed, in order of precedence, as the key, the
488 "name", the "title", or the first property alphabetically.)
491 create(information)
492 ~~~~~~~~~~~~~~~~~~~
494 Create an item in the database. This is generally used to create items
495 in the "definitional" classes like "priority" and "status".
498 Examples of adding to your schema
499 ---------------------------------
501 TODO
504 Detectors - adding behaviour to your tracker
505 ============================================
506 .. _detectors:
508 Detectors are initialised every time you open your tracker database, so
509 you're free to add and remove them any time, even after the database is
510 initialised via the "roundup-admin initialise" command.
512 The detectors in your tracker fire *before* (**auditors**) and *after*
513 (**reactors**) changes to the contents of your database. They are Python
514 modules that sit in your tracker's ``detectors`` directory. You will
515 have some installed by default - have a look. You can write new
516 detectors or modify the existing ones. The existing detectors installed
517 for you are:
519 **nosyreaction.py**
520   This provides the automatic nosy list maintenance and email sending.
521   The nosy reactor (``nosyreaction``) fires when new messages are added
522   to issues. The nosy auditor (``updatenosy``) fires when issues are
523   changed, and figures out what changes need to be made to the nosy list
524   (such as adding new authors, etc.)
525 **statusauditor.py**
526   This provides the ``chatty`` auditor which changes the issue status
527   from ``unread`` or ``closed`` to ``chatting`` if new messages appear.
528   It also provides the ``presetunread`` auditor which pre-sets the
529   status to ``unread`` on new items if the status isn't explicitly
530   defined.
531 **messagesummary.py**
532   Generates the ``summary`` property for new messages based on the message
533   content.
534 **userauditor.py**
535   Verifies the content of some of the user fields (email addresses and
536   roles lists).
538 If you don't want this default behaviour, you're completely free to change
539 or remove these detectors.
541 See the detectors section in the `design document`__ for details of the
542 interface for detectors.
544 __ design.html
546 Sample additional detectors that have been found useful will appear in
547 the ``'detectors'`` directory of the Roundup distribution. If you want
548 to use one, copy it to the ``'detectors'`` of your tracker instance:
550 **newissuecopy.py**
551   This detector sends an email to a team address whenever a new issue is
552   created. The address is hard-coded into the detector, so edit it
553   before you use it (look for the text 'team@team.host') or you'll get
554   email errors!
556   The detector code::
558     from roundup import roundupdb
560     def newissuecopy(db, cl, nodeid, oldvalues):
561         ''' Copy a message about new issues to a team address.
562         '''
563         # so use all the messages in the create
564         change_note = cl.generateCreateNote(nodeid)
566         # send a copy to the nosy list
567         for msgid in cl.get(nodeid, 'messages'):
568             try:
569                 # note: last arg must be a list
570                 cl.send_message(nodeid, msgid, change_note,
571                     ['team@team.host'])
572             except roundupdb.MessageSendError, message:
573                 raise roundupdb.DetectorError, message
575     def init(db):
576         db.issue.react('create', newissuecopy)
579 Database Content
580 ================
582 Note: if you modify the content of definitional classes, you'll most
583        likely need to edit the tracker `detectors`_ to reflect your
584        changes.
586 Customisation of the special "definitional" classes (eg. status,
587 priority, resolution, ...) may be done either before or after the
588 tracker is initialised. The actual method of doing so is completely
589 different in each case though, so be careful to use the right one.
591 **Changing content before tracker initialisation**
592     Edit the dbinit module in your tracker to alter the items created in
593     using the ``create()`` methods.
595 **Changing content after tracker initialisation**
596     As the "admin" user, click on the "class list" link in the web
597     interface to bring up a list of all database classes. Click on the
598     name of the class you wish to change the content of.
600     You may also use the ``roundup-admin`` interface's create, set and
601     retire methods to add, alter or remove items from the classes in
602     question.
604 See "`adding a new field to the classic schema`_" for an example that
605 requires database content changes.
608 Security / Access Controls
609 ==========================
611 A set of Permissions is built into the security module by default:
613 - Edit (everything)
614 - View (everything)
616 The default interfaces define:
618 - Web Registration
619 - Web Access
620 - Web Roles
621 - Email Registration
622 - Email Access
624 These are hooked into the default Roles:
626 - Admin (Edit everything, View everything, Web Roles)
627 - User (Web Access, Email Access)
628 - Anonymous (Web Registration, Email Registration)
630 And finally, the "admin" user gets the "Admin" Role, and the "anonymous"
631 user gets "Anonymous" assigned when the database is initialised on
632 installation. The two default schemas then define:
634 - Edit issue, View issue (both)
635 - Edit file, View file (both)
636 - Edit msg, View msg (both)
637 - Edit support, View support (extended only)
639 and assign those Permissions to the "User" Role. Put together, these
640 settings appear in the ``open()`` function of the tracker ``dbinit.py``
641 (the following is taken from the "minimal" template's ``dbinit.py``)::
643     #
644     # SECURITY SETTINGS
645     #
646     # new permissions for this schema
647     for cl in ('user', ):
648         db.security.addPermission(name="Edit", klass=cl,
649             description="User is allowed to edit "+cl)
650         db.security.addPermission(name="View", klass=cl,
651             description="User is allowed to access "+cl)
653     # and give the regular users access to the web and email interface
654     p = db.security.getPermission('Web Access')
655     db.security.addPermissionToRole('User', p)
656     p = db.security.getPermission('Email Access')
657     db.security.addPermissionToRole('User', p)
659     # May users view other user information? Comment these lines out
660     # if you don't want them to
661     p = db.security.getPermission('View', 'user')
662     db.security.addPermissionToRole('User', p)
664     # Assign the appropriate permissions to the anonymous user's
665     # Anonymous role. Choices here are:
666     # - Allow anonymous users to register through the web
667     p = db.security.getPermission('Web Registration')
668     db.security.addPermissionToRole('Anonymous', p)
669     # - Allow anonymous (new) users to register through the email
670     #   gateway
671     p = db.security.getPermission('Email Registration')
672     db.security.addPermissionToRole('Anonymous', p)
675 New User Roles
676 --------------
678 New users are assigned the Roles defined in the config file as:
680 - NEW_WEB_USER_ROLES
681 - NEW_EMAIL_USER_ROLES
684 Changing Access Controls
685 ------------------------
687 You may alter the configuration variables to change the Role that new
688 web or email users get, for example to not give them access to the web
689 interface if they register through email. 
691 You may use the ``roundup-admin`` "``security``" command to display the
692 current Role and Permission configuration in your tracker.
695 Adding a new Permission
696 ~~~~~~~~~~~~~~~~~~~~~~~
698 When adding a new Permission, you will need to:
700 1. add it to your tracker's dbinit so it is created
701 2. enable it for the Roles that should have it (verify with
702    "``roundup-admin security``")
703 3. add it to the relevant HTML interface templates
704 4. add it to the appropriate xxxPermission methods on in your tracker
705    interfaces module
708 Example Scenarios
709 ~~~~~~~~~~~~~~~~~
711 **automatic registration of users in the e-mail gateway**
712  By giving the "anonymous" user the "Email Registration" Role, any
713  unidentified user will automatically be registered with the tracker
714  (with no password, so they won't be able to log in through the web
715  until an admin sets their password). Note: this is the default
716  behaviour in the tracker templates that ship with Roundup.
718 **anonymous access through the e-mail gateway**
719  Give the "anonymous" user the "Email Access" and ("Edit", "issue")
720  Roles but do not not give them the "Email Registration" Role. This
721  means that when an unknown user sends email into the tracker, they're
722  automatically logged in as "anonymous". Since they don't have the
723  "Email Registration" Role, they won't be automatically registered, but
724  since "anonymous" has permission to use the gateway, they'll still be
725  able to submit issues. Note that the Sender information - their email
726  address - will not be available - they're *anonymous*.
728 **only developers may be assigned issues**
729  Create a new Permission called "Fixer" for the "issue" class. Create a
730  new Role "Developer" which has that Permission, and assign that to the
731  appropriate users. Filter the list of users available in the assignedto
732  list to include only those users. Enforce the Permission with an
733  auditor. See the example 
734  `restricting the list of users that are assignable to a task`_.
736 **only managers may sign off issues as complete**
737  Create a new Permission called "Closer" for the "issue" class. Create a
738  new Role "Manager" which has that Permission, and assign that to the
739  appropriate users. In your web interface, only display the "resolved"
740  issue state option when the user has the "Closer" Permissions. Enforce
741  the Permission with an auditor. This is very similar to the previous
742  example, except that the web interface check would look like::
744    <option tal:condition="python:request.user.hasPermission('Closer')"
745            value="resolved">Resolved</option>
746  
747 **don't give web access to users who register through email**
748  Create a new Role called "Email User" which has all the Permissions of
749  the normal "User" Role minus the "Web Access" Permission. This will
750  allow users to send in emails to the tracker, but not access the web
751  interface.
753 **let some users edit the details of all users**
754  Create a new Role called "User Admin" which has the Permission for
755  editing users::
757     db.security.addRole(name='User Admin', description='Managing users')
758     p = db.security.getPermission('Edit', 'user')
759     db.security.addPermissionToRole('User Admin', p)
761  and assign the Role to the users who need the permission.
764 Web Interface
765 =============
767 .. contents::
768    :local:
769    :depth: 1
771 The web interface is provided by the ``roundup.cgi.client`` module and
772 is used by ``roundup.cgi``, ``roundup-server`` and ``ZRoundup``
773 (``ZRoundup``  is broken, until further notice). In all cases, we
774 determine which tracker is being accessed (the first part of the URL
775 path inside the scope of the CGI handler) and pass control on to the
776 tracker ``interfaces.Client`` class - which uses the ``Client`` class
777 from ``roundup.cgi.client`` - which handles the rest of the access
778 through its ``main()`` method. This means that you can do pretty much
779 anything you want as a web interface to your tracker.
781 Repercussions of changing the tracker schema
782 ---------------------------------------------
784 If you choose to change the `tracker schema`_ you will need to ensure
785 the web interface knows about it:
787 1. Index, item and search pages for the relevant classes may need to
788    have properties added or removed,
789 2. The "page" template may require links to be changed, as might the
790    "home" page's content arguments.
792 How requests are processed
793 --------------------------
795 The basic processing of a web request proceeds as follows:
797 1. figure out who we are, defaulting to the "anonymous" user
798 2. figure out what the request is for - we call this the "context"
799 3. handle any requested action (item edit, search, ...)
800 4. render the template requested by the context, resulting in HTML
801    output
803 In some situations, exceptions occur:
805 - HTTP Redirect  (generally raised by an action)
806 - SendFile       (generally raised by ``determine_context``)
807     here we serve up a FileClass "content" property
808 - SendStaticFile (generally raised by ``determine_context``)
809     here we serve up a file from the tracker "html" directory
810 - Unauthorised   (generally raised by an action)
811     here the action is cancelled, the request is rendered and an error
812     message is displayed indicating that permission was not granted for
813     the action to take place
814 - NotFound       (raised wherever it needs to be)
815     this exception percolates up to the CGI interface that called the
816     client
818 Determining web context
819 -----------------------
821 To determine the "context" of a request, we look at the URL and the
822 special request variable ``@template``. The URL path after the tracker
823 identifier is examined. Typical URL paths look like:
825 1.  ``/tracker/issue``
826 2.  ``/tracker/issue1``
827 3.  ``/tracker/_file/style.css``
828 4.  ``/cgi-bin/roundup.cgi/tracker/file1``
829 5.  ``/cgi-bin/roundup.cgi/tracker/file1/kitten.png``
831 where the "tracker identifier" is "tracker" in the above cases. That means
832 we're looking at "issue", "issue1", "_file/style.css", "file1" and
833 "file1/kitten.png" in the cases above. The path is generally only one
834 entry long - longer paths are handled differently.
836 a. if there is no path, then we are in the "home" context.
837 b. if the path starts with "_file" (as in example 3,
838    "/tracker/_file/style.css"), then the additional path entry,
839    "style.css" specifies the filename of a static file we're to serve up
840    from the tracker "html" directory. Raises a SendStaticFile exception.
841 c. if there is something in the path (as in example 1, "issue"), it
842    identifies the tracker class we're to display.
843 d. if the path is an item designator (as in examples 2 and 4, "issue1"
844    and "file1"), then we're to display a specific item.
845 e. if the path starts with an item designator and is longer than one
846    entry (as in example 5, "file1/kitten.png"), then we're assumed to be
847    handling an item of a ``FileClass``, and the extra path information
848    gives the filename that the client is going to label the download
849    with (i.e. "file1/kitten.png" is nicer to download than "file1").
850    This raises a ``SendFile`` exception.
852 Both b. and e. stop before we bother to determine the template we're
853 going to use. That's because they don't actually use templates.
855 The template used is specified by the ``@template`` CGI variable, which
856 defaults to:
858 - only classname suplied:        "index"
859 - full item designator supplied: "item"
862 Performing actions in web requests
863 ----------------------------------
865 When a user requests a web page, they may optionally also request for an
866 action to take place. As described in `how requests are processed`_, the
867 action is performed before the requested page is generated. Actions are
868 triggered by using a ``@action`` CGI variable, where the value is one
869 of:
871 **login**
872  Attempt to log a user in.
874 **logout**
875  Log the user out - make them "anonymous".
877 **register**
878  Attempt to create a new user based on the contents of the form and then
879  log them in.
881 **edit**
882  Perform an edit of an item in the database. There are some `special form
883  variables`_ you may use.
885 **new**
886  Add a new item to the database. You may use the same `special form
887  variables`_ as in the "edit" action.
889 **retire**
890  Retire the item in the database.
892 **editCSV**
893  Performs an edit of all of a class' items in one go. See also the
894  *class*.csv templating method which generates the CSV data to be
895  edited, and the ``'_generic.index'`` template which uses both of these
896  features.
898 **search**
899  Mangle some of the form variables:
901  - Set the form ":filter" variable based on the values of the filter
902    variables - if they're set to anything other than "dontcare" then add
903    them to :filter.
905  - Also handle the ":queryname" variable and save off the query to the
906    user's query list.
908 Each of the actions is implemented by a corresponding ``*XxxAction*`` (where
909 "Xxx" is the name of the action) class in the ``roundup.cgi.actions`` module.
910 These classes are registered with ``roundup.cgi.client.Client`` which also
911 happens to be available in your tracker instance as ``interfaces.Client``. So
912 if you need to define new actions, you may add them there (see `defining new
913 web actions`_).
915 Each action class also has a ``*permission*`` method which determines whether
916 the action is permissible given the current user. The base permission checks
917 are:
919 **login**
920  Determine whether the user has permission to log in. Base behaviour is
921  to check the user has "Web Access".
922 **logout**
923  No permission checks are made.
924 **register**
925  Determine whether the user has permission to register. Base behaviour
926  is to check the user has the "Web Registration" Permission.
927 **edit**
928  Determine whether the user has permission to edit this item. Base
929  behaviour is to check whether the user can edit this class. If we're
930  editing the "user" class, users are allowed to edit their own details -
931  unless they try to edit the "roles" property, which requires the
932  special Permission "Web Roles".
933 **new**
934  Determine whether the user has permission to create (or edit) this
935  item. Base behaviour is to check the user can edit this class. No
936  additional property checks are made. Additionally, new user items may
937  be created if the user has the "Web Registration" Permission.
938 **editCSV**
939  Determine whether the user has permission to edit this class. Base
940  behaviour is to check whether the user may edit this class.
941 **search**
942  Determine whether the user has permission to search this class. Base
943  behaviour is to check whether the user may view this class.
946 Special form variables
947 ----------------------
949 Item properties and their values are edited with html FORM
950 variables and their values. You can:
952 - Change the value of some property of the current item.
953 - Create a new item of any class, and edit the new item's
954   properties,
955 - Attach newly created items to a multilink property of the
956   current item.
957 - Remove items from a multilink property of the current item.
958 - Specify that some properties are required for the edit
959   operation to be successful.
961 In the following, <bracketed> values are variable, "@" may be
962 either ":" or "@", and other text "required" is fixed.
964 Most properties are specified as form variables:
966 ``<propname>``
967   property on the current context item
969 ``<designator>"@"<propname>``
970   property on the indicated item (for editing related information)
972 Designators name a specific item of a class.
974 ``<classname><N>``
975     Name an existing item of class <classname>.
977 ``<classname>"-"<N>``
978     Name the <N>th new item of class <classname>. If the form
979     submission is successful, a new item of <classname> is
980     created. Within the submitted form, a particular
981     designator of this form always refers to the same new
982     item.
984 Once we have determined the "propname", we look at it to see
985 if it's special:
987 ``@required``
988     The associated form value is a comma-separated list of
989     property names that must be specified when the form is
990     submitted for the edit operation to succeed.  
992     When the <designator> is missing, the properties are
993     for the current context item.  When <designator> is
994     present, they are for the item specified by
995     <designator>.
997     The "@required" specifier must come before any of the
998     properties it refers to are assigned in the form.
1000 ``@remove@<propname>=id(s)`` or ``@add@<propname>=id(s)``
1001     The "@add@" and "@remove@" edit actions apply only to
1002     Multilink properties.  The form value must be a
1003     comma-separate list of keys for the class specified by
1004     the simple form variable.  The listed items are added
1005     to (respectively, removed from) the specified
1006     property.
1008 ``@link@<propname>=<designator>``
1009     If the edit action is "@link@", the simple form
1010     variable must specify a Link or Multilink property.
1011     The form value is a comma-separated list of
1012     designators.  The item corresponding to each
1013     designator is linked to the property given by simple
1014     form variable.
1016 None of the above (ie. just a simple form value)
1017     The value of the form variable is converted
1018     appropriately, depending on the type of the property.
1020     For a Link('klass') property, the form value is a
1021     single key for 'klass', where the key field is
1022     specified in dbinit.py.  
1024     For a Multilink('klass') property, the form value is a
1025     comma-separated list of keys for 'klass', where the
1026     key field is specified in dbinit.py.  
1028     Note that for simple-form-variables specifiying Link
1029     and Multilink properties, the linked-to class must
1030     have a key field.
1032     For a String() property specifying a filename, the
1033     file named by the form value is uploaded. This means we
1034     try to set additional properties "filename" and "type" (if
1035     they are valid for the class).  Otherwise, the property
1036     is set to the form value.
1038     For Date(), Interval(), Boolean(), and Number()
1039     properties, the form value is converted to the
1040     appropriate
1042 Any of the form variables may be prefixed with a classname or
1043 designator.
1045 Two special form values are supported for backwards compatibility:
1047 @note
1048     This is equivalent to::
1050         @link@messages=msg-1
1051         msg-1@content=value
1053     except that in addition, the "author" and "date" properties of
1054     "msg-1" are set to the userid of the submitter, and the current
1055     time, respectively.
1057 @file
1058     This is equivalent to::
1060         @link@files=file-1
1061         file-1@content=value
1063     The String content value is handled as described above for file
1064     uploads.
1066 If both the "@note" and "@file" form variables are
1067 specified, the action::
1069         @link@msg-1@files=file-1
1071 is also performed.
1073 We also check that FileClass items have a "content" property with
1074 actual content, otherwise we remove them from all_props before
1075 returning.
1079 Default templates
1080 -----------------
1082 The default templates are html4 compliant. If you wish to change them to be
1083 xhtml compliant, you'll need to change the ``HTML_VERSION`` configuration
1084 variable in ``config.py`` to ``'xhtml'`` instead of ``'html4'``.
1086 Most customisation of the web view can be done by modifying the
1087 templates in the tracker ``'html'`` directory. There are several types
1088 of files in there. The *minimal* template includes:
1090 **page.html**
1091   This template usually defines the overall look of your tracker. When
1092   you view an issue, it appears inside this template. When you view an
1093   index, it also appears inside this template. This template defines a
1094   macro called "icing" which is used by almost all other templates as a
1095   coating for their content, using its "content" slot. It also defines
1096   the "head_title" and "body_title" slots to allow setting of the page
1097   title.
1098 **home.html**
1099   the default page displayed when no other page is indicated by the user
1100 **home.classlist.html**
1101   a special version of the default page that lists the classes in the
1102   tracker
1103 **classname.item.html**
1104   displays an item of the *classname* class
1105 **classname.index.html**
1106   displays a list of *classname* items
1107 **classname.search.html**
1108   displays a search page for *classname* items
1109 **_generic.index.html**
1110   used to display a list of items where there is no
1111   ``*classname*.index`` available
1112 **_generic.help.html**
1113   used to display a "class help" page where there is no
1114   ``*classname*.help``
1115 **user.register.html**
1116   a special page just for the user class, that renders the registration
1117   page
1118 **style.css.html**
1119   a static file that is served up as-is
1121 The *classic* template has a number of additional templates.
1123 Note: Remember that you can create any template extension you want to,
1124 so if you just want to play around with the templating for new issues,
1125 you can copy the current "issue.item" template to "issue.test", and then
1126 access the test template using the "@template" URL argument::
1128    http://your.tracker.example/tracker/issue?@template=test
1130 and it won't affect your users using the "issue.item" template.
1133 How the templates work
1134 ----------------------
1137 Basic Templating Actions
1138 ~~~~~~~~~~~~~~~~~~~~~~~~
1140 Roundup's templates consist of special attributes on the HTML tags.
1141 These attributes form the Template Attribute Language, or TAL. The basic
1142 TAL commands are:
1144 **tal:define="variable expression; variable expression; ..."**
1145    Define a new variable that is local to this tag and its contents. For
1146    example::
1148       <html tal:define="title request/description">
1149        <head><title tal:content="title"></title></head>
1150       </html>
1152    In this example, the variable "title" is defined as the result of the
1153    expression "request/description". The "tal:content" command inside the
1154    <html> tag may then use the "title" variable.
1156 **tal:condition="expression"**
1157    Only keep this tag and its contents if the expression is true. For
1158    example::
1160      <p tal:condition="python:request.user.hasPermission('View', 'issue')">
1161       Display some issue information.
1162      </p>
1164    In the example, the <p> tag and its contents are only displayed if
1165    the user has the "View" permission for issues. We consider the number
1166    zero, a blank string, an empty list, and the built-in variable
1167    nothing to be false values. Nearly every other value is true,
1168    including non-zero numbers, and strings with anything in them (even
1169    spaces!).
1171 **tal:repeat="variable expression"**
1172    Repeat this tag and its contents for each element of the sequence
1173    that the expression returns, defining a new local variable and a
1174    special "repeat" variable for each element. For example::
1176      <tr tal:repeat="u user/list">
1177       <td tal:content="u/id"></td>
1178       <td tal:content="u/username"></td>
1179       <td tal:content="u/realname"></td>
1180      </tr>
1182    The example would iterate over the sequence of users returned by
1183    "user/list" and define the local variable "u" for each entry.
1185 **tal:replace="expression"**
1186    Replace this tag with the result of the expression. For example::
1188     <span tal:replace="request/user/realname" />
1190    The example would replace the <span> tag and its contents with the
1191    user's realname. If the user's realname was "Bruce", then the
1192    resultant output would be "Bruce".
1194 **tal:content="expression"**
1195    Replace the contents of this tag with the result of the expression.
1196    For example::
1198     <span tal:content="request/user/realname">user's name appears here
1199     </span>
1201    The example would replace the contents of the <span> tag with the
1202    user's realname. If the user's realname was "Bruce" then the
1203    resultant output would be "<span>Bruce</span>".
1205 **tal:attributes="attribute expression; attribute expression; ..."**
1206    Set attributes on this tag to the results of expressions. For
1207    example::
1209      <a tal:attributes="href string:user${request/user/id}">My Details</a>
1211    In the example, the "href" attribute of the <a> tag is set to the
1212    value of the "string:user${request/user/id}" expression, which will
1213    be something like "user123".
1215 **tal:omit-tag="expression"**
1216    Remove this tag (but not its contents) if the expression is true. For
1217    example::
1219       <span tal:omit-tag="python:1">Hello, world!</span>
1221    would result in output of::
1223       Hello, world!
1225 Note that the commands on a given tag are evaulated in the order above,
1226 so *define* comes before *condition*, and so on.
1228 Additionally, you may include tags such as <tal:block>, which are
1229 removed from output. Its content is kept, but the tag itself is not (so
1230 don't go using any "tal:attributes" commands on it). This is useful for
1231 making arbitrary blocks of HTML conditional or repeatable (very handy
1232 for repeating multiple table rows, which would othewise require an
1233 illegal tag placement to effect the repeat).
1236 Templating Expressions
1237 ~~~~~~~~~~~~~~~~~~~~~~
1239 The expressions you may use in the attribute values may be one of the
1240 following forms:
1242 **Path Expressions** - eg. ``item/status/checklist``
1243    These are object attribute / item accesses. Roughly speaking, the
1244    path ``item/status/checklist`` is broken into parts ``item``,
1245    ``status`` and ``checklist``. The ``item`` part is the root of the
1246    expression. We then look for a ``status`` attribute on ``item``, or
1247    failing that, a ``status`` item (as in ``item['status']``). If that
1248    fails, the path expression fails. When we get to the end, the object
1249    we're left with is evaluated to get a string - if it is a method, it
1250    is called; if it is an object, it is stringified. Path expressions
1251    may have an optional ``path:`` prefix, but they are the default
1252    expression type, so it's not necessary.
1254    If an expression evaluates to ``default``, then the expression is
1255    "cancelled" - whatever HTML already exists in the template will
1256    remain (tag content in the case of ``tal:content``, attributes in the
1257    case of ``tal:attributes``).
1259    If an expression evaluates to ``nothing`` then the target of the
1260    expression is removed (tag content in the case of ``tal:content``,
1261    attributes in the case of ``tal:attributes`` and the tag itself in
1262    the case of ``tal:replace``).
1264    If an element in the path may not exist, then you can use the ``|``
1265    operator in the expression to provide an alternative. So, the
1266    expression ``request/form/foo/value | default`` would simply leave
1267    the current HTML in place if the "foo" form variable doesn't exist.
1269    You may use the python function ``path``, as in
1270    ``path("item/status")``, to embed path expressions in Python
1271    expressions.
1273 **String Expressions** - eg. ``string:hello ${user/name}`` 
1274    These expressions are simple string interpolations - though they can
1275    be just plain strings with no interpolation if you want. The
1276    expression in the ``${ ... }`` is just a path expression as above.
1278 **Python Expressions** - eg. ``python: 1+1`` 
1279    These expressions give the full power of Python. All the "root level"
1280    variables are available, so ``python:item.status.checklist()`` would
1281    be equivalent to ``item/status/checklist``, assuming that
1282    ``checklist`` is a method.
1284 Modifiers:
1286 **structure** - eg. ``structure python:msg.content.plain(hyperlink=1)``
1287    The result of expressions are normally *escaped* to be safe for HTML
1288    display (all "<", ">" and "&" are turned into special entities). The
1289    ``structure`` expression modifier turns off this escaping - the
1290    result of the expression is now assumed to be HTML, which is passed
1291    to the web browser for rendering.
1293 **not:** - eg. ``not:python:1=1``
1294    This simply inverts the logical true/false value of another
1295    expression.
1298 Template Macros
1299 ~~~~~~~~~~~~~~~
1301 Macros are used in Roundup to save us from repeating the same common
1302 page stuctures over and over. The most common (and probably only) macro
1303 you'll use is the "icing" macro defined in the "page" template.
1305 Macros are generated and used inside your templates using special
1306 attributes similar to the `basic templating actions`_. In this case,
1307 though, the attributes belong to the Macro Expansion Template Attribute
1308 Language, or METAL. The macro commands are:
1310 **metal:define-macro="macro name"**
1311   Define that the tag and its contents are now a macro that may be
1312   inserted into other templates using the *use-macro* command. For
1313   example::
1315     <html metal:define-macro="page">
1316      ...
1317     </html>
1319   defines a macro called "page" using the ``<html>`` tag and its
1320   contents. Once defined, macros are stored on the template they're
1321   defined on in the ``macros`` attribute. You can access them later on
1322   through the ``templates`` variable, eg. the most common
1323   ``templates/page/macros/icing`` to access the "page" macro of the
1324   "page" template.
1326 **metal:use-macro="path expression"**
1327   Use a macro, which is identified by the path expression (see above).
1328   This will replace the current tag with the identified macro contents.
1329   For example::
1331    <tal:block metal:use-macro="templates/page/macros/icing">
1332     ...
1333    </tal:block>
1335    will replace the tag and its contents with the "page" macro of the
1336    "page" template.
1338 **metal:define-slot="slot name"** and **metal:fill-slot="slot name"**
1339   To define *dynamic* parts of the macro, you define "slots" which may
1340   be filled when the macro is used with a *use-macro* command. For
1341   example, the ``templates/page/macros/icing`` macro defines a slot like
1342   so::
1344     <title metal:define-slot="head_title">title goes here</title>
1346   In your *use-macro* command, you may now use a *fill-slot* command
1347   like this::
1349     <title metal:fill-slot="head_title">My Title</title>
1351   where the tag that fills the slot completely replaces the one defined
1352   as the slot in the macro.
1354 Note that you may not mix METAL and TAL commands on the same tag, but
1355 TAL commands may be used freely inside METAL-using tags (so your
1356 *fill-slots* tags may have all manner of TAL inside them).
1359 Information available to templates
1360 ----------------------------------
1362 Note: this is implemented by
1363 ``roundup.cgi.templating.RoundupPageTemplate``
1365 The following variables are available to templates.
1367 **context**
1368   The current context. This is either None, a `hyperdb class wrapper`_
1369   or a `hyperdb item wrapper`_
1370 **request**
1371   Includes information about the current request, including:
1372    - the current index information (``filterspec``, ``filter`` args,
1373      ``properties``, etc) parsed out of the form. 
1374    - methods for easy filterspec link generation
1375    - *user*, the current user item as an HTMLItem instance
1376    - *form*
1377      The current CGI form information as a mapping of form argument name
1378      to value
1379 **config**
1380   This variable holds all the values defined in the tracker config.py
1381   file (eg. TRACKER_NAME, etc.)
1382 **db**
1383   The current database, used to access arbitrary database items.
1384 **templates**
1385   Access to all the tracker templates by name. Used mainly in
1386   *use-macro* commands.
1387 **utils**
1388   This variable makes available some utility functions like batching.
1389 **nothing**
1390   This is a special variable - if an expression evaluates to this, then
1391   the tag (in the case of a ``tal:replace``), its contents (in the case
1392   of ``tal:content``) or some attributes (in the case of
1393   ``tal:attributes``) will not appear in the the output. So, for
1394   example::
1396     <span tal:attributes="class nothing">Hello, World!</span>
1398   would result in::
1400     <span>Hello, World!</span>
1402 **default**
1403   Also a special variable - if an expression evaluates to this, then the
1404   existing HTML in the template will not be replaced or removed, it will
1405   remain. So::
1407     <span tal:replace="default">Hello, World!</span>
1409   would result in::
1411     <span>Hello, World!</span>
1414 The context variable
1415 ~~~~~~~~~~~~~~~~~~~~
1417 The *context* variable is one of three things based on the current
1418 context (see `determining web context`_ for how we figure this out):
1420 1. if we're looking at a "home" page, then it's None
1421 2. if we're looking at a specific hyperdb class, it's a
1422    `hyperdb class wrapper`_.
1423 3. if we're looking at a specific hyperdb item, it's a
1424    `hyperdb item wrapper`_.
1426 If the context is not None, we can access the properties of the class or
1427 item. The only real difference between cases 2 and 3 above are:
1429 1. the properties may have a real value behind them, and this will
1430    appear if the property is displayed through ``context/property`` or
1431    ``context/property/field``.
1432 2. the context's "id" property will be a false value in the second case,
1433    but a real, or true value in the third. Thus we can determine whether
1434    we're looking at a real item from the hyperdb by testing
1435    "context/id".
1437 Hyperdb class wrapper
1438 :::::::::::::::::::::
1440 Note: this is implemented by the ``roundup.cgi.templating.HTMLClass``
1441 class.
1443 This wrapper object provides access to a hyperb class. It is used
1444 primarily in both index view and new item views, but it's also usable
1445 anywhere else that you wish to access information about a class, or the
1446 items of a class, when you don't have a specific item of that class in
1447 mind.
1449 We allow access to properties. There will be no "id" property. The value
1450 accessed through the property will be the current value of the same name
1451 from the CGI form.
1453 There are several methods available on these wrapper objects:
1455 =========== =============================================================
1456 Method      Description
1457 =========== =============================================================
1458 properties  return a `hyperdb property wrapper`_ for all of this class's
1459             properties.
1460 list        lists all of the active (not retired) items in the class.
1461 csv         return the items of this class as a chunk of CSV text.
1462 propnames   lists the names of the properties of this class.
1463 filter      lists of items from this class, filtered and sorted by the
1464             current *request* filterspec/filter/sort/group args
1465 classhelp   display a link to a javascript popup containing this class'
1466             "help" template.
1467 submit      generate a submit button (and action hidden element)
1468 renderWith  render this class with the given template.
1469 history     returns 'New node - no history' :)
1470 is_edit_ok  is the user allowed to Edit the current class?
1471 is_view_ok  is the user allowed to View the current class?
1472 =========== =============================================================
1474 Note that if you have a property of the same name as one of the above
1475 methods, you'll need to access it using a python "item access"
1476 expression. For example::
1478    python:context['list']
1480 will access the "list" property, rather than the list method.
1483 Hyperdb item wrapper
1484 ::::::::::::::::::::
1486 Note: this is implemented by the ``roundup.cgi.templating.HTMLItem``
1487 class.
1489 This wrapper object provides access to a hyperb item.
1491 We allow access to properties. There will be no "id" property. The value
1492 accessed through the property will be the current value of the same name
1493 from the CGI form.
1495 There are several methods available on these wrapper objects:
1497 =============== ========================================================
1498 Method          Description
1499 =============== ========================================================
1500 submit          generate a submit button (and action hidden element)
1501 journal         return the journal of the current item (**not
1502                 implemented**)
1503 history         render the journal of the current item as HTML
1504 renderQueryForm specific to the "query" class - render the search form
1505                 for the query
1506 hasPermission   specific to the "user" class - determine whether the
1507                 user has a Permission
1508 is_edit_ok      is the user allowed to Edit the current item?
1509 is_view_ok      is the user allowed to View the current item?
1510 =============== ========================================================
1512 Note that if you have a property of the same name as one of the above
1513 methods, you'll need to access it using a python "item access"
1514 expression. For example::
1516    python:context['journal']
1518 will access the "journal" property, rather than the journal method.
1521 Hyperdb property wrapper
1522 ::::::::::::::::::::::::
1524 Note: this is implemented by subclasses of the
1525 ``roundup.cgi.templating.HTMLProperty`` class (``HTMLStringProperty``,
1526 ``HTMLNumberProperty``, and so on).
1528 This wrapper object provides access to a single property of a class. Its
1529 value may be either:
1531 1. if accessed through a `hyperdb item wrapper`_, then it's a value from
1532    the hyperdb
1533 2. if access through a `hyperdb class wrapper`_, then it's a value from
1534    the CGI form
1537 The property wrapper has some useful attributes:
1539 =============== ========================================================
1540 Attribute       Description
1541 =============== ========================================================
1542 _name           the name of the property
1543 _value          the value of the property if any - this is the actual
1544                 value retrieved from the hyperdb for this property
1545 =============== ========================================================
1547 There are several methods available on these wrapper objects:
1549 =========== ================================================================
1550 Method      Description
1551 =========== ================================================================
1552 plain       render a "plain" representation of the property. This method
1553             may take two arguments:
1555             escape
1556              If true, escape the text so it is HTML safe (default: no). The
1557              reason this defaults to off is that text is usually escaped
1558              at a later stage by the TAL commands, unless the "structure"
1559              option is used in the template. The following ``tal:content``
1560              expressions are all equivalent::
1561  
1562               "structure python:msg.content.plain(escape=1)"
1563               "python:msg.content.plain()"
1564               "msg/content/plain"
1565               "msg/content"
1567              Usually you'll only want to use the escape option in a
1568              complex expression.
1570             hyperlink
1571              If true, turn URLs, email addresses and hyperdb item
1572              designators in the text into hyperlinks (default: no). Note
1573              that you'll need to use the "structure" TAL option if you
1574              want to use this ``tal:content`` expression::
1575   
1576               "structure python:msg.content.plain(hyperlink=1)"
1578              Note also that the text is automatically HTML-escaped before
1579              the hyperlinking transformation.
1580 hyperlinked The same as msg.content.plain(hyperlink=1), but nicer::
1582               "structure msg/content/hyperlinked"
1584 field       render an appropriate form edit field for the property - for
1585             most types this is a text entry box, but for Booleans it's a
1586             tri-state yes/no/neither selection.
1587 stext       only on String properties - render the value of the property
1588             as StructuredText (requires the StructureText module to be
1589             installed separately)
1590 multiline   only on String properties - render a multiline form edit
1591             field for the property
1592 email       only on String properties - render the value of the property
1593             as an obscured email address
1594 confirm     only on Password properties - render a second form edit field
1595             for the property, used for confirmation that the user typed
1596             the password correctly. Generates a field with name
1597             "name:confirm".
1598 now         only on Date properties - return the current date as a new
1599             property
1600 reldate     only on Date properties - render the interval between the date
1601             and now
1602 local       only on Date properties - return this date as a new property
1603             with some timezone offset, for example::
1604             
1605                 python:context.creation.local(10)
1607             will render the date with a +10 hour offset.
1608 pretty      only on Interval properties - render the interval in a pretty
1609             format (eg. "yesterday")
1610 menu        only on Link and Multilink properties - render a form select
1611             list for this property
1612 reverse     only on Multilink properties - produce a list of the linked
1613             items in reverse order
1614 =========== ================================================================
1617 The request variable
1618 ~~~~~~~~~~~~~~~~~~~~
1620 Note: this is implemented by the ``roundup.cgi.templating.HTMLRequest``
1621 class.
1623 The request variable is packed with information about the current
1624 request.
1626 .. taken from ``roundup.cgi.templating.HTMLRequest`` docstring
1628 =========== ============================================================
1629 Variable    Holds
1630 =========== ============================================================
1631 form        the CGI form as a cgi.FieldStorage
1632 env         the CGI environment variables
1633 base        the base URL for this tracker
1634 user        a HTMLUser instance for this user
1635 classname   the current classname (possibly None)
1636 template    the current template (suffix, also possibly None)
1637 form        the current CGI form variables in a FieldStorage
1638 =========== ============================================================
1640 **Index page specific variables (indexing arguments)**
1642 =========== ============================================================
1643 Variable    Holds
1644 =========== ============================================================
1645 columns     dictionary of the columns to display in an index page
1646 show        a convenience access to columns - request/show/colname will
1647             be true if the columns should be displayed, false otherwise
1648 sort        index sort column (direction, column name)
1649 group       index grouping property (direction, column name)
1650 filter      properties to filter the index on
1651 filterspec  values to filter the index on
1652 search_text text to perform a full-text search on for an index
1653 =========== ============================================================
1655 There are several methods available on the request variable:
1657 =============== ========================================================
1658 Method          Description
1659 =============== ========================================================
1660 description     render a description of the request - handle for the
1661                 page title
1662 indexargs_form  render the current index args as form elements
1663 indexargs_url   render the current index args as a URL
1664 base_javascript render some javascript that is used by other components
1665                 of the templating
1666 batch           run the current index args through a filter and return a
1667                 list of items (see `hyperdb item wrapper`_, and
1668                 `batching`_)
1669 =============== ========================================================
1671 The form variable
1672 :::::::::::::::::
1674 The form variable is a bit special because it's actually a python
1675 FieldStorage object. That means that you have two ways to access its
1676 contents. For example, to look up the CGI form value for the variable
1677 "name", use the path expression::
1679    request/form/name/value
1681 or the python expression::
1683    python:request.form['name'].value
1685 Note the "item" access used in the python case, and also note the
1686 explicit "value" attribute we have to access. That's because the form
1687 variables are stored as MiniFieldStorages. If there's more than one
1688 "name" value in the form, then the above will break since
1689 ``request/form/name`` is actually a *list* of MiniFieldStorages. So it's
1690 best to know beforehand what you're dealing with.
1693 The db variable
1694 ~~~~~~~~~~~~~~~
1696 Note: this is implemented by the ``roundup.cgi.templating.HTMLDatabase``
1697 class.
1699 Allows access to all hyperdb classes as attributes of this variable. If
1700 you want access to the "user" class, for example, you would use::
1702   db/user
1703   python:db.user
1705 Also, the current id of the current user is available as
1706 ``db.getuid()``. This isn't so useful in templates (where you have
1707 ``request/user``), but it can be useful in detectors or interfaces.
1709 The access results in a `hyperdb class wrapper`_.
1712 The templates variable
1713 ~~~~~~~~~~~~~~~~~~~~~~
1715 Note: this is implemented by the ``roundup.cgi.templating.Templates``
1716 class.
1718 This variable doesn't have any useful methods defined. It supports being
1719 used in expressions to access the templates, and consequently the
1720 template macros. You may access the templates using the following path
1721 expression::
1723    templates/name
1725 or the python expression::
1727    templates[name]
1729 where "name" is the name of the template you wish to access. The
1730 template has one useful attribute, namely "macros". To access a specific
1731 macro (called "macro_name"), use the path expression::
1733    templates/name/macros/macro_name
1735 or the python expression::
1737    templates[name].macros[macro_name]
1740 The utils variable
1741 ~~~~~~~~~~~~~~~~~~
1743 Note: this is implemented by the
1744 ``roundup.cgi.templating.TemplatingUtils`` class, but it may be extended
1745 as described below.
1747 =============== ========================================================
1748 Method          Description
1749 =============== ========================================================
1750 Batch           return a batch object using the supplied list
1751 =============== ========================================================
1753 You may add additional utility methods by writing them in your tracker
1754 ``interfaces.py`` module's ``TemplatingUtils`` class. See `adding a time
1755 log to your issues`_ for an example. The TemplatingUtils class itself
1756 will have a single attribute, ``client``, which may be used to access
1757 the ``client.db`` when you need to perform arbitrary database queries.
1759 Batching
1760 ::::::::
1762 Use Batch to turn a list of items, or item ids of a given class, into a
1763 series of batches. Its usage is::
1765     python:utils.Batch(sequence, size, start, end=0, orphan=0,
1766     overlap=0)
1768 or, to get the current index batch::
1770     request/batch
1772 The parameters are:
1774 ========= ==============================================================
1775 Parameter  Usage
1776 ========= ==============================================================
1777 sequence  a list of HTMLItems
1778 size      how big to make the sequence.
1779 start     where to start (0-indexed) in the sequence.
1780 end       where to end (0-indexed) in the sequence.
1781 orphan    if the next batch would contain less items than this value,
1782           then it is combined with this batch
1783 overlap   the number of items shared between adjacent batches
1784 ========= ==============================================================
1786 All of the parameters are assigned as attributes on the batch object. In
1787 addition, it has several more attributes:
1789 =============== ========================================================
1790 Attribute       Description
1791 =============== ========================================================
1792 start           indicates the start index of the batch. *Note: unlike
1793                 the argument, is a 1-based index (I know, lame)*
1794 first           indicates the start index of the batch *as a 0-based
1795                 index*
1796 length          the actual number of elements in the batch
1797 sequence_length the length of the original, unbatched, sequence.
1798 =============== ========================================================
1800 And several methods:
1802 =============== ========================================================
1803 Method          Description
1804 =============== ========================================================
1805 previous        returns a new Batch with the previous batch settings
1806 next            returns a new Batch with the next batch settings
1807 propchanged     detect if the named property changed on the current item
1808                 when compared to the last item
1809 =============== ========================================================
1811 An example of batching::
1813  <table class="otherinfo">
1814   <tr><th colspan="4" class="header">Existing Keywords</th></tr>
1815   <tr tal:define="keywords db/keyword/list"
1816       tal:repeat="start python:range(0, len(keywords), 4)">
1817    <td tal:define="batch python:utils.Batch(keywords, 4, start)"
1818        tal:repeat="keyword batch" tal:content="keyword/name">
1819        keyword here</td>
1820   </tr>
1821  </table>
1823 ... which will produce a table with four columns containing the items of
1824 the "keyword" class (well, their "name" anyway).
1826 Displaying Properties
1827 ---------------------
1829 Properties appear in the user interface in three contexts: in indices,
1830 in editors, and as search arguments. For each type of property, there
1831 are several display possibilities. For example, in an index view, a
1832 string property may just be printed as a plain string, but in an editor
1833 view, that property may be displayed in an editable field.
1836 Index Views
1837 -----------
1839 This is one of the class context views. It is also the default view for
1840 classes. The template used is "*classname*.index".
1843 Index View Specifiers
1844 ~~~~~~~~~~~~~~~~~~~~~
1846 An index view specifier (URL fragment) looks like this (whitespace has
1847 been added for clarity)::
1849      /issue?status=unread,in-progress,resolved&
1850             topic=security,ui&
1851             :group=+priority&
1852             :sort==activity&
1853             :filters=status,topic&
1854             :columns=title,status,fixer
1856 The index view is determined by two parts of the specifier: the layout
1857 part and the filter part. The layout part consists of the query
1858 parameters that begin with colons, and it determines the way that the
1859 properties of selected items are displayed. The filter part consists of
1860 all the other query parameters, and it determines the criteria by which
1861 items are selected for display. The filter part is interactively
1862 manipulated with the form widgets displayed in the filter section. The
1863 layout part is interactively manipulated by clicking on the column
1864 headings in the table.
1866 The filter part selects the union of the sets of items with values
1867 matching any specified Link properties and the intersection of the sets
1868 of items with values matching any specified Multilink properties.
1870 The example specifies an index of "issue" items. Only items with a
1871 "status" of either "unread" or "in-progress" or "resolved" are
1872 displayed, and only items with "topic" values including both "security"
1873 and "ui" are displayed. The items are grouped by priority, arranged in
1874 ascending order; and within groups, sorted by activity, arranged in
1875 descending order. The filter section shows filters for the "status" and
1876 "topic" properties, and the table includes columns for the "title",
1877 "status", and "fixer" properties.
1879 Searching Views
1880 ---------------
1882 Note: if you add a new column to the ``:columns`` form variable
1883       potentials then you will need to add the column to the appropriate
1884       `index views`_ template so that it is actually displayed.
1886 This is one of the class context views. The template used is typically
1887 "*classname*.search". The form on this page should have "search" as its
1888 ``@action`` variable. The "search" action:
1890 - sets up additional filtering, as well as performing indexed text
1891   searching
1892 - sets the ``:filter`` variable correctly
1893 - saves the query off if ``:query_name`` is set.
1895 The search page should lay out any fields that you wish to allow the
1896 user to search on. If your schema contains a large number of properties,
1897 you should be wary of making all of those properties available for
1898 searching, as this can cause confusion. If the additional properties are
1899 Strings, consider having their value indexed, and then they will be
1900 searchable using the full text indexed search. This is both faster, and
1901 more useful for the end user.
1903 The two special form values on search pages which are handled by the
1904 "search" action are:
1906 :search_text
1907   Text with which to perform a search of the text index. Results from
1908   that search will be used to limit the results of other filters (using
1909   an intersection operation)
1910 :query_name
1911   If supplied, the search parameters (including :search_text) will be
1912   saved off as a the query item and registered against the user's
1913   queries property. Note that the *classic* template schema has this
1914   ability, but the *minimal* template schema does not.
1917 Item Views
1918 ----------
1920 The basic view of a hyperdb item is provided by the "*classname*.item"
1921 template. It generally has three sections; an "editor", a "spool" and a
1922 "history" section.
1925 Editor Section
1926 ~~~~~~~~~~~~~~
1928 The editor section is used to manipulate the item - it may be a static
1929 display if the user doesn't have permission to edit the item.
1931 Here's an example of a basic editor template (this is the default
1932 "classic" template issue item edit form - from the "issue.item.html"
1933 template)::
1935  <table class="form">
1936  <tr>
1937   <th>Title</th>
1938   <td colspan="3" tal:content="structure python:context.title.field(size=60)">title</td>
1939  </tr>
1940  
1941  <tr>
1942   <th>Priority</th>
1943   <td tal:content="structure context/priority/menu">priority</td>
1944   <th>Status</th>
1945   <td tal:content="structure context/status/menu">status</td>
1946  </tr>
1947  
1948  <tr>
1949   <th>Superseder</th>
1950   <td>
1951    <span tal:replace="structure python:context.superseder.field(showid=1, size=20)" />
1952    <span tal:replace="structure python:db.issue.classhelp('id,title')" />
1953    <span tal:condition="context/superseder">
1954     <br>View: <span tal:replace="structure python:context.superseder.link(showid=1)" />
1955    </span>
1956   </td>
1957   <th>Nosy List</th>
1958   <td>
1959    <span tal:replace="structure context/nosy/field" />
1960    <span tal:replace="structure python:db.user.classhelp('username,realname,address,phone')" />
1961   </td>
1962  </tr>
1963  
1964  <tr>
1965   <th>Assigned To</th>
1966   <td tal:content="structure context/assignedto/menu">
1967    assignedto menu
1968   </td>
1969   <td>&nbsp;</td>
1970   <td>&nbsp;</td>
1971  </tr>
1972  
1973  <tr>
1974   <th>Change Note</th>
1975   <td colspan="3">
1976    <textarea name=":note" wrap="hard" rows="5" cols="60"></textarea>
1977   </td>
1978  </tr>
1979  
1980  <tr>
1981   <th>File</th>
1982   <td colspan="3"><input type="file" name=":file" size="40"></td>
1983  </tr>
1984  
1985  <tr>
1986   <td>&nbsp;</td>
1987   <td colspan="3" tal:content="structure context/submit">
1988    submit button will go here
1989   </td>
1990  </tr>
1991  </table>
1994 When a change is submitted, the system automatically generates a message
1995 describing the changed properties. As shown in the example, the editor
1996 template can use the ":note" and ":file" fields, which are added to the
1997 standard changenote message generated by Roundup.
2000 Form values
2001 :::::::::::
2003 We have a number of ways to pull properties out of the form in order to
2004 meet the various needs of:
2006 1. editing the current item (perhaps an issue item)
2007 2. editing information related to the current item (eg. messages or
2008    attached files)
2009 3. creating new information to be linked to the current item (eg. time
2010    spent on an issue)
2012 In the following, ``<bracketed>`` values are variable, ":" may be one of
2013 ":" or "@", and other text ("required") is fixed.
2015 Properties are specified as form variables:
2017 ``<propname>``
2018   property on the current context item
2020 ``<designator>:<propname>``
2021   property on the indicated item (for editing related information)
2023 ``<classname>-<N>:<propname>``
2024   property on the Nth new item of classname (generally for creating new
2025   items to attach to the current item)
2027 Once we have determined the "propname", we check to see if it is one of
2028 the special form values:
2030 ``@required``
2031   The named property values must be supplied or a ValueError will be
2032   raised.
2034 ``@remove@<propname>=id(s)``
2035   The ids will be removed from the multilink property.
2037 ``:add:<propname>=id(s)``
2038   The ids will be added to the multilink property.
2040 ``:link:<propname>=<designator>``
2041   Used to add a link to new items created during edit. These are
2042   collected and returned in ``all_links``. This will result in an
2043   additional linking operation (either Link set or Multilink append)
2044   after the edit/create is done using ``all_props`` in ``_editnodes``.
2045   The <propname> on the current item will be set/appended the id of the
2046   newly created item of class <designator> (where <designator> must be
2047   <classname>-<N>).
2049 Any of the form variables may be prefixed with a classname or
2050 designator.
2052 Two special form values are supported for backwards compatibility:
2054 ``:note``
2055   create a message (with content, author and date), linked to the
2056   context item. This is ALWAYS designated "msg-1".
2057 ``:file``
2058   create a file, attached to the current item and any message created by
2059   :note. This is ALWAYS designated "file-1".
2062 Spool Section
2063 ~~~~~~~~~~~~~
2065 The spool section lists related information like the messages and files
2066 of an issue.
2068 TODO
2071 History Section
2072 ~~~~~~~~~~~~~~~
2074 The final section displayed is the history of the item - its database
2075 journal. This is generally generated with the template::
2077  <tal:block tal:replace="structure context/history" />
2079 *To be done:*
2081 *The actual history entries of the item may be accessed for manual
2082 templating through the "journal" method of the item*::
2084  <tal:block tal:repeat="entry context/journal">
2085   a journal entry
2086  </tal:block>
2088 *where each journal entry is an HTMLJournalEntry.*
2090 Defining new web actions
2091 ------------------------
2093 You may define new actions to be triggered by the ``@action`` form variable.
2094 These are added to the tracker ``interfaces.py`` as ``Action`` classes that get
2095 called by the the ``Client`` class.
2097 Adding action classes takes three steps; first you `define the new
2098 action class`_, then you `register the action class`_ with the cgi
2099 interface so it may be triggered by the ``@action`` form variable.
2100 Finally you `use the new action`_ in your HTML form.
2102 See "`setting up a "wizard" (or "druid") for controlled adding of
2103 issues`_" for an example.
2106 Define the new action class
2107 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
2109 The action classes have the following interface::
2111  class MyAction(Action):
2112      def handle(self):
2113          ''' Perform some action. No return value is required.
2114          '''
2116 The *self.client* attribute is an instance of your tracker ``instance.Client``
2117 class - thus it's mostly implemented by ``roundup.cgi.client.Client``. See the
2118 docstring of that class for details of what it can do.
2120 The method will typically check the ``self.form`` variable's contents.
2121 It may then:
2123 - add information to ``self.client.ok_message`` or ``self.client.error_message``
2124 - change the ``self.client.template`` variable to alter what the user will see
2125   next
2126 - raise Unauthorised, SendStaticFile, SendFile, NotFound or Redirect
2127   exceptions (import them from roundup.cgi.exceptions)
2130 Register the action class
2131 ~~~~~~~~~~~~~~~~~~~~~~~~~~
2133 The class is now written, but isn't available to the user until you add it to
2134 the ``instance.Client`` class ``actions`` variable, like so::
2136     actions = client.Client.actions + (
2137         ('myaction', myActionClass),
2138     )
2140 This maps the action name "myaction" to the action class we defined.
2142 Use the new action
2143 ~~~~~~~~~~~~~~~~~~
2145 In your HTML form, add a hidden form element like so::
2147   <input type="hidden" name="@action" value="myaction">
2149 where "myaction" is the name you registered in the previous step.
2151 Actions may return content to the user
2152 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
2154 Actions generally perform some database manipulation and then pass control
2155 on to the rendering of a template in the current context (see `Determining
2156 web context`_ for how that works.) Some actions will want to generate the
2157 actual content returned to the user. Action methods may return their own
2158 content string to be displayed to the user, overriding the templating step.
2159 In this situation, we assume that the content is HTML by default. You may
2160 override the content type indicated to the user by calling ``setHeader``::
2162    self.client.setHeader('Content-Type', 'text/csv')
2164 This example indicates that the value sent back to the user is actually
2165 comma-separated value content (eg. something to be loaded into a
2166 spreadsheet or database).
2169 Examples
2170 ========
2172 .. contents::
2173    :local:
2174    :depth: 1
2177 Adding a new field to the classic schema
2178 ----------------------------------------
2180 This example shows how to add a new constrained property (i.e. a
2181 selection of distinct values) to your tracker.
2184 Introduction
2185 ~~~~~~~~~~~~
2187 To make the classic schema of roundup useful as a TODO tracking system
2188 for a group of systems administrators, it needed an extra data field per
2189 issue: a category.
2191 This would let sysadmins quickly list all TODOs in their particular area
2192 of interest without having to do complex queries, and without relying on
2193 the spelling capabilities of other sysadmins (a losing proposition at
2194 best).
2197 Adding a field to the database
2198 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
2200 This is the easiest part of the change. The category would just be a
2201 plain string, nothing fancy. To change what is in the database you need
2202 to add some lines to the ``open()`` function in ``dbinit.py``. Under the
2203 comment::
2205     # add any additional database schema configuration here
2207 add::
2209     category = Class(db, "category", name=String())
2210     category.setkey("name")
2212 Here we are setting up a chunk of the database which we are calling
2213 "category". It contains a string, which we are refering to as "name" for
2214 lack of a more imaginative title. (Since "name" is one of the properties
2215 that Roundup looks for on items if you do not set a key for them, it's
2216 probably a good idea to stick with it for new classes if at all
2217 appropriate.) Then we are setting the key of this chunk of the database
2218 to be that "name". This is equivalent to an index for database types.
2219 This also means that there can only be one category with a given name.
2221 Adding the above lines allows us to create categories, but they're not
2222 tied to the issues that we are going to be creating. It's just a list of
2223 categories off on its own, which isn't much use. We need to link it in
2224 with the issues. To do that, find the lines in the ``open()`` function
2225 in ``dbinit.py`` which set up the "issue" class, and then add a link to
2226 the category::
2228     issue = IssueClass(db, "issue", ... ,
2229         category=Multilink("category"), ... )
2231 The ``Multilink()`` means that each issue can have many categories. If
2232 you were adding something with a one-to-one relationship to issues (such
2233 as the "assignedto" property), use ``Link()`` instead.
2235 That is all you need to do to change the schema. The rest of the effort
2236 is fiddling around so you can actually use the new category.
2239 Populating the new category class
2240 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
2242 If you haven't initialised the database with the roundup-admin
2243 "initialise" command, then you can add the following to the tracker
2244 ``dbinit.py`` in the ``init()`` function under the comment::
2246     # add any additional database create steps here - but only if you
2247     # haven't initialised the database with the admin "initialise" command
2249 Add::
2251      category = db.getclass('category')
2252      category.create(name="scipy", order="1")
2253      category.create(name="chaco", order="2")
2254      category.create(name="weave", order="3")
2256 If the database has already been initalised, then you need to use the
2257 ``roundup-admin`` tool::
2259      % roundup-admin -i <tracker home>
2260      Roundup <version> ready for input.
2261      Type "help" for help.
2262      roundup> create category name=scipy order=1
2263      1
2264      roundup> create category name=chaco order=1
2265      2
2266      roundup> create category name=weave order=1
2267      3
2268      roundup> exit...
2269      There are unsaved changes. Commit them (y/N)? y
2271 TODO: explain why order=1 in each case. Also, does key get set to "name"
2272 automatically when added via roundup-admin?
2275 Setting up security on the new objects
2276 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
2278 By default only the admin user can look at and change objects. This
2279 doesn't suit us, as we want any user to be able to create new categories
2280 as required, and obviously everyone needs to be able to view the
2281 categories of issues for it to be useful.
2283 We therefore need to change the security of the category objects. This
2284 is also done in the ``open()`` function of ``dbinit.py``.
2286 There are currently two loops which set up permissions and then assign
2287 them to various roles. Simply add the new "category" to both lists::
2289     # new permissions for this schema
2290     for cl in 'issue', 'file', 'msg', 'user', 'category':
2291         db.security.addPermission(name="Edit", klass=cl,
2292             description="User is allowed to edit "+cl)
2293         db.security.addPermission(name="View", klass=cl,
2294             description="User is allowed to access "+cl)
2296     # Assign the access and edit permissions for issue, file and message
2297     # to regular users now
2298     for cl in 'issue', 'file', 'msg', 'category':
2299         p = db.security.getPermission('View', cl)
2300         db.security.addPermissionToRole('User', p)
2301         p = db.security.getPermission('Edit', cl)
2302         db.security.addPermissionToRole('User', p)
2304 So you are in effect doing the following (with 'cl' substituted by its
2305 value)::
2307     db.security.addPermission(name="Edit", klass='category',
2308         description="User is allowed to edit "+'category')
2309     db.security.addPermission(name="View", klass='category',
2310         description="User is allowed to access "+'category')
2312 which is creating two permission types; that of editing and viewing
2313 "category" objects respectively. Then the following lines assign those
2314 new permissions to the "User" role, so that normal users can view and
2315 edit "category" objects::
2317     p = db.security.getPermission('View', 'category')
2318     db.security.addPermissionToRole('User', p)
2320     p = db.security.getPermission('Edit', 'category')
2321     db.security.addPermissionToRole('User', p)
2323 This is all the work that needs to be done for the database. It will
2324 store categories, and let users view and edit them. Now on to the
2325 interface stuff.
2328 Changing the web left hand frame
2329 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
2331 We need to give the users the ability to create new categories, and the
2332 place to put the link to this functionality is in the left hand function
2333 bar, under the "Issues" area. The file that defines how this area looks
2334 is ``html/page``, which is what we are going to be editing next.
2336 If you look at this file you can see that it contains a lot of
2337 "classblock" sections which are chunks of HTML that will be included or
2338 excluded in the output depending on whether the condition in the
2339 classblock is met. Under the end of the classblock for issue is where we
2340 are going to add the category code::
2342   <p class="classblock"
2343      tal:condition="python:request.user.hasPermission('View', 'category')">
2344    <b>Categories</b><br>
2345    <a tal:condition="python:request.user.hasPermission('Edit', 'category')"
2346       href="category?@template=item">New Category<br></a>
2347   </p>
2349 The first two lines is the classblock definition, which sets up a
2350 condition that only users who have "View" permission for the "category"
2351 object will have this section included in their output. Next comes a
2352 plain "Categories" header in bold. Everyone who can view categories will
2353 get that.
2355 Next comes the link to the editing area of categories. This link will
2356 only appear if the condition - that the user has "Edit" permissions for
2357 the "category" objects - is matched. If they do have permission then
2358 they will get a link to another page which will let the user add new
2359 categories.
2361 Note that if you have permission to *view* but not to *edit* categories,
2362 then all you will see is a "Categories" header with nothing underneath
2363 it. This is obviously not very good interface design, but will do for
2364 now. I just claim that it is so I can add more links in this section
2365 later on. However to fix the problem you could change the condition in
2366 the classblock statement, so that only users with "Edit" permission
2367 would see the "Categories" stuff.
2370 Setting up a page to edit categories
2371 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
2373 We defined code in the previous section which let users with the
2374 appropriate permissions see a link to a page which would let them edit
2375 conditions. Now we have to write that page.
2377 The link was for the *item* template of the *category* object. This
2378 translates into Roundup looking for a file called ``category.item.html``
2379 in the ``html`` tracker directory. This is the file that we are going to
2380 write now.
2382 First we add an info tag in a comment which doesn't affect the outcome
2383 of the code at all, but is useful for debugging. If you load a page in a
2384 browser and look at the page source, you can see which sections come
2385 from which files by looking for these comments::
2387     <!-- category.item -->
2389 Next we need to add in the METAL macro stuff so we get the normal page
2390 trappings::
2392  <tal:block metal:use-macro="templates/page/macros/icing">
2393   <title metal:fill-slot="head_title">Category editing</title>
2394   <td class="page-header-top" metal:fill-slot="body_title">
2395    <h2>Category editing</h2>
2396   </td>
2397   <td class="content" metal:fill-slot="content">
2399 Next we need to setup up a standard HTML form, which is the whole
2400 purpose of this file. We link to some handy javascript which sends the
2401 form through only once. This is to stop users hitting the send button
2402 multiple times when they are impatient and thus having the form sent
2403 multiple times::
2405     <form method="POST" onSubmit="return submit_once()"
2406           enctype="multipart/form-data">
2408 Next we define some code which sets up the minimum list of fields that
2409 we require the user to enter. There will be only one field - "name" - so
2410 they better put something in it, otherwise the whole form is pointless::
2412     <input type="hidden" name="@required" value="name">
2414 To get everything to line up properly we will put everything in a table,
2415 and put a nice big header on it so the user has an idea what is
2416 happening::
2418     <table class="form">
2419      <tr><th class="header" colspan="2">Category</th></tr>
2421 Next, we need the field into which the user is going to enter the new
2422 category. The "context.name.field(size=60)" bit tells Roundup to
2423 generate a normal HTML field of size 60, and the contents of that field
2424 will be the "name" variable of the current context (which is
2425 "category"). The upshot of this is that when the user types something in
2426 to the form, a new category will be created with that name::
2428     <tr>
2429      <th>Name</th>
2430      <td tal:content="structure python:context.name.field(size=60)">
2431      name</td>
2432     </tr>
2434 Then a submit button so that the user can submit the new category::
2436     <tr>
2437      <td>&nbsp;</td>
2438      <td colspan="3" tal:content="structure context/submit">
2439       submit button will go here
2440      </td>
2441     </tr>
2443 Finally we finish off the tags we used at the start to do the METAL
2444 stuff::
2446   </td>
2447  </tal:block>
2449 So putting it all together, and closing the table and form we get::
2451  <!-- category.item -->
2452  <tal:block metal:use-macro="templates/page/macros/icing">
2453   <title metal:fill-slot="head_title">Category editing</title>
2454   <td class="page-header-top" metal:fill-slot="body_title">
2455    <h2>Category editing</h2>
2456   </td>
2457   <td class="content" metal:fill-slot="content">
2458    <form method="POST" onSubmit="return submit_once()"
2459          enctype="multipart/form-data">
2461     <table class="form">
2462      <tr><th class="header" colspan="2">Category</th></tr>
2464      <tr>
2465       <th>Name</th>
2466       <td tal:content="structure python:context.name.field(size=60)">
2467       name</td>
2468      </tr>
2470      <tr>
2471       <td>
2472         &nbsp;
2473         <input type="hidden" name="@required" value="name"> 
2474       </td>
2475       <td colspan="3" tal:content="structure context/submit">
2476        submit button will go here
2477       </td>
2478      </tr>
2479     </table>
2480    </form>
2481   </td>
2482  </tal:block>
2484 This is quite a lot to just ask the user one simple question, but there
2485 is a lot of setup for basically one line (the form line) to do its work.
2486 To add another field to "category" would involve one more line (well,
2487 maybe a few extra to get the formatting correct).
2490 Adding the category to the issue
2491 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
2493 We now have the ability to create issues to our heart's content, but
2494 that is pointless unless we can assign categories to issues.  Just like
2495 the ``html/category.item.html`` file was used to define how to add a new
2496 category, the ``html/issue.item.html`` is used to define how a new issue
2497 is created.
2499 Just like ``category.issue.html`` this file defines a form which has a
2500 table to lay things out. It doesn't matter where in the table we add new
2501 stuff, it is entirely up to your sense of aesthetics::
2503    <th>Category</th>
2504    <td><span tal:replace="structure context/category/field" />
2505        <span tal:replace="structure db/category/classhelp" />
2506    </td>
2508 First, we define a nice header so that the user knows what the next
2509 section is, then the middle line does what we are most interested in.
2510 This ``context/category/field`` gets replaced by a field which contains
2511 the category in the current context (the current context being the new
2512 issue).
2514 The classhelp lines generate a link (labelled "list") to a popup window
2515 which contains the list of currently known categories.
2518 Searching on categories
2519 ~~~~~~~~~~~~~~~~~~~~~~~
2521 We can add categories, and create issues with categories. The next
2522 obvious thing that we would like to be able to do, would be to search
2523 for issues based on their category, so that, for example, anyone working
2524 on the web server could look at all issues in the category "Web".
2526 If you look for "Search Issues" in the 'html/page.html' file, you will
2527 find that it looks something like 
2528 ``<a href="issue?@template=search">Search Issues</a>``. This shows us
2529 that when you click on "Search Issues" it will be looking for a
2530 ``issue.search.html`` file to display. So that is the file that we will
2531 change.
2533 If you look at this file it should be starting to seem familiar, although it
2534 does use some new macros. You can add the new category search code anywhere you
2535 like within that form::
2537   <tr tal:define="name string:category;
2538                   db_klass string:category;
2539                   db_content string:name;">
2540     <th>Priority:</th>
2541     <td metal:use-macro="search_select"></td>
2542     <td metal:use-macro="column_input"></td>
2543     <td metal:use-macro="sort_input"></td>
2544     <td metal:use-macro="group_input"></td>
2545   </tr>
2547 The definitions in the <tr> opening tag are used by the macros:
2549 - search_select expands to a drop-down box with all categories using db_klass
2550   and db_content.
2551 - column_input expands to a checkbox for selecting what columns should be
2552   displayed.
2553 - sort_input expands to a radio button for selecting what property should be
2554   sorted on.
2555 - group_input expands to a radio button for selecting what property should be
2556   group on.
2558 The category search code above would expand to the following::
2560   <tr>
2561     <th>Category:</th>
2562     <td>
2563       <select name="category">
2564         <option value="">don't care</option>
2565         <option value="">------------</option>      
2566         <option value="1">scipy</option>
2567         <option value="2">chaco</option>
2568         <option value="3">weave</option>
2569       </select>
2570     </td>
2571     <td><input type="checkbox" name=":columns" value="category"></td>
2572     <td><input type="radio" name=":sort" value="category"></td>
2573     <td><input type="radio" name=":group" value="category"></td>
2574   </tr>
2576 Adding category to the default view
2577 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
2579 We can now add categories, add issues with categories, and search for
2580 issues based on categories. This is everything that we need to do;
2581 however, there is some more icing that we would like. I think the
2582 category of an issue is important enough that it should be displayed by
2583 default when listing all the issues.
2585 Unfortunately, this is a bit less obvious than the previous steps. The
2586 code defining how the issues look is in ``html/issue.index.html``. This
2587 is a large table with a form down at the bottom for redisplaying and so
2588 forth. 
2590 Firstly we need to add an appropriate header to the start of the table::
2592     <th tal:condition="request/show/category">Category</th>
2594 The *condition* part of this statement is to avoid displaying the
2595 Category column if the user has selected not to see it.
2597 The rest of the table is a loop which will go through every issue that
2598 matches the display criteria. The loop variable is "i" - which means
2599 that every issue gets assigned to "i" in turn.
2601 The new part of code to display the category will look like this::
2603     <td tal:condition="request/show/category"
2604         tal:content="i/category"></td>
2606 The condition is the same as above: only display the condition when the
2607 user hasn't asked for it to be hidden. The next part is to set the
2608 content of the cell to be the category part of "i" - the current issue.
2610 Finally we have to edit ``html/page.html`` again. This time, we need to
2611 tell it that when the user clicks on "Unasigned Issues" or "All Issues",
2612 the category column should be included in the resulting list. If you
2613 scroll down the page file, you can see the links with lots of options.
2614 The option that we are interested in is the ``:columns=`` one which
2615 tells roundup which fields of the issue to display. Simply add
2616 "category" to that list and it all should work.
2619 Adding in state transition control
2620 ----------------------------------
2622 Sometimes tracker admins want to control the states that users may move
2623 issues to. You can do this by following these steps:
2625 1. make "status" a required variable. This is achieved by adding the
2626    following to the top of the form in the ``issue.item.html``
2627    template::
2629      <input type="hidden" name="@required" value="status">
2631    this will force users to select a status.
2633 2. add a Multilink property to the status class::
2635      stat = Class(db, "status", ... , transitions=Multilink('status'),
2636                   ...)
2638    and then edit the statuses already created, either:
2640    a. through the web using the class list -> status class editor, or
2641    b. using the roundup-admin "set" command.
2643 3. add an auditor module ``checktransition.py`` in your tracker's
2644    ``detectors`` directory, for example::
2646      def checktransition(db, cl, nodeid, newvalues):
2647          ''' Check that the desired transition is valid for the "status"
2648              property.
2649          '''
2650          if not newvalues.has_key('status'):
2651              return
2652          current = cl.get(nodeid, 'status')
2653          new = newvalues['status']
2654          if new == current:
2655              return
2656          ok = db.status.get(current, 'transitions')
2657          if new not in ok:
2658              raise ValueError, 'Status not allowed to move from "%s" to "%s"'%(
2659                  db.status.get(current, 'name'), db.status.get(new, 'name'))
2661      def init(db):
2662          db.issue.audit('set', checktransition)
2664 4. in the ``issue.item.html`` template, change the status editing bit
2665    from::
2667     <th>Status</th>
2668     <td tal:content="structure context/status/menu">status</td>
2670    to::
2672     <th>Status</th>
2673     <td>
2674      <select tal:condition="context/id" name="status">
2675       <tal:block tal:define="ok context/status/transitions"
2676                  tal:repeat="state db/status/list">
2677        <option tal:condition="python:state.id in ok"
2678                tal:attributes="
2679                     value state/id;
2680                     selected python:state.id == context.status.id"
2681                tal:content="state/name"></option>
2682       </tal:block>
2683      </select>
2684      <tal:block tal:condition="not:context/id"
2685                 tal:replace="structure context/status/menu" />
2686     </td>
2688    which displays only the allowed status to transition to.
2691 Displaying only message summaries in the issue display
2692 ------------------------------------------------------
2694 Alter the issue.item template section for messages to::
2696  <table class="messages" tal:condition="context/messages">
2697   <tr><th colspan="5" class="header">Messages</th></tr>
2698   <tr tal:repeat="msg context/messages">
2699    <td><a tal:attributes="href string:msg${msg/id}"
2700           tal:content="string:msg${msg/id}"></a></td>
2701    <td tal:content="msg/author">author</td>
2702    <td class="date" tal:content="msg/date/pretty">date</td>
2703    <td tal:content="msg/summary">summary</td>
2704    <td>
2705     <a tal:attributes="href string:?@remove@messages=${msg/id}&@action=edit">
2706     remove</a>
2707    </td>
2708   </tr>
2709  </table>
2711 Restricting the list of users that are assignable to a task
2712 -----------------------------------------------------------
2714 1. In your tracker's "dbinit.py", create a new Role, say "Developer"::
2716      db.security.addRole(name='Developer', description='A developer')
2718 2. Just after that, create a new Permission, say "Fixer", specific to
2719    "issue"::
2721      p = db.security.addPermission(name='Fixer', klass='issue',
2722          description='User is allowed to be assigned to fix issues')
2724 3. Then assign the new Permission to your "Developer" Role::
2726      db.security.addPermissionToRole('Developer', p)
2728 4. In the issue item edit page ("html/issue.item.html" in your tracker
2729    directory), use the new Permission in restricting the "assignedto"
2730    list::
2732     <select name="assignedto">
2733      <option value="-1">- no selection -</option>
2734      <tal:block tal:repeat="user db/user/list">
2735      <option tal:condition="python:user.hasPermission(
2736                                 'Fixer', context._classname)"
2737              tal:attributes="
2738                 value user/id;
2739                 selected python:user.id == context.assignedto"
2740              tal:content="user/realname"></option>
2741      </tal:block>
2742     </select>
2744 For extra security, you may wish to setup an auditor to enforce the
2745 Permission requirement (install this as "assignedtoFixer.py" in your
2746 tracker "detectors" directory)::
2748   def assignedtoMustBeFixer(db, cl, nodeid, newvalues):
2749       ''' Ensure the assignedto value in newvalues is a used with the
2750           Fixer Permission
2751       '''
2752       if not newvalues.has_key('assignedto'):
2753           # don't care
2754           return
2755   
2756       # get the userid
2757       userid = newvalues['assignedto']
2758       if not db.security.hasPermission('Fixer', userid, cl.classname):
2759           raise ValueError, 'You do not have permission to edit %s'%cl.classname
2761   def init(db):
2762       db.issue.audit('set', assignedtoMustBeFixer)
2763       db.issue.audit('create', assignedtoMustBeFixer)
2765 So now, if an edit action attempts to set "assignedto" to a user that
2766 doesn't have the "Fixer" Permission, the error will be raised.
2769 Setting up a "wizard" (or "druid") for controlled adding of issues
2770 ------------------------------------------------------------------
2772 1. Set up the page templates you wish to use for data input. My wizard
2773    is going to be a two-step process: first figuring out what category
2774    of issue the user is submitting, and then getting details specific to
2775    that category. The first page includes a table of help, explaining
2776    what the category names mean, and then the core of the form::
2778     <form method="POST" onSubmit="return submit_once()"
2779           enctype="multipart/form-data">
2780       <input type="hidden" name="@template" value="add_page1">
2781       <input type="hidden" name="@action" value="page1_submit">
2783       <strong>Category:</strong>
2784       <tal:block tal:replace="structure context/category/menu" />
2785       <input type="submit" value="Continue">
2786     </form>
2788    The next page has the usual issue entry information, with the
2789    addition of the following form fragments::
2791     <form method="POST" onSubmit="return submit_once()"
2792           enctype="multipart/form-data"
2793           tal:condition="context/is_edit_ok"
2794           tal:define="cat request/form/category/value">
2796       <input type="hidden" name="@template" value="add_page2">
2797       <input type="hidden" name="@required" value="title">
2798       <input type="hidden" name="category" tal:attributes="value cat">
2799        .
2800        .
2801        .
2802     </form>
2804    Note that later in the form, I test the value of "cat" include form
2805    elements that are appropriate. For exsample::
2807     <tal:block tal:condition="python:cat in '6 10 13 14 15 16 17'.split()">
2808      <tr>
2809       <th>Operating System</th>
2810       <td tal:content="structure context/os/field"></td>
2811      </tr>
2812      <tr>
2813       <th>Web Browser</th>
2814       <td tal:content="structure context/browser/field"></td>
2815      </tr>
2816     </tal:block>
2818    ... the above section will only be displayed if the category is one
2819    of 6, 10, 13, 14, 15, 16 or 17.
2821 3. Determine what actions need to be taken between the pages - these are
2822    usually to validate user choices and determine what page is next. Now encode
2823    those actions in a new ``Action`` class and insert hooks to those actions in
2824    the "actions" attribute on on the ``interfaces.Client`` class, like so (see 
2825    `defining new web actions`_)::
2827     class Page1SubmitAction(Action):
2828         def handle(self):
2829             ''' Verify that the user has selected a category, and then move
2830                 on to page 2.
2831             '''
2832             category = self.form['category'].value
2833             if category == '-1':
2834                 self.error_message.append('You must select a category of report')
2835                 return
2836             # everything's ok, move on to the next page
2837             self.template = 'add_page2'
2839     actions = client.Client.actions + (
2840         ('page1_submit', Page1SubmitAction),
2841     )
2843 4. Use the usual "new" action as the ``@action`` on the final page, and
2844    you're done (the standard context/submit method can do this for you).
2847 Using an external password validation source
2848 --------------------------------------------
2850 We have a centrally-managed password changing system for our users. This
2851 results in a UN*X passwd-style file that we use for verification of
2852 users. Entries in the file consist of ``name:password`` where the
2853 password is encrypted using the standard UN*X ``crypt()`` function (see
2854 the ``crypt`` module in your Python distribution). An example entry
2855 would be::
2857     admin:aamrgyQfDFSHw
2859 Each user of Roundup must still have their information stored in the Roundup
2860 database - we just use the passwd file to check their password. To do this, we
2861 need to override the standard ``verifyPassword`` method defined in
2862 ``roundup.cgi.actions.LoginAction`` and register the new class with our
2863 ``Client`` class in the tracker home ``interfaces.py`` module::
2865     from roundup.cgi.actions import LoginAction    
2867     class ExternalPasswordLoginAction(LoginAction):
2868         def verifyPassword(self, userid, password):
2869             # get the user's username
2870             username = self.db.user.get(userid, 'username')
2872             # the passwords are stored in the "passwd.txt" file in the
2873             # tracker home
2874             file = os.path.join(self.db.config.TRACKER_HOME, 'passwd.txt')
2876             # see if we can find a match
2877             for ent in [line.strip().split(':') for line in
2878                                                 open(file).readlines()]:
2879                 if ent[0] == username:
2880                     return crypt.crypt(password, ent[1][:2]) == ent[1]
2882             # user doesn't exist in the file
2883             return 0
2885     class Client(client.Client):
2886         actions = client.Client.actions + (
2887             ('login', ExternalPasswordLoginAction)
2888         )
2890 What this does is look through the file, line by line, looking for a
2891 name that matches.
2893 We also remove the redundant password fields from the ``user.item``
2894 template.
2897 Adding a "vacation" flag to users for stopping nosy messages
2898 ------------------------------------------------------------
2900 When users go on vacation and set up vacation email bouncing, you'll
2901 start to see a lot of messages come back through Roundup "Fred is on
2902 vacation". Not very useful, and relatively easy to stop.
2904 1. add a "vacation" flag to your users::
2906          user = Class(db, "user",
2907                     username=String(),   password=Password(),
2908                     address=String(),    realname=String(),
2909                     phone=String(),      organisation=String(),
2910                     alternate_addresses=String(),
2911                     roles=String(), queries=Multilink("query"),
2912                     vacation=Boolean())
2914 2. So that users may edit the vacation flags, add something like the
2915    following to your ``user.item`` template::
2917      <tr>
2918       <th>On Vacation</th> 
2919       <td tal:content="structure context/vacation/field">vacation</td> 
2920      </tr> 
2922 3. edit your detector ``nosyreactor.py`` so that the ``nosyreaction()``
2923    consists of::
2925     def nosyreaction(db, cl, nodeid, oldvalues):
2926         # send a copy of all new messages to the nosy list
2927         for msgid in determineNewMessages(cl, nodeid, oldvalues):
2928             try:
2929                 users = db.user
2930                 messages = db.msg
2932                 # figure the recipient ids
2933                 sendto = []
2934                 r = {}
2935                 recipients = messages.get(msgid, 'recipients')
2936                 for recipid in messages.get(msgid, 'recipients'):
2937                     r[recipid] = 1
2939                 # figure the author's id, and indicate they've received
2940                 # the message
2941                 authid = messages.get(msgid, 'author')
2943                 # possibly send the message to the author, as long as
2944                 # they aren't anonymous
2945                 if (db.config.MESSAGES_TO_AUTHOR == 'yes' and
2946                         users.get(authid, 'username') != 'anonymous'):
2947                     sendto.append(authid)
2948                 r[authid] = 1
2950                 # now figure the nosy people who weren't recipients
2951                 nosy = cl.get(nodeid, 'nosy')
2952                 for nosyid in nosy:
2953                     # Don't send nosy mail to the anonymous user (that
2954                     # user shouldn't appear in the nosy list, but just
2955                     # in case they do...)
2956                     if users.get(nosyid, 'username') == 'anonymous':
2957                         continue
2958                     # make sure they haven't seen the message already
2959                     if not r.has_key(nosyid):
2960                         # send it to them
2961                         sendto.append(nosyid)
2962                         recipients.append(nosyid)
2964                 # generate a change note
2965                 if oldvalues:
2966                     note = cl.generateChangeNote(nodeid, oldvalues)
2967                 else:
2968                     note = cl.generateCreateNote(nodeid)
2970                 # we have new recipients
2971                 if sendto:
2972                     # filter out the people on vacation
2973                     sendto = [i for i in sendto 
2974                               if not users.get(i, 'vacation', 0)]
2976                     # map userids to addresses
2977                     sendto = [users.get(i, 'address') for i in sendto]
2979                     # update the message's recipients list
2980                     messages.set(msgid, recipients=recipients)
2982                     # send the message
2983                     cl.send_message(nodeid, msgid, note, sendto)
2984             except roundupdb.MessageSendError, message:
2985                 raise roundupdb.DetectorError, message
2987    Note that this is the standard nosy reaction code, with the small
2988    addition of::
2990     # filter out the people on vacation
2991     sendto = [i for i in sendto if not users.get(i, 'vacation', 0)]
2993    which filters out the users that have the vacation flag set to true.
2996 Adding a time log to your issues
2997 --------------------------------
2999 We want to log the dates and amount of time spent working on issues, and
3000 be able to give a summary of the total time spent on a particular issue.
3002 1. Add a new class to your tracker ``dbinit.py``::
3004     # storage for time logging
3005     timelog = Class(db, "timelog", period=Interval())
3007    Note that we automatically get the date of the time log entry
3008    creation through the standard property "creation".
3010 2. Link to the new class from your issue class (again, in
3011    ``dbinit.py``)::
3013     issue = IssueClass(db, "issue", 
3014                     assignedto=Link("user"), topic=Multilink("keyword"),
3015                     priority=Link("priority"), status=Link("status"),
3016                     times=Multilink("timelog"))
3018    the "times" property is the new link to the "timelog" class.
3020 3. We'll need to let people add in times to the issue, so in the web
3021    interface we'll have a new entry field. This is a special field
3022    because unlike the other fields in the issue.item template, it
3023    affects a different item (a timelog item) and not the template's
3024    item, an issue. We have a special syntax for form fields that affect
3025    items other than the template default item (see the cgi 
3026    documentation on `special form variables`_). In particular, we add a
3027    field to capture a new timelog item's perdiod::
3029     <tr> 
3030      <th>Time Log</th> 
3031      <td colspan=3><input type="text" name="timelog-1@period" /> 
3032       <br />(enter as '3y 1m 4d 2:40:02' or parts thereof) 
3033      </td> 
3034     </tr> 
3035          
3036    and another hidden field that links that new timelog item (new
3037    because it's marked as having id "-1") to the issue item. It looks
3038    like this::
3040      <input type="hidden" name="@link@times" value="timelog-1" />
3042    On submission, the "-1" timelog item will be created and assigned a
3043    real item id. The "times" property of the issue will have the new id
3044    added to it.
3046 4. We want to display a total of the time log times that have been
3047    accumulated for an issue. To do this, we'll need to actually write
3048    some Python code, since it's beyond the scope of PageTemplates to
3049    perform such calculations. We do this by adding a method to the
3050    TemplatingUtils class in our tracker ``interfaces.py`` module::
3052     class TemplatingUtils:
3053         ''' Methods implemented on this class will be available to HTML
3054             templates through the 'utils' variable.
3055         '''
3056         def totalTimeSpent(self, times):
3057             ''' Call me with a list of timelog items (which have an
3058                 Interval "period" property)
3059             '''
3060             total = Interval('0d')
3061             for time in times:
3062                 total += time.period._value
3063             return total
3065    Replace the ``pass`` line if one appears in your TemplatingUtils
3066    class. As indicated in the docstrings, we will be able to access the
3067    ``totalTimeSpent`` method via the ``utils`` variable in our templates.
3069 5. Display the time log for an issue::
3071      <table class="otherinfo" tal:condition="context/times">
3072       <tr><th colspan="3" class="header">Time Log
3073        <tal:block
3074             tal:replace="python:utils.totalTimeSpent(context.times)" />
3075       </th></tr>
3076       <tr><th>Date</th><th>Period</th><th>Logged By</th></tr>
3077       <tr tal:repeat="time context/times">
3078        <td tal:content="time/creation"></td>
3079        <td tal:content="time/period"></td>
3080        <td tal:content="time/creator"></td>
3081       </tr>
3082      </table>
3084    I put this just above the Messages log in my issue display. Note our
3085    use of the ``totalTimeSpent`` method which will total up the times
3086    for the issue and return a new Interval. That will be automatically
3087    displayed in the template as text like "+ 1y 2:40" (1 year, 2 hours
3088    and 40 minutes).
3090 8. If you're using a persistent web server - roundup-server or
3091    mod_python for example - then you'll need to restart that to pick up
3092    the code changes. When that's done, you'll be able to use the new
3093    time logging interface.
3095 Using a UN*X passwd file as the user database
3096 ---------------------------------------------
3098 On some systems the primary store of users is the UN*X passwd file. It
3099 holds information on users such as their username, real name, password
3100 and primary user group.
3102 Roundup can use this store as its primary source of user information,
3103 but it needs additional information too - email address(es), roundup
3104 Roles, vacation flags, roundup hyperdb item ids, etc. Also, "retired"
3105 users must still exist in the user database, unlike some passwd files in
3106 which the users are removed when they no longer have access to a system.
3108 To make use of the passwd file, we therefore synchronise between the two
3109 user stores. We also use the passwd file to validate the user logins, as
3110 described in the previous example, `using an external password
3111 validation source`_. We keep the users lists in sync using a fairly
3112 simple script that runs once a day, or several times an hour if more
3113 immediate access is needed. In short, it:
3115 1. parses the passwd file, finding usernames, passwords and real names,
3116 2. compares that list to the current roundup user list:
3118    a. entries no longer in the passwd file are *retired*
3119    b. entries with mismatching real names are *updated*
3120    c. entries only exist in the passwd file are *created*
3122 3. send an email to administrators to let them know what's been done.
3124 The retiring and updating are simple operations, requiring only a call
3125 to ``retire()`` or ``set()``. The creation operation requires more
3126 information though - the user's email address and their roundup Roles.
3127 We're going to assume that the user's email address is the same as their
3128 login name, so we just append the domain name to that. The Roles are
3129 determined using the passwd group identifier - mapping their UN*X group
3130 to an appropriate set of Roles.
3132 The script to perform all this, broken up into its main components, is
3133 as follows. Firstly, we import the necessary modules and open the
3134 tracker we're to work on::
3136     import sys, os, smtplib
3137     from roundup import instance, date
3139     # open the tracker
3140     tracker_home = sys.argv[1]
3141     tracker = instance.open(tracker_home)
3143 Next we read in the *passwd* file from the tracker home::
3145     # read in the users
3146     file = os.path.join(tracker_home, 'users.passwd')
3147     users = [x.strip().split(':') for x in open(file).readlines()]
3149 Handle special users (those to ignore in the file, and those who don't
3150 appear in the file)::
3152     # users to not keep ever, pre-load with the users I know aren't
3153     # "real" users
3154     ignore = ['ekmmon', 'bfast', 'csrmail']
3156     # users to keep - pre-load with the roundup-specific users
3157     keep = ['comment_pool', 'network_pool', 'admin', 'dev-team',
3158             'cs_pool', 'anonymous', 'system_pool', 'automated']
3160 Now we map the UN*X group numbers to the Roles that users should have::
3162     roles = {
3163      '501': 'User,Tech',  # tech
3164      '502': 'User',       # finance
3165      '503': 'User,CSR',   # customer service reps
3166      '504': 'User',       # sales
3167      '505': 'User',       # marketing
3168     }
3170 Now we do all the work. Note that the body of the script (where we have
3171 the tracker database open) is wrapped in a ``try`` / ``finally`` clause,
3172 so that we always close the database cleanly when we're finished. So, we
3173 now do all the work::
3175     # open the database
3176     db = tracker.open('admin')
3177     try:
3178         # store away messages to send to the tracker admins
3179         msg = []
3181         # loop over the users list read in from the passwd file
3182         for user,passw,uid,gid,real,home,shell in users:
3183             if user in ignore:
3184                 # this user shouldn't appear in our tracker
3185                 continue
3186             keep.append(user)
3187             try:
3188                 # see if the user exists in the tracker
3189                 uid = db.user.lookup(user)
3191                 # yes, they do - now check the real name for correctness
3192                 if real != db.user.get(uid, 'realname'):
3193                     db.user.set(uid, realname=real)
3194                     msg.append('FIX %s - %s'%(user, real))
3195             except KeyError:
3196                 # nope, the user doesn't exist
3197                 db.user.create(username=user, realname=real,
3198                     address='%s@ekit-inc.com'%user, roles=roles[gid])
3199                 msg.append('ADD %s - %s (%s)'%(user, real, roles[gid]))
3201         # now check that all the users in the tracker are also in our
3202         # "keep" list - retire those who aren't
3203         for uid in db.user.list():
3204             user = db.user.get(uid, 'username')
3205             if user not in keep:
3206                 db.user.retire(uid)
3207                 msg.append('RET %s'%user)
3209         # if we did work, then send email to the tracker admins
3210         if msg:
3211             # create the email
3212             msg = '''Subject: %s user database maintenance
3214             %s
3215             '''%(db.config.TRACKER_NAME, '\n'.join(msg))
3217             # send the email
3218             smtp = smtplib.SMTP(db.config.MAILHOST)
3219             addr = db.config.ADMIN_EMAIL
3220             smtp.sendmail(addr, addr, msg)
3222         # now we're done - commit the changes
3223         db.commit()
3224     finally:
3225         # always close the database cleanly
3226         db.close()
3228 And that's it!
3231 Using an LDAP database for user information
3232 -------------------------------------------
3234 A script that reads users from an LDAP store using
3235 http://python-ldap.sf.net/ and then compares the list to the users in the
3236 roundup user database would be pretty easy to write. You'd then have it run
3237 once an hour / day (or on demand if you can work that into your LDAP store
3238 workflow). See the example `Using a UN*X passwd file as the user database`_
3239 for more information about doing this.
3241 To authenticate off the LDAP store (rather than using the passwords in the
3242 roundup user database) you'd use the same python-ldap module inside an
3243 extension to the cgi interface. You'd do this by overriding the method called
3244 "verifyPassword" on the LoginAction class in your tracker's interfaces.py
3245 module (see `using an external password validation source`_). The method is
3246 implemented by default as::
3248     def verifyPassword(self, userid, password):
3249         ''' Verify the password that the user has supplied
3250         '''
3251         stored = self.db.user.get(self.userid, 'password')
3252         if password == stored:
3253             return 1
3254         if not password and not stored:
3255             return 1
3256         return 0
3258 So you could reimplement this as something like::
3260     def verifyPassword(self, userid, password):
3261         ''' Verify the password that the user has supplied
3262         '''
3263         # look up some unique LDAP information about the user
3264         username = self.db.user.get(self.userid, 'username')
3265         # now verify the password supplied against the LDAP store
3268 Enabling display of either message summaries or the entire messages
3269 -------------------------------------------------------------------
3271 This is pretty simple - all we need to do is copy the code from the
3272 example `displaying only message summaries in the issue display`_ into
3273 our template alongside the summary display, and then introduce a switch
3274 that shows either one or the other. We'll use a new form variable,
3275 ``@whole_messages`` to achieve this::
3277  <table class="messages" tal:condition="context/messages">
3278   <tal:block tal:condition="not:request/form/@whole_messages/value | python:0">
3279    <tr><th colspan="3" class="header">Messages</th>
3280        <th colspan="2" class="header">
3281          <a href="?@whole_messages=yes">show entire messages</a>
3282        </th>
3283    </tr>
3284    <tr tal:repeat="msg context/messages">
3285     <td><a tal:attributes="href string:msg${msg/id}"
3286            tal:content="string:msg${msg/id}"></a></td>
3287     <td tal:content="msg/author">author</td>
3288     <td class="date" tal:content="msg/date/pretty">date</td>
3289     <td tal:content="msg/summary">summary</td>
3290     <td>
3291      <a tal:attributes="href string:?@remove@messages=${msg/id}&@action=edit">remove</a>
3292     </td>
3293    </tr>
3294   </tal:block>
3296   <tal:block tal:condition="request/form/@whole_messages/value | python:0">
3297    <tr><th colspan="2" class="header">Messages</th>
3298        <th class="header">
3299          <a href="?@whole_messages=">show only summaries</a>
3300        </th>
3301    </tr>
3302    <tal:block tal:repeat="msg context/messages">
3303     <tr>
3304      <th tal:content="msg/author">author</th>
3305      <th class="date" tal:content="msg/date/pretty">date</th>
3306      <th style="text-align: right">
3307       (<a tal:attributes="href string:?@remove@messages=${msg/id}&@action=edit">remove</a>)
3308      </th>
3309     </tr>
3310     <tr><td colspan="3" tal:content="msg/content"></td></tr>
3311    </tal:block>
3312   </tal:block>
3313  </table>
3316 Blocking issues that depend on other issues
3317 -------------------------------------------
3319 We needed the ability to mark certain issues as "blockers" - that is,
3320 they can't be resolved until another issue (the blocker) they rely on is
3321 resolved. To achieve this:
3323 1. Create a new property on the issue Class,
3324    ``blockers=Multilink("issue")``. Edit your tracker's dbinit.py file.
3325    Where the "issue" class is defined, something like::
3327     issue = IssueClass(db, "issue", 
3328                     assignedto=Link("user"), topic=Multilink("keyword"),
3329                     priority=Link("priority"), status=Link("status"))
3331    add the blockers entry like so::
3333     issue = IssueClass(db, "issue", 
3334                     blockers=Multilink("issue"),
3335                     assignedto=Link("user"), topic=Multilink("keyword"),
3336                     priority=Link("priority"), status=Link("status"))
3338 2. Add the new "blockers" property to the issue.item edit page, using
3339    something like::
3341     <th>Waiting On</th>
3342     <td>
3343      <span tal:replace="structure python:context.blockers.field(showid=1,
3344                                   size=20)" />
3345      <span tal:replace="structure python:db.issue.classhelp('id,title')" />
3346      <span tal:condition="context/blockers"
3347            tal:repeat="blk context/blockers">
3348       <br>View: <a tal:attributes="href string:issue${blk/id}"
3349                    tal:content="blk/id"></a>
3350      </span>
3352    You'll need to fiddle with your item page layout to find an
3353    appropriate place to put it - I'll leave that fun part up to you.
3354    Just make sure it appears in the first table, possibly somewhere near
3355    the "superseders" field.
3357 3. Create a new detector module (attached) which enforces the rules:
3359    - issues may not be resolved if they have blockers
3360    - when a blocker is resolved, it's removed from issues it blocks
3362    The contents of the detector should be something like this::
3364     def blockresolution(db, cl, nodeid, newvalues):
3365         ''' If the issue has blockers, don't allow it to be resolved.
3366         '''
3367         if nodeid is None:
3368             blockers = []
3369         else:
3370             blockers = cl.get(nodeid, 'blockers')
3371         blockers = newvalues.get('blockers', blockers)
3373         # don't do anything if there's no blockers or the status hasn't
3374         # changed
3375         if not blockers or not newvalues.has_key('status'):
3376             return
3378         # get the resolved state ID
3379         resolved_id = db.status.lookup('resolved')
3381         # format the info
3382         u = db.config.TRACKER_WEB
3383         s = ', '.join(['<a href="%sissue%s">%s</a>'%(
3384                         u,id,id) for id in blockers])
3385         if len(blockers) == 1:
3386             s = 'issue %s is'%s
3387         else:
3388             s = 'issues %s are'%s
3390         # ok, see if we're trying to resolve
3391         if newvalues['status'] == resolved_id:
3392             raise ValueError, "This issue can't be resolved until %s resolved."%s
3394     def resolveblockers(db, cl, nodeid, newvalues):
3395         ''' When we resolve an issue that's a blocker, remove it from the
3396             blockers list of the issue(s) it blocks.
3397         '''
3398         if not newvalues.has_key('status'):
3399             return
3401         # get the resolved state ID
3402         resolved_id = db.status.lookup('resolved')
3404         # interesting?
3405         if newvalues['status'] != resolved_id:
3406             return
3408         # yes - find all the blocked issues, if any, and remove me from
3409         # their blockers list
3410         issues = cl.find(blockers=nodeid)
3411         for issueid in issues:
3412             blockers = cl.get(issueid, 'blockers')
3413             if nodeid in blockers:
3414                 blockers.remove(nodeid)
3415                 cl.set(issueid, blockers=blockers)
3418     def init(db):
3419         # might, in an obscure situation, happen in a create
3420         db.issue.audit('create', blockresolution)
3421         db.issue.audit('set', blockresolution)
3423         # can only happen on a set
3424         db.issue.react('set', resolveblockers)
3426    Put the above code in a file called "blockers.py" in your tracker's
3427    "detectors" directory.
3429 4. Finally, and this is an optional step, modify the tracker web page
3430    URLs so they filter out issues with any blockers. You do this by
3431    adding an additional filter on "blockers" for the value "-1". For
3432    example, the existing "Show All" link in the "page" template (in the
3433    tracker's "html" directory) looks like this::
3435      <a href="issue?:sort=-activity&:group=priority&:filter=status&:columns=id,activity,title,creator,assignedto,status&status=-1,1,2,3,4,5,6,7">Show All</a><br>
3437    modify it to add the "blockers" info to the URL (note, both the
3438    ":filter" *and* "blockers" values must be specified)::
3440      <a href="issue?:sort=-activity&:group=priority&:filter=status,blockers&blockers=-1&:columns=id,activity,title,creator,assignedto,status&status=-1,1,2,3,4,5,6,7">Show All</a><br>
3442 That's it. You should now be able to set blockers on your issues. Note
3443 that if you want to know whether an issue has any other issues dependent
3444 on it (i.e. it's in their blockers list) you can look at the journal
3445 history at the bottom of the issue page - look for a "link" event to
3446 another issue's "blockers" property.
3448 Add users to the nosy list based on the topic
3449 ---------------------------------------------
3451 We need the ability to automatically add users to the nosy list based
3452 on the occurence of a topic. Every user should be allowed to edit his
3453 own list of topics for which he wants to be added to the nosy list.
3455 Below will be showed that such a change can be performed with only
3456 minimal understanding of the roundup system, but with clever use
3457 of Copy and Paste.
3459 This requires three changes to the tracker: a change in the database to
3460 allow per-user recording of the lists of topics for which he wants to
3461 be put on the nosy list, a change in the user view allowing to edit
3462 this list of topics, and addition of an auditor which updates the nosy
3463 list when a topic is set.
3465 Adding the nosy topic list
3466 ~~~~~~~~~~~~~~~~~~~~~~~~~~
3468 The change in the database to make is that for any user there should be
3469 a list of topics for which he wants to be put on the nosy list. Adding
3470 a ``Multilink`` of ``keyword`` seem to fullfill this (note that within
3471 the code topics are called ``keywords``.) As such, all what has to be
3472 done is to add a new field to the definition of ``user`` within the
3473 file ``dbinit.py``.  We will call this new field ``nosy_keywords``, and
3474 the updated definition of user will be::
3476     user = Class(db, "user", 
3477                     username=String(),   password=Password(),
3478                     address=String(),    realname=String(), 
3479                     phone=String(),      organisation=String(),
3480                     alternate_addresses=String(),
3481                     queries=Multilink('query'), roles=String(),
3482                     timezone=String(),
3483                     nosy_keywords=Multilink('keyword'))
3484  
3485 Changing the user view to allow changing the nosy topic list
3486 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
3488 We want any user to be able to change the list of topics for which
3489 he will by default be added to the nosy list. We choose to add this
3490 to the user view, as is generated by the file ``html/user.item.html``.
3491 We easily can
3492 see that the topic field in the issue view has very similar editting
3493 requirements as our nosy topics, both being a list of topics. As
3494 such, we search for Topics in ``issue.item.html``, and extract the
3495 associated parts from there. We add this to ``user.item.html`` at the 
3496 bottom of the list of viewed items (i.e. just below the 'Alternate
3497 E-mail addresses' in the classic template)::
3499  <tr>
3500   <th>Nosy Topics</th>
3501   <td>
3502   <span tal:replace="structure context/nosy_keywords/field" />
3503   <span tal:replace="structure python:db.keyword.classhelp(property='nosy_keywords')" />
3504   </td>
3505  </tr>
3506   
3508 Addition of an auditor to update the nosy list
3509 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
3511 The more difficult part is the addition of the logic to actually
3512 at the users to the nosy list when it is required. 
3513 The choice is made to perform this action when the topics on an
3514 item are set, including when an item is created.
3515 Here we choose to start out with a copy of the 
3516 ``detectors/nosyreaction.py`` detector, which we copy to the file
3517 ``detectors/nosy_keyword_reaction.py``. 
3518 This looks like a good start as it also adds users
3519 to the nosy list. A look through the code reveals that the
3520 ``nosyreaction`` function actually is sending the e-mail, which
3521 we do not need. As such, we can change the init function to::
3523     def init(db):
3524         db.issue.audit('create', update_kw_nosy)
3525         db.issue.audit('set', update_kw_nosy)
3527 After that we rename the ``updatenosy`` function to ``update_kw_nosy``.
3528 The first two blocks of code in that function relate to settings
3529 ``current`` to a combination of the old and new nosy lists. This
3530 functionality is left in the new auditor. The following block of
3531 code, which in ``updatenosy`` handled adding the assignedto user(s)
3532 to the nosy list, should be replaced by a block of code to add the
3533 interested users to the nosy list. We choose here to loop over all
3534 new topics, than loop over all users,
3535 and assign the user to the nosy list when the topic in the user's
3536 nosy_keywords. The next part in ``updatenosy``, adding the author
3537 and/or recipients of a message to the nosy list, obviously is not
3538 relevant here and thus is deleted from the new auditor. The last
3539 part, copying the new nosy list to newvalues, does not have to be changed.
3540 This brings the following function::
3542     def update_kw_nosy(db, cl, nodeid, newvalues):
3543         '''Update the nosy list for changes to the topics
3544         '''
3545         # nodeid will be None if this is a new node
3546         current = {}
3547         if nodeid is None:
3548             ok = ('new', 'yes')
3549         else:
3550             ok = ('yes',)
3551             # old node, get the current values from the node if they haven't
3552             # changed
3553             if not newvalues.has_key('nosy'):
3554                 nosy = cl.get(nodeid, 'nosy')
3555                 for value in nosy:
3556                     if not current.has_key(value):
3557                         current[value] = 1
3559         # if the nosy list changed in this transaction, init from the new value
3560         if newvalues.has_key('nosy'):
3561             nosy = newvalues.get('nosy', [])
3562             for value in nosy:
3563                 if not db.hasnode('user', value):
3564                     continue
3565                 if not current.has_key(value):
3566                     current[value] = 1
3568         # add users with topic in nosy_keywords to the nosy list
3569         if newvalues.has_key('topic') and newvalues['topic'] is not None:
3570             topic_ids = newvalues['topic']
3571             for topic in topic_ids:
3572                 # loop over all users,
3573                 # and assign user to nosy when topic in nosy_keywords
3574                 for user_id in db.user.list():
3575                     nosy_kw = db.user.get(user_id, "nosy_keywords")
3576                     found = 0
3577                     for kw in nosy_kw:
3578                         if kw == topic:
3579                             found = 1
3580                     if found:
3581                         current[user_id] = 1
3583         # that's it, save off the new nosy list
3584         newvalues['nosy'] = current.keys()
3586 and these two function are the only ones needed in the file.
3588 TODO: update this example to use the find() Class method.
3590 Caveats
3591 ~~~~~~~
3593 A few problems with the design here can be noted:
3595 Multiple additions
3596     When a user, after automatic selection, is manually removed
3597     from the nosy list, he again is added to the nosy list when the
3598     topic list of the issue is updated. A better design might be
3599     to only check which topics are new compared to the old list
3600     of topics, and only add users when they have indicated
3601     interest on a new topic.
3603     The code could also be changed to only trigger on the create() event,
3604     rather than also on the set() event, thus only setting the nosy list
3605     when the issue is created.
3607 Scalability
3608     In the auditor there is a loop over all users. For a site with
3609     only few users this will pose no serious problem, however, with
3610     many users this will be a serious performance bottleneck.
3611     A way out will be to link from the topics to the users which
3612     selected these topics a nosy topics. This will eliminate the
3613     loop over all users.
3616 Adding action links to the index page
3617 -------------------------------------
3619 Add a column to the item.index.html template.
3621 Resolving the issue::
3623   <a tal:attributes="href
3624      string:issue${i/id}?:status=resolved&:action=edit">resolve</a>
3626 "Take" the issue::
3628   <a tal:attributes="href
3629      string:issue${i/id}?:assignedto=${request/user/id}&:action=edit">take</a>
3631 ... and so on
3633 Users may only edit their issues
3634 --------------------------------
3636 Users registering themselves are granted Provisional access - meaning they
3637 have access to edit the issues they submit, but not others. We create a new
3638 Role called "Provisional User" which is granted to newly-registered users,
3639 and has limited access. One of the Permissions they have is the new "Edit
3640 Own" on issues (regular users have "Edit".) We back up the permissions with
3641 an auditor.
3643 First up, we create the new Role and Permission structure in
3644 ``dbinit.py``::
3646     # New users not approved by the admin
3647     db.security.addRole(name='Provisional User',
3648         description='New user registered via web or email')
3649     p = db.security.addPermission(name='Edit Own', klass='issue',
3650         description='Can only edit own issues')
3651     db.security.addPermissionToRole('Provisional User', p)
3653     # Assign the access and edit Permissions for issue to new users now
3654     p = db.security.getPermission('View', 'issue')
3655     db.security.addPermissionToRole('Provisional User', p)
3656     p = db.security.getPermission('Edit', 'issue')
3657     db.security.addPermissionToRole('Provisional User', p)
3659     # and give the new users access to the web and email interface
3660     p = db.security.getPermission('Web Access')
3661     db.security.addPermissionToRole('Provisional User', p)
3662     p = db.security.getPermission('Email Access')
3663     db.security.addPermissionToRole('Provisional User', p)
3666 Then in the ``config.py`` we change the Role assigned to newly-registered
3667 users, replacing the existing ``'User'`` values::
3669     NEW_WEB_USER_ROLES = 'Provisional User'
3670     NEW_EMAIL_USER_ROLES = 'Provisional User'
3672 Finally we add a new *auditor* to the ``detectors`` directory called
3673 ``provisional_user_auditor.py``::
3675  def audit_provisionaluser(db, cl, nodeid, newvalues):
3676      ''' New users are only allowed to modify their own issues.
3677      '''
3678      if (db.getuid() != cl.get(nodeid, 'creator')
3679          and db.security.hasPermission('Edit Own', db.getuid(), cl.classname)):
3680          raise ValueError, ('You are only allowed to edit your own %s'
3681                             % cl.classname)
3683  def init(db):
3684      # fire before changes are made
3685      db.issue.audit('set', audit_provisionaluser)
3686      db.issue.audit('retire', audit_provisionaluser)
3687      db.issue.audit('restore', audit_provisionaluser)
3689 Note that some older trackers might also want to change the ``page.html``
3690 template as follows::
3692  <p class="classblock"
3693  -       tal:condition="python:request.user.username != 'anonymous'">
3694  +       tal:condition="python:request.user.hasPermission('View', 'user')">
3695      <b>Administration</b><br>
3696      <tal:block tal:condition="python:request.user.hasPermission('Edit', None)">
3697       <a href="home?:template=classlist">Class List</a><br>
3699 (note that the "-" indicates a removed line, and the "+" indicates an added
3700 line).
3703 Colouring the rows in the issue index according to priority
3704 -----------------------------------------------------------
3706 A simple ``tal:attributes`` statement will do the bulk of the work here. In
3707 the ``issue.index.html`` template, add to the ``<tr>`` that displays the
3708 actual rows of data::
3710    <tr tal:attributes="class string:priority-${i/priority/plain}">
3712 and then in your stylesheet (``style.css``) specify the colouring for the
3713 different priorities, like::
3715    tr.priority-critical td {
3716        background-color: red;
3717    }
3719    tr.priority-urgent td {
3720        background-color: orange;
3721    }
3723 and so on, with far less offensive colours :)
3725 Editing multiple items in an index view
3726 ---------------------------------------
3728 To edit the status of all items in the item index view, edit the
3729 ``issue.item.html``:
3731 1. add a form around the listing table, so at the top it reads::
3733     <form method="POST" tal:attributes="action request/classname">
3734      <table class="list">
3736    and at the bottom of that table::
3738      </table>
3739     </form
3741    making sure you match the ``</table>`` from the list table, not the
3742    navigation table or the subsequent form table.
3744 2. in the display for the issue property, change::
3746     <td tal:condition="request/show/status"
3747         tal:content="python:i.status.plain() or default">&nbsp;</td>
3749    to::
3751     <td tal:condition="request/show/status"
3752         tal:content="structure i/status/field">&nbsp;</td>
3754    this will result in an edit field for the status property.
3756 3. after the ``tal:block`` which lists the actual index items (marked by
3757    ``tal:repeat="i batch"``) add a new table row::
3759     <tr>
3760      <td tal:attributes="colspan python:len(request.columns)">
3761       <input type="submit" value=" Save Changes ">
3762       <input type="hidden" name="@action" value="edit">
3763       <tal:block replace="structure request/indexargs_form" />
3764      </td>
3765     </tr>
3767    which gives us a submit button, indicates that we are performing an edit
3768    on any changed statuses and the final block will make sure that the
3769    current index view parameters (filtering, columns, etc) will be used in 
3770    rendering the next page (the results of the editing).
3772 -------------------
3774 Back to `Table of Contents`_
3776 .. _`Table of Contents`: index.html
3777 .. _`design documentation`: design.html