Code

Update documentation for the client.py split and add an upgrade notice.
[roundup.git] / doc / customizing.txt
1 ===================
2 Customising Roundup
3 ===================
5 :Version: $Revision: 1.114 $
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 The default config.py is given below - as you
191 can see, the MAIL_DOMAIN must be edited before any interaction with the
192 tracker is attempted.::
194     # roundup home is this package's directory
195     TRACKER_HOME=os.path.split(__file__)[0]
197     # The SMTP mail host that roundup will use to send mail
198     MAILHOST = 'localhost'
200     # The domain name used for email addresses.
201     MAIL_DOMAIN = 'your.tracker.email.domain.example'
203     # This is the directory that the database is going to be stored in
204     DATABASE = os.path.join(TRACKER_HOME, 'db')
206     # This is the directory that the HTML templates reside in
207     TEMPLATES = os.path.join(TRACKER_HOME, 'html')
209     # A descriptive name for your roundup tracker
210     TRACKER_NAME = 'Roundup issue tracker'
212     # The email address that mail to roundup should go to
213     TRACKER_EMAIL = 'issue_tracker@%s'%MAIL_DOMAIN
215     # The web address that the tracker is viewable at. This will be
216     # included in information sent to users of the tracker. The URL MUST
217     # include the cgi-bin part or anything else that is required to get
218     # to the home page of the tracker. You MUST include a trailing '/'
219     # in the URL.
220     TRACKER_WEB = 'http://tracker.example/cgi-bin/roundup.cgi/bugs/'
222     # The email address that roundup will complain to if it runs into
223     # trouble
224     ADMIN_EMAIL = 'roundup-admin@%s'%MAIL_DOMAIN
226     # Additional text to include in the "name" part of the From: address
227     # used in nosy messages. If the sending user is "Foo Bar", the From:
228     # line is usually: "Foo Bar" <issue_tracker@tracker.example>
229     # the EMAIL_FROM_TAG goes inside the "Foo Bar" quotes like so:
230     #    "Foo Bar EMAIL_FROM_TAG" <issue_tracker@tracker.example>
231     EMAIL_FROM_TAG = ""
233     # Send nosy messages to the author of the message
234     MESSAGES_TO_AUTHOR = 'no'           # either 'yes' or 'no'
236     # Does the author of a message get placed on the nosy list
237     # automatically? If 'new' is used, then the author will only be
238     # added when a message creates a new issue. If 'yes', then the
239     # author will be added on followups too. If 'no', they're never
240     # added to the nosy.
241     ADD_AUTHOR_TO_NOSY = 'new'          # one of 'yes', 'no', 'new'
243     # Do the recipients (To:, Cc:) of a message get placed on the nosy
244     # list? If 'new' is used, then the recipients will only be added
245     # when a message creates a new issue. If 'yes', then the recipients
246     # will be added on followups too. If 'no', they're never added to
247     # the nosy.
248     ADD_RECIPIENTS_TO_NOSY = 'new'      # either 'yes', 'no', 'new'
250     # Where to place the email signature
251     EMAIL_SIGNATURE_POSITION = 'bottom' # one of 'top', 'bottom', 'none'
253     # Keep email citations
254     EMAIL_KEEP_QUOTED_TEXT = 'no'       # either 'yes' or 'no'
256     # Preserve the email body as is
257     EMAIL_LEAVE_BODY_UNCHANGED = 'no'   # either 'yes' or 'no'
259     # Default class to use in the mailgw if one isn't supplied in email
260     # subjects. To disable, comment out the variable below or leave it
261     # blank. Examples:
262     MAIL_DEFAULT_CLASS = 'issue'   # use "issue" class by default
263     #MAIL_DEFAULT_CLASS = ''        # disable (or just comment the var out)
265     # HTML version to generate. The templates are html4 by default. If you
266     # wish to make them xhtml, then you'll need to change this var to 'xhtml'
267     # too so all auto-generated HTML is compliant.
268     HTML_VERSION = 'html4'         # either 'html4' or 'xhtml'
270     # 
271     # SECURITY DEFINITIONS
272     #
273     # define the Roles that a user gets when they register with the
274     # tracker these are a comma-separated string of role names (e.g.
275     # 'Admin,User')
276     NEW_WEB_USER_ROLES = 'User'
277     NEW_EMAIL_USER_ROLES = 'User'
279 Tracker Schema
280 ==============
282 Note: if you modify the schema, you'll most likely need to edit the
283       `web interface`_ HTML template files and `detectors`_ to reflect
284       your changes.
286 A tracker schema defines what data is stored in the tracker's database.
287 Schemas are defined using Python code in the ``dbinit.py`` module of your
288 tracker. The "classic" schema looks like this (see below for the meaning
289 of ``'setkey'``)::
291     pri = Class(db, "priority", name=String(), order=String())
292     pri.setkey("name")
294     stat = Class(db, "status", name=String(), order=String())
295     stat.setkey("name")
297     keyword = Class(db, "keyword", name=String())
298     keyword.setkey("name")
300     user = Class(db, "user", username=String(), organisation=String(),
301         password=String(), address=String(), realname=String(),
302         phone=String())
303     user.setkey("username")
305     msg = FileClass(db, "msg", author=Link("user"), summary=String(),
306         date=Date(), recipients=Multilink("user"),
307         files=Multilink("file"))
309     file = FileClass(db, "file", name=String(), type=String())
311     issue = IssueClass(db, "issue", topic=Multilink("keyword"),
312         status=Link("status"), assignedto=Link("user"),
313         priority=Link("priority"))
314     issue.setkey('title')
317 What you can't do to the schema
318 -------------------------------
320 You must never:
322 **Remove the users class**
323   This class is the only *required* class in Roundup. Similarly, its
324   username, password and address properties must never be removed.
326 **Change the type of a property**
327   Property types must *never* be changed - the database simply doesn't take
328   this kind of action into account. Note that you can't just remove a
329   property and re-add it as a new type either. If you wanted to make the
330   assignedto property a Multilink, you'd need to create a new property
331   assignedto_list and remove the old assignedto property.
334 What you can do to the schema
335 -----------------------------
337 Your schema may be changed at any time before or after the tracker has been
338 initialised (or used). You may:
340 **Add new properties to classes, or add whole new classes**
341   This is painless and easy to do - there are generally no repurcussions
342   from adding new information to a tracker's schema.
344 **Remove properties**
345   Removing properties is a little more tricky - you need to make sure that
346   the property is no longer used in the `web interface`_ *or* by the
347   detectors_.
351 Classes and Properties - creating a new information store
352 ---------------------------------------------------------
354 In the tracker above, we've defined 7 classes of information:
356   priority
357       Defines the possible levels of urgency for issues.
359   status
360       Defines the possible states of processing the issue may be in.
362   keyword
363       Initially empty, will hold keywords useful for searching issues.
365   user
366       Initially holding the "admin" user, will eventually have an entry
367       for all users using roundup.
369   msg
370       Initially empty, will hold all e-mail messages sent to or
371       generated by roundup.
373   file
374       Initially empty, will hold all files attached to issues.
376   issue
377       Initially empty, this is where the issue information is stored.
379 We define the "priority" and "status" classes to allow two things:
380 reduction in the amount of information stored on the issue and more
381 powerful, accurate searching of issues by priority and status. By only
382 requiring a link on the issue (which is stored as a single number) we
383 reduce the chance that someone mis-types a priority or status - or
384 simply makes a new one up.
387 Class and Items
388 ~~~~~~~~~~~~~~~
390 A Class defines a particular class (or type) of data that will be stored
391 in the database. A class comprises one or more properties, which gives
392 the information about the class items.
394 The actual data entered into the database, using ``class.create()``, are
395 called items. They have a special immutable property called ``'id'``. We
396 sometimes refer to this as the *itemid*.
399 Properties
400 ~~~~~~~~~~
402 A Class is comprised of one or more properties of the following types:
404 * String properties are for storing arbitrary-length strings.
405 * Password properties are for storing encoded arbitrary-length strings.
406   The default encoding is defined on the ``roundup.password.Password``
407   class.
408 * Date properties store date-and-time stamps. Their values are Timestamp
409   objects.
410 * Number properties store numeric values.
411 * Boolean properties store on/off, yes/no, true/false values.
412 * A Link property refers to a single other item selected from a
413   specified class. The class is part of the property; the value is an
414   integer, the id of the chosen item.
415 * A Multilink property refers to possibly many items in a specified
416   class. The value is a list of integers.
419 FileClass
420 ~~~~~~~~~
422 FileClasses save their "content" attribute off in a separate file from
423 the rest of the database. This reduces the number of large entries in
424 the database, which generally makes databases more efficient, and also
425 allows us to use command-line tools to operate on the files. They are
426 stored in the files sub-directory of the ``'db'`` directory in your
427 tracker.
430 IssueClass
431 ~~~~~~~~~~
433 IssueClasses automatically include the "messages", "files", "nosy", and
434 "superseder" properties.
436 The messages and files properties list the links to the messages and
437 files related to the issue. The nosy property is a list of links to
438 users who wish to be informed of changes to the issue - they get "CC'ed"
439 e-mails when messages are sent to or generated by the issue. The nosy
440 reactor (in the ``'detectors'`` directory) handles this action. The
441 superseder link indicates an issue which has superseded this one.
443 They also have the dynamically generated "creation", "activity" and
444 "creator" properties.
446 The value of the "creation" property is the date when an item was
447 created, and the value of the "activity" property is the date when any
448 property on the item was last edited (equivalently, these are the dates
449 on the first and last records in the item's journal). The "creator"
450 property holds a link to the user that created the issue.
453 setkey(property)
454 ~~~~~~~~~~~~~~~~
456 Select a String property of the class to be the key property. The key
457 property must be unique, and allows references to the items in the class
458 by the content of the key property. That is, we can refer to users by
459 their username: for example, let's say that there's an issue in roundup,
460 issue 23. There's also a user, richard, who happens to be user 2. To
461 assign an issue to him, we could do either of::
463      roundup-admin set issue23 assignedto=2
465 or::
467      roundup-admin set issue23 assignedto=richard
469 Note, the same thing can be done in the web and e-mail interfaces. 
471 If a class does not have an "order" property, the key is also used to
472 sort instances of the class when it is rendered in the user interface.
473 (If a class has no "order" property, sorting is by the labelproperty of
474 the class. This is computed, in order of precedence, as the key, the
475 "name", the "title", or the first property alphabetically.)
478 create(information)
479 ~~~~~~~~~~~~~~~~~~~
481 Create an item in the database. This is generally used to create items
482 in the "definitional" classes like "priority" and "status".
485 Examples of adding to your schema
486 ---------------------------------
488 TODO
491 Detectors - adding behaviour to your tracker
492 ============================================
493 .. _detectors:
495 Detectors are initialised every time you open your tracker database, so
496 you're free to add and remove them any time, even after the database is
497 initialised via the "roundup-admin initialise" command.
499 The detectors in your tracker fire *before* (**auditors**) and *after*
500 (**reactors**) changes to the contents of your database. They are Python
501 modules that sit in your tracker's ``detectors`` directory. You will
502 have some installed by default - have a look. You can write new
503 detectors or modify the existing ones. The existing detectors installed
504 for you are:
506 **nosyreaction.py**
507   This provides the automatic nosy list maintenance and email sending.
508   The nosy reactor (``nosyreaction``) fires when new messages are added
509   to issues. The nosy auditor (``updatenosy``) fires when issues are
510   changed, and figures out what changes need to be made to the nosy list
511   (such as adding new authors, etc.)
512 **statusauditor.py**
513   This provides the ``chatty`` auditor which changes the issue status
514   from ``unread`` or ``closed`` to ``chatting`` if new messages appear.
515   It also provides the ``presetunread`` auditor which pre-sets the
516   status to ``unread`` on new items if the status isn't explicitly
517   defined.
518 **messagesummary.py**
519   Generates the ``summary`` property for new messages based on the message
520   content.
521 **userauditor.py**
522   Verifies the content of some of the user fields (email addresses and
523   roles lists).
525 If you don't want this default behaviour, you're completely free to change
526 or remove these detectors.
528 See the detectors section in the `design document`__ for details of the
529 interface for detectors.
531 __ design.html
533 Sample additional detectors that have been found useful will appear in
534 the ``'detectors'`` directory of the Roundup distribution. If you want
535 to use one, copy it to the ``'detectors'`` of your tracker instance:
537 **newissuecopy.py**
538   This detector sends an email to a team address whenever a new issue is
539   created. The address is hard-coded into the detector, so edit it
540   before you use it (look for the text 'team@team.host') or you'll get
541   email errors!
543   The detector code::
545     from roundup import roundupdb
547     def newissuecopy(db, cl, nodeid, oldvalues):
548         ''' Copy a message about new issues to a team address.
549         '''
550         # so use all the messages in the create
551         change_note = cl.generateCreateNote(nodeid)
553         # send a copy to the nosy list
554         for msgid in cl.get(nodeid, 'messages'):
555             try:
556                 # note: last arg must be a list
557                 cl.send_message(nodeid, msgid, change_note,
558                     ['team@team.host'])
559             except roundupdb.MessageSendError, message:
560                 raise roundupdb.DetectorError, message
562     def init(db):
563         db.issue.react('create', newissuecopy)
566 Database Content
567 ================
569 Note: if you modify the content of definitional classes, you'll most
570        likely need to edit the tracker `detectors`_ to reflect your
571        changes.
573 Customisation of the special "definitional" classes (eg. status,
574 priority, resolution, ...) may be done either before or after the
575 tracker is initialised. The actual method of doing so is completely
576 different in each case though, so be careful to use the right one.
578 **Changing content before tracker initialisation**
579     Edit the dbinit module in your tracker to alter the items created in
580     using the ``create()`` methods.
582 **Changing content after tracker initialisation**
583     As the "admin" user, click on the "class list" link in the web
584     interface to bring up a list of all database classes. Click on the
585     name of the class you wish to change the content of.
587     You may also use the ``roundup-admin`` interface's create, set and
588     retire methods to add, alter or remove items from the classes in
589     question.
591 See "`adding a new field to the classic schema`_" for an example that
592 requires database content changes.
595 Security / Access Controls
596 ==========================
598 A set of Permissions is built into the security module by default:
600 - Edit (everything)
601 - View (everything)
603 The default interfaces define:
605 - Web Registration
606 - Web Access
607 - Web Roles
608 - Email Registration
609 - Email Access
611 These are hooked into the default Roles:
613 - Admin (Edit everything, View everything, Web Roles)
614 - User (Web Access, Email Access)
615 - Anonymous (Web Registration, Email Registration)
617 And finally, the "admin" user gets the "Admin" Role, and the "anonymous"
618 user gets "Anonymous" assigned when the database is initialised on
619 installation. The two default schemas then define:
621 - Edit issue, View issue (both)
622 - Edit file, View file (both)
623 - Edit msg, View msg (both)
624 - Edit support, View support (extended only)
626 and assign those Permissions to the "User" Role. Put together, these
627 settings appear in the ``open()`` function of the tracker ``dbinit.py``
628 (the following is taken from the "minimal" template's ``dbinit.py``)::
630     #
631     # SECURITY SETTINGS
632     #
633     # new permissions for this schema
634     for cl in ('user', ):
635         db.security.addPermission(name="Edit", klass=cl,
636             description="User is allowed to edit "+cl)
637         db.security.addPermission(name="View", klass=cl,
638             description="User is allowed to access "+cl)
640     # and give the regular users access to the web and email interface
641     p = db.security.getPermission('Web Access')
642     db.security.addPermissionToRole('User', p)
643     p = db.security.getPermission('Email Access')
644     db.security.addPermissionToRole('User', p)
646     # May users view other user information? Comment these lines out
647     # if you don't want them to
648     p = db.security.getPermission('View', 'user')
649     db.security.addPermissionToRole('User', p)
651     # Assign the appropriate permissions to the anonymous user's
652     # Anonymous role. Choices here are:
653     # - Allow anonymous users to register through the web
654     p = db.security.getPermission('Web Registration')
655     db.security.addPermissionToRole('Anonymous', p)
656     # - Allow anonymous (new) users to register through the email
657     #   gateway
658     p = db.security.getPermission('Email Registration')
659     db.security.addPermissionToRole('Anonymous', p)
662 New User Roles
663 --------------
665 New users are assigned the Roles defined in the config file as:
667 - NEW_WEB_USER_ROLES
668 - NEW_EMAIL_USER_ROLES
671 Changing Access Controls
672 ------------------------
674 You may alter the configuration variables to change the Role that new
675 web or email users get, for example to not give them access to the web
676 interface if they register through email. 
678 You may use the ``roundup-admin`` "``security``" command to display the
679 current Role and Permission configuration in your tracker.
682 Adding a new Permission
683 ~~~~~~~~~~~~~~~~~~~~~~~
685 When adding a new Permission, you will need to:
687 1. add it to your tracker's dbinit so it is created
688 2. enable it for the Roles that should have it (verify with
689    "``roundup-admin security``")
690 3. add it to the relevant HTML interface templates
691 4. add it to the appropriate xxxPermission methods on in your tracker
692    interfaces module
695 Example Scenarios
696 ~~~~~~~~~~~~~~~~~
698 **automatic registration of users in the e-mail gateway**
699  By giving the "anonymous" user the "Email Registration" Role, any
700  unidentified user will automatically be registered with the tracker
701  (with no password, so they won't be able to log in through the web
702  until an admin sets their password). Note: this is the default
703  behaviour in the tracker templates that ship with Roundup.
705 **anonymous access through the e-mail gateway**
706  Give the "anonymous" user the "Email Access" and ("Edit", "issue")
707  Roles but do not not give them the "Email Registration" Role. This
708  means that when an unknown user sends email into the tracker, they're
709  automatically logged in as "anonymous". Since they don't have the
710  "Email Registration" Role, they won't be automatically registered, but
711  since "anonymous" has permission to use the gateway, they'll still be
712  able to submit issues. Note that the Sender information - their email
713  address - will not be available - they're *anonymous*.
715 **only developers may be assigned issues**
716  Create a new Permission called "Fixer" for the "issue" class. Create a
717  new Role "Developer" which has that Permission, and assign that to the
718  appropriate users. Filter the list of users available in the assignedto
719  list to include only those users. Enforce the Permission with an
720  auditor. See the example 
721  `restricting the list of users that are assignable to a task`_.
723 **only managers may sign off issues as complete**
724  Create a new Permission called "Closer" for the "issue" class. Create a
725  new Role "Manager" which has that Permission, and assign that to the
726  appropriate users. In your web interface, only display the "resolved"
727  issue state option when the user has the "Closer" Permissions. Enforce
728  the Permission with an auditor. This is very similar to the previous
729  example, except that the web interface check would look like::
731    <option tal:condition="python:request.user.hasPermission('Closer')"
732            value="resolved">Resolved</option>
733  
734 **don't give web access to users who register through email**
735  Create a new Role called "Email User" which has all the Permissions of
736  the normal "User" Role minus the "Web Access" Permission. This will
737  allow users to send in emails to the tracker, but not access the web
738  interface.
740 **let some users edit the details of all users**
741  Create a new Role called "User Admin" which has the Permission for
742  editing users::
744     db.security.addRole(name='User Admin', description='Managing users')
745     p = db.security.getPermission('Edit', 'user')
746     db.security.addPermissionToRole('User Admin', p)
748  and assign the Role to the users who need the permission.
751 Web Interface
752 =============
754 .. contents::
755    :local:
756    :depth: 1
758 The web interface is provided by the ``roundup.cgi.client`` module and
759 is used by ``roundup.cgi``, ``roundup-server`` and ``ZRoundup``
760 (``ZRoundup``  is broken, until further notice). In all cases, we
761 determine which tracker is being accessed (the first part of the URL
762 path inside the scope of the CGI handler) and pass control on to the
763 tracker ``interfaces.Client`` class - which uses the ``Client`` class
764 from ``roundup.cgi.client`` - which handles the rest of the access
765 through its ``main()`` method. This means that you can do pretty much
766 anything you want as a web interface to your tracker.
768 Repercussions of changing the tracker schema
769 ---------------------------------------------
771 If you choose to change the `tracker schema`_ you will need to ensure
772 the web interface knows about it:
774 1. Index, item and search pages for the relevant classes may need to
775    have properties added or removed,
776 2. The "page" template may require links to be changed, as might the
777    "home" page's content arguments.
779 How requests are processed
780 --------------------------
782 The basic processing of a web request proceeds as follows:
784 1. figure out who we are, defaulting to the "anonymous" user
785 2. figure out what the request is for - we call this the "context"
786 3. handle any requested action (item edit, search, ...)
787 4. render the template requested by the context, resulting in HTML
788    output
790 In some situations, exceptions occur:
792 - HTTP Redirect  (generally raised by an action)
793 - SendFile       (generally raised by ``determine_context``)
794     here we serve up a FileClass "content" property
795 - SendStaticFile (generally raised by ``determine_context``)
796     here we serve up a file from the tracker "html" directory
797 - Unauthorised   (generally raised by an action)
798     here the action is cancelled, the request is rendered and an error
799     message is displayed indicating that permission was not granted for
800     the action to take place
801 - NotFound       (raised wherever it needs to be)
802     this exception percolates up to the CGI interface that called the
803     client
805 Determining web context
806 -----------------------
808 To determine the "context" of a request, we look at the URL and the
809 special request variable ``@template``. The URL path after the tracker
810 identifier is examined. Typical URL paths look like:
812 1.  ``/tracker/issue``
813 2.  ``/tracker/issue1``
814 3.  ``/tracker/_file/style.css``
815 4.  ``/cgi-bin/roundup.cgi/tracker/file1``
816 5.  ``/cgi-bin/roundup.cgi/tracker/file1/kitten.png``
818 where the "tracker identifier" is "tracker" in the above cases. That means
819 we're looking at "issue", "issue1", "_file/style.css", "file1" and
820 "file1/kitten.png" in the cases above. The path is generally only one
821 entry long - longer paths are handled differently.
823 a. if there is no path, then we are in the "home" context.
824 b. if the path starts with "_file" (as in example 3,
825    "/tracker/_file/style.css"), then the additional path entry,
826    "style.css" specifies the filename of a static file we're to serve up
827    from the tracker "html" directory. Raises a SendStaticFile exception.
828 c. if there is something in the path (as in example 1, "issue"), it
829    identifies the tracker class we're to display.
830 d. if the path is an item designator (as in examples 2 and 4, "issue1"
831    and "file1"), then we're to display a specific item.
832 e. if the path starts with an item designator and is longer than one
833    entry (as in example 5, "file1/kitten.png"), then we're assumed to be
834    handling an item of a ``FileClass``, and the extra path information
835    gives the filename that the client is going to label the download
836    with (i.e. "file1/kitten.png" is nicer to download than "file1").
837    This raises a ``SendFile`` exception.
839 Both b. and e. stop before we bother to determine the template we're
840 going to use. That's because they don't actually use templates.
842 The template used is specified by the ``@template`` CGI variable, which
843 defaults to:
845 - only classname suplied:        "index"
846 - full item designator supplied: "item"
849 Performing actions in web requests
850 ----------------------------------
852 When a user requests a web page, they may optionally also request for an
853 action to take place. As described in `how requests are processed`_, the
854 action is performed before the requested page is generated. Actions are
855 triggered by using a ``@action`` CGI variable, where the value is one
856 of:
858 **login**
859  Attempt to log a user in.
861 **logout**
862  Log the user out - make them "anonymous".
864 **register**
865  Attempt to create a new user based on the contents of the form and then
866  log them in.
868 **edit**
869  Perform an edit of an item in the database. There are some `special form
870  variables`_ you may use.
872 **new**
873  Add a new item to the database. You may use the same `special form
874  variables`_ as in the "edit" action.
876 **retire**
877  Retire the item in the database.
879 **editCSV**
880  Performs an edit of all of a class' items in one go. See also the
881  *class*.csv templating method which generates the CSV data to be
882  edited, and the ``'_generic.index'`` template which uses both of these
883  features.
885 **search**
886  Mangle some of the form variables:
888  - Set the form ":filter" variable based on the values of the filter
889    variables - if they're set to anything other than "dontcare" then add
890    them to :filter.
892  - Also handle the ":queryname" variable and save off the query to the
893    user's query list.
895 Each of the actions is implemented by a corresponding ``*actionAction*``
896 (where "action" is the name of the action) method on the
897 ``roundup.cgi.Client`` class, which also happens to be available in your
898 tracker instance as ``interfaces.Client``. So if you need to define new
899 actions, you may add them there (see `defining new web actions`_).
901 Each action also has a corresponding ``*actionPermission*`` (where
902 "action" is the name of the action) method which determines whether the
903 action is permissible given the current user. The base permission checks
904 are:
906 **login**
907  Determine whether the user has permission to log in. Base behaviour is
908  to check the user has "Web Access".
909 **logout**
910  No permission checks are made.
911 **register**
912  Determine whether the user has permission to register. Base behaviour
913  is to check the user has the "Web Registration" Permission.
914 **edit**
915  Determine whether the user has permission to edit this item. Base
916  behaviour is to check whether the user can edit this class. If we're
917  editing the "user" class, users are allowed to edit their own details -
918  unless they try to edit the "roles" property, which requires the
919  special Permission "Web Roles".
920 **new**
921  Determine whether the user has permission to create (or edit) this
922  item. Base behaviour is to check the user can edit this class. No
923  additional property checks are made. Additionally, new user items may
924  be created if the user has the "Web Registration" Permission.
925 **editCSV**
926  Determine whether the user has permission to edit this class. Base
927  behaviour is to check whether the user may edit this class.
928 **search**
929  Determine whether the user has permission to search this class. Base
930  behaviour is to check whether the user may view this class.
933 Special form variables
934 ----------------------
936 Item properties and their values are edited with html FORM
937 variables and their values. You can:
939 - Change the value of some property of the current item.
940 - Create a new item of any class, and edit the new item's
941   properties,
942 - Attach newly created items to a multilink property of the
943   current item.
944 - Remove items from a multilink property of the current item.
945 - Specify that some properties are required for the edit
946   operation to be successful.
948 In the following, <bracketed> values are variable, "@" may be
949 either ":" or "@", and other text "required" is fixed.
951 Most properties are specified as form variables:
953 ``<propname>``
954   property on the current context item
956 ``<designator>"@"<propname>``
957   property on the indicated item (for editing related information)
959 Designators name a specific item of a class.
961 ``<classname><N>``
962     Name an existing item of class <classname>.
964 ``<classname>"-"<N>``
965     Name the <N>th new item of class <classname>. If the form
966     submission is successful, a new item of <classname> is
967     created. Within the submitted form, a particular
968     designator of this form always refers to the same new
969     item.
971 Once we have determined the "propname", we look at it to see
972 if it's special:
974 ``@required``
975     The associated form value is a comma-separated list of
976     property names that must be specified when the form is
977     submitted for the edit operation to succeed.  
979     When the <designator> is missing, the properties are
980     for the current context item.  When <designator> is
981     present, they are for the item specified by
982     <designator>.
984     The "@required" specifier must come before any of the
985     properties it refers to are assigned in the form.
987 ``@remove@<propname>=id(s)`` or ``@add@<propname>=id(s)``
988     The "@add@" and "@remove@" edit actions apply only to
989     Multilink properties.  The form value must be a
990     comma-separate list of keys for the class specified by
991     the simple form variable.  The listed items are added
992     to (respectively, removed from) the specified
993     property.
995 ``@link@<propname>=<designator>``
996     If the edit action is "@link@", the simple form
997     variable must specify a Link or Multilink property.
998     The form value is a comma-separated list of
999     designators.  The item corresponding to each
1000     designator is linked to the property given by simple
1001     form variable.
1003 None of the above (ie. just a simple form value)
1004     The value of the form variable is converted
1005     appropriately, depending on the type of the property.
1007     For a Link('klass') property, the form value is a
1008     single key for 'klass', where the key field is
1009     specified in dbinit.py.  
1011     For a Multilink('klass') property, the form value is a
1012     comma-separated list of keys for 'klass', where the
1013     key field is specified in dbinit.py.  
1015     Note that for simple-form-variables specifiying Link
1016     and Multilink properties, the linked-to class must
1017     have a key field.
1019     For a String() property specifying a filename, the
1020     file named by the form value is uploaded. This means we
1021     try to set additional properties "filename" and "type" (if
1022     they are valid for the class).  Otherwise, the property
1023     is set to the form value.
1025     For Date(), Interval(), Boolean(), and Number()
1026     properties, the form value is converted to the
1027     appropriate
1029 Any of the form variables may be prefixed with a classname or
1030 designator.
1032 Two special form values are supported for backwards compatibility:
1034 @note
1035     This is equivalent to::
1037         @link@messages=msg-1
1038         msg-1@content=value
1040     except that in addition, the "author" and "date" properties of
1041     "msg-1" are set to the userid of the submitter, and the current
1042     time, respectively.
1044 @file
1045     This is equivalent to::
1047         @link@files=file-1
1048         file-1@content=value
1050     The String content value is handled as described above for file
1051     uploads.
1053 If both the "@note" and "@file" form variables are
1054 specified, the action::
1056         @link@msg-1@files=file-1
1058 is also performed.
1060 We also check that FileClass items have a "content" property with
1061 actual content, otherwise we remove them from all_props before
1062 returning.
1066 Default templates
1067 -----------------
1069 The default templates are html4 compliant. If you wish to change them to be
1070 xhtml compliant, you'll need to change the ``HTML_VERSION`` configuration
1071 variable in ``config.py`` to ``'xhtml'`` instead of ``'html4'``.
1073 Most customisation of the web view can be done by modifying the
1074 templates in the tracker ``'html'`` directory. There are several types
1075 of files in there. The *minimal* template includes:
1077 **page.html**
1078   This template usually defines the overall look of your tracker. When
1079   you view an issue, it appears inside this template. When you view an
1080   index, it also appears inside this template. This template defines a
1081   macro called "icing" which is used by almost all other templates as a
1082   coating for their content, using its "content" slot. It also defines
1083   the "head_title" and "body_title" slots to allow setting of the page
1084   title.
1085 **home.html**
1086   the default page displayed when no other page is indicated by the user
1087 **home.classlist.html**
1088   a special version of the default page that lists the classes in the
1089   tracker
1090 **classname.item.html**
1091   displays an item of the *classname* class
1092 **classname.index.html**
1093   displays a list of *classname* items
1094 **classname.search.html**
1095   displays a search page for *classname* items
1096 **_generic.index.html**
1097   used to display a list of items where there is no
1098   ``*classname*.index`` available
1099 **_generic.help.html**
1100   used to display a "class help" page where there is no
1101   ``*classname*.help``
1102 **user.register.html**
1103   a special page just for the user class, that renders the registration
1104   page
1105 **style.css.html**
1106   a static file that is served up as-is
1108 The *classic* template has a number of additional templates.
1110 Note: Remember that you can create any template extension you want to,
1111 so if you just want to play around with the templating for new issues,
1112 you can copy the current "issue.item" template to "issue.test", and then
1113 access the test template using the "@template" URL argument::
1115    http://your.tracker.example/tracker/issue?@template=test
1117 and it won't affect your users using the "issue.item" template.
1120 How the templates work
1121 ----------------------
1124 Basic Templating Actions
1125 ~~~~~~~~~~~~~~~~~~~~~~~~
1127 Roundup's templates consist of special attributes on the HTML tags.
1128 These attributes form the Template Attribute Language, or TAL. The basic
1129 TAL commands are:
1131 **tal:define="variable expression; variable expression; ..."**
1132    Define a new variable that is local to this tag and its contents. For
1133    example::
1135       <html tal:define="title request/description">
1136        <head><title tal:content="title"></title></head>
1137       </html>
1139    In this example, the variable "title" is defined as the result of the
1140    expression "request/description". The "tal:content" command inside the
1141    <html> tag may then use the "title" variable.
1143 **tal:condition="expression"**
1144    Only keep this tag and its contents if the expression is true. For
1145    example::
1147      <p tal:condition="python:request.user.hasPermission('View', 'issue')">
1148       Display some issue information.
1149      </p>
1151    In the example, the <p> tag and its contents are only displayed if
1152    the user has the "View" permission for issues. We consider the number
1153    zero, a blank string, an empty list, and the built-in variable
1154    nothing to be false values. Nearly every other value is true,
1155    including non-zero numbers, and strings with anything in them (even
1156    spaces!).
1158 **tal:repeat="variable expression"**
1159    Repeat this tag and its contents for each element of the sequence
1160    that the expression returns, defining a new local variable and a
1161    special "repeat" variable for each element. For example::
1163      <tr tal:repeat="u user/list">
1164       <td tal:content="u/id"></td>
1165       <td tal:content="u/username"></td>
1166       <td tal:content="u/realname"></td>
1167      </tr>
1169    The example would iterate over the sequence of users returned by
1170    "user/list" and define the local variable "u" for each entry.
1172 **tal:replace="expression"**
1173    Replace this tag with the result of the expression. For example::
1175     <span tal:replace="request/user/realname" />
1177    The example would replace the <span> tag and its contents with the
1178    user's realname. If the user's realname was "Bruce", then the
1179    resultant output would be "Bruce".
1181 **tal:content="expression"**
1182    Replace the contents of this tag with the result of the expression.
1183    For example::
1185     <span tal:content="request/user/realname">user's name appears here
1186     </span>
1188    The example would replace the contents of the <span> tag with the
1189    user's realname. If the user's realname was "Bruce" then the
1190    resultant output would be "<span>Bruce</span>".
1192 **tal:attributes="attribute expression; attribute expression; ..."**
1193    Set attributes on this tag to the results of expressions. For
1194    example::
1196      <a tal:attributes="href string:user${request/user/id}">My Details</a>
1198    In the example, the "href" attribute of the <a> tag is set to the
1199    value of the "string:user${request/user/id}" expression, which will
1200    be something like "user123".
1202 **tal:omit-tag="expression"**
1203    Remove this tag (but not its contents) if the expression is true. For
1204    example::
1206       <span tal:omit-tag="python:1">Hello, world!</span>
1208    would result in output of::
1210       Hello, world!
1212 Note that the commands on a given tag are evaulated in the order above,
1213 so *define* comes before *condition*, and so on.
1215 Additionally, you may include tags such as <tal:block>, which are
1216 removed from output. Its content is kept, but the tag itself is not (so
1217 don't go using any "tal:attributes" commands on it). This is useful for
1218 making arbitrary blocks of HTML conditional or repeatable (very handy
1219 for repeating multiple table rows, which would othewise require an
1220 illegal tag placement to effect the repeat).
1223 Templating Expressions
1224 ~~~~~~~~~~~~~~~~~~~~~~
1226 The expressions you may use in the attribute values may be one of the
1227 following forms:
1229 **Path Expressions** - eg. ``item/status/checklist``
1230    These are object attribute / item accesses. Roughly speaking, the
1231    path ``item/status/checklist`` is broken into parts ``item``,
1232    ``status`` and ``checklist``. The ``item`` part is the root of the
1233    expression. We then look for a ``status`` attribute on ``item``, or
1234    failing that, a ``status`` item (as in ``item['status']``). If that
1235    fails, the path expression fails. When we get to the end, the object
1236    we're left with is evaluated to get a string - if it is a method, it
1237    is called; if it is an object, it is stringified. Path expressions
1238    may have an optional ``path:`` prefix, but they are the default
1239    expression type, so it's not necessary.
1241    If an expression evaluates to ``default``, then the expression is
1242    "cancelled" - whatever HTML already exists in the template will
1243    remain (tag content in the case of ``tal:content``, attributes in the
1244    case of ``tal:attributes``).
1246    If an expression evaluates to ``nothing`` then the target of the
1247    expression is removed (tag content in the case of ``tal:content``,
1248    attributes in the case of ``tal:attributes`` and the tag itself in
1249    the case of ``tal:replace``).
1251    If an element in the path may not exist, then you can use the ``|``
1252    operator in the expression to provide an alternative. So, the
1253    expression ``request/form/foo/value | default`` would simply leave
1254    the current HTML in place if the "foo" form variable doesn't exist.
1256    You may use the python function ``path``, as in
1257    ``path("item/status")``, to embed path expressions in Python
1258    expressions.
1260 **String Expressions** - eg. ``string:hello ${user/name}`` 
1261    These expressions are simple string interpolations - though they can
1262    be just plain strings with no interpolation if you want. The
1263    expression in the ``${ ... }`` is just a path expression as above.
1265 **Python Expressions** - eg. ``python: 1+1`` 
1266    These expressions give the full power of Python. All the "root level"
1267    variables are available, so ``python:item.status.checklist()`` would
1268    be equivalent to ``item/status/checklist``, assuming that
1269    ``checklist`` is a method.
1271 Modifiers:
1273 **structure** - eg. ``structure python:msg.content.plain(hyperlink=1)``
1274    The result of expressions are normally *escaped* to be safe for HTML
1275    display (all "<", ">" and "&" are turned into special entities). The
1276    ``structure`` expression modifier turns off this escaping - the
1277    result of the expression is now assumed to be HTML, which is passed
1278    to the web browser for rendering.
1280 **not:** - eg. ``not:python:1=1``
1281    This simply inverts the logical true/false value of another
1282    expression.
1285 Template Macros
1286 ~~~~~~~~~~~~~~~
1288 Macros are used in Roundup to save us from repeating the same common
1289 page stuctures over and over. The most common (and probably only) macro
1290 you'll use is the "icing" macro defined in the "page" template.
1292 Macros are generated and used inside your templates using special
1293 attributes similar to the `basic templating actions`_. In this case,
1294 though, the attributes belong to the Macro Expansion Template Attribute
1295 Language, or METAL. The macro commands are:
1297 **metal:define-macro="macro name"**
1298   Define that the tag and its contents are now a macro that may be
1299   inserted into other templates using the *use-macro* command. For
1300   example::
1302     <html metal:define-macro="page">
1303      ...
1304     </html>
1306   defines a macro called "page" using the ``<html>`` tag and its
1307   contents. Once defined, macros are stored on the template they're
1308   defined on in the ``macros`` attribute. You can access them later on
1309   through the ``templates`` variable, eg. the most common
1310   ``templates/page/macros/icing`` to access the "page" macro of the
1311   "page" template.
1313 **metal:use-macro="path expression"**
1314   Use a macro, which is identified by the path expression (see above).
1315   This will replace the current tag with the identified macro contents.
1316   For example::
1318    <tal:block metal:use-macro="templates/page/macros/icing">
1319     ...
1320    </tal:block>
1322    will replace the tag and its contents with the "page" macro of the
1323    "page" template.
1325 **metal:define-slot="slot name"** and **metal:fill-slot="slot name"**
1326   To define *dynamic* parts of the macro, you define "slots" which may
1327   be filled when the macro is used with a *use-macro* command. For
1328   example, the ``templates/page/macros/icing`` macro defines a slot like
1329   so::
1331     <title metal:define-slot="head_title">title goes here</title>
1333   In your *use-macro* command, you may now use a *fill-slot* command
1334   like this::
1336     <title metal:fill-slot="head_title">My Title</title>
1338   where the tag that fills the slot completely replaces the one defined
1339   as the slot in the macro.
1341 Note that you may not mix METAL and TAL commands on the same tag, but
1342 TAL commands may be used freely inside METAL-using tags (so your
1343 *fill-slots* tags may have all manner of TAL inside them).
1346 Information available to templates
1347 ----------------------------------
1349 Note: this is implemented by
1350 ``roundup.cgi.templating.RoundupPageTemplate``
1352 The following variables are available to templates.
1354 **context**
1355   The current context. This is either None, a `hyperdb class wrapper`_
1356   or a `hyperdb item wrapper`_
1357 **request**
1358   Includes information about the current request, including:
1359    - the current index information (``filterspec``, ``filter`` args,
1360      ``properties``, etc) parsed out of the form. 
1361    - methods for easy filterspec link generation
1362    - *user*, the current user item as an HTMLItem instance
1363    - *form*
1364      The current CGI form information as a mapping of form argument name
1365      to value
1366 **config**
1367   This variable holds all the values defined in the tracker config.py
1368   file (eg. TRACKER_NAME, etc.)
1369 **db**
1370   The current database, used to access arbitrary database items.
1371 **templates**
1372   Access to all the tracker templates by name. Used mainly in
1373   *use-macro* commands.
1374 **utils**
1375   This variable makes available some utility functions like batching.
1376 **nothing**
1377   This is a special variable - if an expression evaluates to this, then
1378   the tag (in the case of a ``tal:replace``), its contents (in the case
1379   of ``tal:content``) or some attributes (in the case of
1380   ``tal:attributes``) will not appear in the the output. So, for
1381   example::
1383     <span tal:attributes="class nothing">Hello, World!</span>
1385   would result in::
1387     <span>Hello, World!</span>
1389 **default**
1390   Also a special variable - if an expression evaluates to this, then the
1391   existing HTML in the template will not be replaced or removed, it will
1392   remain. So::
1394     <span tal:replace="default">Hello, World!</span>
1396   would result in::
1398     <span>Hello, World!</span>
1401 The context variable
1402 ~~~~~~~~~~~~~~~~~~~~
1404 The *context* variable is one of three things based on the current
1405 context (see `determining web context`_ for how we figure this out):
1407 1. if we're looking at a "home" page, then it's None
1408 2. if we're looking at a specific hyperdb class, it's a
1409    `hyperdb class wrapper`_.
1410 3. if we're looking at a specific hyperdb item, it's a
1411    `hyperdb item wrapper`_.
1413 If the context is not None, we can access the properties of the class or
1414 item. The only real difference between cases 2 and 3 above are:
1416 1. the properties may have a real value behind them, and this will
1417    appear if the property is displayed through ``context/property`` or
1418    ``context/property/field``.
1419 2. the context's "id" property will be a false value in the second case,
1420    but a real, or true value in the third. Thus we can determine whether
1421    we're looking at a real item from the hyperdb by testing
1422    "context/id".
1424 Hyperdb class wrapper
1425 :::::::::::::::::::::
1427 Note: this is implemented by the ``roundup.cgi.templating.HTMLClass``
1428 class.
1430 This wrapper object provides access to a hyperb class. It is used
1431 primarily in both index view and new item views, but it's also usable
1432 anywhere else that you wish to access information about a class, or the
1433 items of a class, when you don't have a specific item of that class in
1434 mind.
1436 We allow access to properties. There will be no "id" property. The value
1437 accessed through the property will be the current value of the same name
1438 from the CGI form.
1440 There are several methods available on these wrapper objects:
1442 =========== =============================================================
1443 Method      Description
1444 =========== =============================================================
1445 properties  return a `hyperdb property wrapper`_ for all of this class's
1446             properties.
1447 list        lists all of the active (not retired) items in the class.
1448 csv         return the items of this class as a chunk of CSV text.
1449 propnames   lists the names of the properties of this class.
1450 filter      lists of items from this class, filtered and sorted by the
1451             current *request* filterspec/filter/sort/group args
1452 classhelp   display a link to a javascript popup containing this class'
1453             "help" template.
1454 submit      generate a submit button (and action hidden element)
1455 renderWith  render this class with the given template.
1456 history     returns 'New node - no history' :)
1457 is_edit_ok  is the user allowed to Edit the current class?
1458 is_view_ok  is the user allowed to View the current class?
1459 =========== =============================================================
1461 Note that if you have a property of the same name as one of the above
1462 methods, you'll need to access it using a python "item access"
1463 expression. For example::
1465    python:context['list']
1467 will access the "list" property, rather than the list method.
1470 Hyperdb item wrapper
1471 ::::::::::::::::::::
1473 Note: this is implemented by the ``roundup.cgi.templating.HTMLItem``
1474 class.
1476 This wrapper object provides access to a hyperb item.
1478 We allow access to properties. There will be no "id" property. The value
1479 accessed through the property will be the current value of the same name
1480 from the CGI form.
1482 There are several methods available on these wrapper objects:
1484 =============== ========================================================
1485 Method          Description
1486 =============== ========================================================
1487 submit          generate a submit button (and action hidden element)
1488 journal         return the journal of the current item (**not
1489                 implemented**)
1490 history         render the journal of the current item as HTML
1491 renderQueryForm specific to the "query" class - render the search form
1492                 for the query
1493 hasPermission   specific to the "user" class - determine whether the
1494                 user has a Permission
1495 is_edit_ok      is the user allowed to Edit the current item?
1496 is_view_ok      is the user allowed to View the current item?
1497 =============== ========================================================
1499 Note that if you have a property of the same name as one of the above
1500 methods, you'll need to access it using a python "item access"
1501 expression. For example::
1503    python:context['journal']
1505 will access the "journal" property, rather than the journal method.
1508 Hyperdb property wrapper
1509 ::::::::::::::::::::::::
1511 Note: this is implemented by subclasses of the
1512 ``roundup.cgi.templating.HTMLProperty`` class (``HTMLStringProperty``,
1513 ``HTMLNumberProperty``, and so on).
1515 This wrapper object provides access to a single property of a class. Its
1516 value may be either:
1518 1. if accessed through a `hyperdb item wrapper`_, then it's a value from
1519    the hyperdb
1520 2. if access through a `hyperdb class wrapper`_, then it's a value from
1521    the CGI form
1524 The property wrapper has some useful attributes:
1526 =============== ========================================================
1527 Attribute       Description
1528 =============== ========================================================
1529 _name           the name of the property
1530 _value          the value of the property if any - this is the actual
1531                 value retrieved from the hyperdb for this property
1532 =============== ========================================================
1534 There are several methods available on these wrapper objects:
1536 =========== ================================================================
1537 Method      Description
1538 =========== ================================================================
1539 plain       render a "plain" representation of the property. This method
1540             may take two arguments:
1542             escape
1543              If true, escape the text so it is HTML safe (default: no). The
1544              reason this defaults to off is that text is usually escaped
1545              at a later stage by the TAL commands, unless the "structure"
1546              option is used in the template. The following ``tal:content``
1547              expressions are all equivalent::
1548  
1549               "structure python:msg.content.plain(escape=1)"
1550               "python:msg.content.plain()"
1551               "msg/content/plain"
1552               "msg/content"
1554              Usually you'll only want to use the escape option in a
1555              complex expression.
1557             hyperlink
1558              If true, turn URLs, email addresses and hyperdb item
1559              designators in the text into hyperlinks (default: no). Note
1560              that you'll need to use the "structure" TAL option if you
1561              want to use this ``tal:content`` expression::
1562   
1563               "structure python:msg.content.plain(hyperlink=1)"
1565              Note also that the text is automatically HTML-escaped before
1566              the hyperlinking transformation.
1567 hyperlinked The same as msg.content.plain(hyperlink=1), but nicer::
1569               "structure msg/content/hyperlinked"
1571 field       render an appropriate form edit field for the property - for
1572             most types this is a text entry box, but for Booleans it's a
1573             tri-state yes/no/neither selection.
1574 stext       only on String properties - render the value of the property
1575             as StructuredText (requires the StructureText module to be
1576             installed separately)
1577 multiline   only on String properties - render a multiline form edit
1578             field for the property
1579 email       only on String properties - render the value of the property
1580             as an obscured email address
1581 confirm     only on Password properties - render a second form edit field
1582             for the property, used for confirmation that the user typed
1583             the password correctly. Generates a field with name
1584             "name:confirm".
1585 now         only on Date properties - return the current date as a new
1586             property
1587 reldate     only on Date properties - render the interval between the date
1588             and now
1589 local       only on Date properties - return this date as a new property
1590             with some timezone offset, for example::
1591             
1592                 python:context.creation.local(10)
1594             will render the date with a +10 hour offset.
1595 pretty      only on Interval properties - render the interval in a pretty
1596             format (eg. "yesterday")
1597 menu        only on Link and Multilink properties - render a form select
1598             list for this property
1599 reverse     only on Multilink properties - produce a list of the linked
1600             items in reverse order
1601 =========== ================================================================
1604 The request variable
1605 ~~~~~~~~~~~~~~~~~~~~
1607 Note: this is implemented by the ``roundup.cgi.templating.HTMLRequest``
1608 class.
1610 The request variable is packed with information about the current
1611 request.
1613 .. taken from ``roundup.cgi.templating.HTMLRequest`` docstring
1615 =========== ============================================================
1616 Variable    Holds
1617 =========== ============================================================
1618 form        the CGI form as a cgi.FieldStorage
1619 env         the CGI environment variables
1620 base        the base URL for this tracker
1621 user        a HTMLUser instance for this user
1622 classname   the current classname (possibly None)
1623 template    the current template (suffix, also possibly None)
1624 form        the current CGI form variables in a FieldStorage
1625 =========== ============================================================
1627 **Index page specific variables (indexing arguments)**
1629 =========== ============================================================
1630 Variable    Holds
1631 =========== ============================================================
1632 columns     dictionary of the columns to display in an index page
1633 show        a convenience access to columns - request/show/colname will
1634             be true if the columns should be displayed, false otherwise
1635 sort        index sort column (direction, column name)
1636 group       index grouping property (direction, column name)
1637 filter      properties to filter the index on
1638 filterspec  values to filter the index on
1639 search_text text to perform a full-text search on for an index
1640 =========== ============================================================
1642 There are several methods available on the request variable:
1644 =============== ========================================================
1645 Method          Description
1646 =============== ========================================================
1647 description     render a description of the request - handle for the
1648                 page title
1649 indexargs_form  render the current index args as form elements
1650 indexargs_url   render the current index args as a URL
1651 base_javascript render some javascript that is used by other components
1652                 of the templating
1653 batch           run the current index args through a filter and return a
1654                 list of items (see `hyperdb item wrapper`_, and
1655                 `batching`_)
1656 =============== ========================================================
1658 The form variable
1659 :::::::::::::::::
1661 The form variable is a bit special because it's actually a python
1662 FieldStorage object. That means that you have two ways to access its
1663 contents. For example, to look up the CGI form value for the variable
1664 "name", use the path expression::
1666    request/form/name/value
1668 or the python expression::
1670    python:request.form['name'].value
1672 Note the "item" access used in the python case, and also note the
1673 explicit "value" attribute we have to access. That's because the form
1674 variables are stored as MiniFieldStorages. If there's more than one
1675 "name" value in the form, then the above will break since
1676 ``request/form/name`` is actually a *list* of MiniFieldStorages. So it's
1677 best to know beforehand what you're dealing with.
1680 The db variable
1681 ~~~~~~~~~~~~~~~
1683 Note: this is implemented by the ``roundup.cgi.templating.HTMLDatabase``
1684 class.
1686 Allows access to all hyperdb classes as attributes of this variable. If
1687 you want access to the "user" class, for example, you would use::
1689   db/user
1690   python:db.user
1692 Also, the current id of the current user is available as
1693 ``db.getuid()``. This isn't so useful in templates (where you have
1694 ``request/user``), but it can be useful in detectors or interfaces.
1696 The access results in a `hyperdb class wrapper`_.
1699 The templates variable
1700 ~~~~~~~~~~~~~~~~~~~~~~
1702 Note: this is implemented by the ``roundup.cgi.templating.Templates``
1703 class.
1705 This variable doesn't have any useful methods defined. It supports being
1706 used in expressions to access the templates, and consequently the
1707 template macros. You may access the templates using the following path
1708 expression::
1710    templates/name
1712 or the python expression::
1714    templates[name]
1716 where "name" is the name of the template you wish to access. The
1717 template has one useful attribute, namely "macros". To access a specific
1718 macro (called "macro_name"), use the path expression::
1720    templates/name/macros/macro_name
1722 or the python expression::
1724    templates[name].macros[macro_name]
1727 The utils variable
1728 ~~~~~~~~~~~~~~~~~~
1730 Note: this is implemented by the
1731 ``roundup.cgi.templating.TemplatingUtils`` class, but it may be extended
1732 as described below.
1734 =============== ========================================================
1735 Method          Description
1736 =============== ========================================================
1737 Batch           return a batch object using the supplied list
1738 =============== ========================================================
1740 You may add additional utility methods by writing them in your tracker
1741 ``interfaces.py`` module's ``TemplatingUtils`` class. See `adding a time
1742 log to your issues`_ for an example. The TemplatingUtils class itself
1743 will have a single attribute, ``client``, which may be used to access
1744 the ``client.db`` when you need to perform arbitrary database queries.
1746 Batching
1747 ::::::::
1749 Use Batch to turn a list of items, or item ids of a given class, into a
1750 series of batches. Its usage is::
1752     python:utils.Batch(sequence, size, start, end=0, orphan=0,
1753     overlap=0)
1755 or, to get the current index batch::
1757     request/batch
1759 The parameters are:
1761 ========= ==============================================================
1762 Parameter  Usage
1763 ========= ==============================================================
1764 sequence  a list of HTMLItems
1765 size      how big to make the sequence.
1766 start     where to start (0-indexed) in the sequence.
1767 end       where to end (0-indexed) in the sequence.
1768 orphan    if the next batch would contain less items than this value,
1769           then it is combined with this batch
1770 overlap   the number of items shared between adjacent batches
1771 ========= ==============================================================
1773 All of the parameters are assigned as attributes on the batch object. In
1774 addition, it has several more attributes:
1776 =============== ========================================================
1777 Attribute       Description
1778 =============== ========================================================
1779 start           indicates the start index of the batch. *Note: unlike
1780                 the argument, is a 1-based index (I know, lame)*
1781 first           indicates the start index of the batch *as a 0-based
1782                 index*
1783 length          the actual number of elements in the batch
1784 sequence_length the length of the original, unbatched, sequence.
1785 =============== ========================================================
1787 And several methods:
1789 =============== ========================================================
1790 Method          Description
1791 =============== ========================================================
1792 previous        returns a new Batch with the previous batch settings
1793 next            returns a new Batch with the next batch settings
1794 propchanged     detect if the named property changed on the current item
1795                 when compared to the last item
1796 =============== ========================================================
1798 An example of batching::
1800  <table class="otherinfo">
1801   <tr><th colspan="4" class="header">Existing Keywords</th></tr>
1802   <tr tal:define="keywords db/keyword/list"
1803       tal:repeat="start python:range(0, len(keywords), 4)">
1804    <td tal:define="batch python:utils.Batch(keywords, 4, start)"
1805        tal:repeat="keyword batch" tal:content="keyword/name">
1806        keyword here</td>
1807   </tr>
1808  </table>
1810 ... which will produce a table with four columns containing the items of
1811 the "keyword" class (well, their "name" anyway).
1813 Displaying Properties
1814 ---------------------
1816 Properties appear in the user interface in three contexts: in indices,
1817 in editors, and as search arguments. For each type of property, there
1818 are several display possibilities. For example, in an index view, a
1819 string property may just be printed as a plain string, but in an editor
1820 view, that property may be displayed in an editable field.
1823 Index Views
1824 -----------
1826 This is one of the class context views. It is also the default view for
1827 classes. The template used is "*classname*.index".
1830 Index View Specifiers
1831 ~~~~~~~~~~~~~~~~~~~~~
1833 An index view specifier (URL fragment) looks like this (whitespace has
1834 been added for clarity)::
1836      /issue?status=unread,in-progress,resolved&
1837             topic=security,ui&
1838             :group=+priority&
1839             :sort==activity&
1840             :filters=status,topic&
1841             :columns=title,status,fixer
1843 The index view is determined by two parts of the specifier: the layout
1844 part and the filter part. The layout part consists of the query
1845 parameters that begin with colons, and it determines the way that the
1846 properties of selected items are displayed. The filter part consists of
1847 all the other query parameters, and it determines the criteria by which
1848 items are selected for display. The filter part is interactively
1849 manipulated with the form widgets displayed in the filter section. The
1850 layout part is interactively manipulated by clicking on the column
1851 headings in the table.
1853 The filter part selects the union of the sets of items with values
1854 matching any specified Link properties and the intersection of the sets
1855 of items with values matching any specified Multilink properties.
1857 The example specifies an index of "issue" items. Only items with a
1858 "status" of either "unread" or "in-progress" or "resolved" are
1859 displayed, and only items with "topic" values including both "security"
1860 and "ui" are displayed. The items are grouped by priority, arranged in
1861 ascending order; and within groups, sorted by activity, arranged in
1862 descending order. The filter section shows filters for the "status" and
1863 "topic" properties, and the table includes columns for the "title",
1864 "status", and "fixer" properties.
1866 Searching Views
1867 ---------------
1869 Note: if you add a new column to the ``:columns`` form variable
1870       potentials then you will need to add the column to the appropriate
1871       `index views`_ template so that it is actually displayed.
1873 This is one of the class context views. The template used is typically
1874 "*classname*.search". The form on this page should have "search" as its
1875 ``@action`` variable. The "search" action:
1877 - sets up additional filtering, as well as performing indexed text
1878   searching
1879 - sets the ``:filter`` variable correctly
1880 - saves the query off if ``:query_name`` is set.
1882 The search page should lay out any fields that you wish to allow the
1883 user to search on. If your schema contains a large number of properties,
1884 you should be wary of making all of those properties available for
1885 searching, as this can cause confusion. If the additional properties are
1886 Strings, consider having their value indexed, and then they will be
1887 searchable using the full text indexed search. This is both faster, and
1888 more useful for the end user.
1890 The two special form values on search pages which are handled by the
1891 "search" action are:
1893 :search_text
1894   Text with which to perform a search of the text index. Results from
1895   that search will be used to limit the results of other filters (using
1896   an intersection operation)
1897 :query_name
1898   If supplied, the search parameters (including :search_text) will be
1899   saved off as a the query item and registered against the user's
1900   queries property. Note that the *classic* template schema has this
1901   ability, but the *minimal* template schema does not.
1904 Item Views
1905 ----------
1907 The basic view of a hyperdb item is provided by the "*classname*.item"
1908 template. It generally has three sections; an "editor", a "spool" and a
1909 "history" section.
1912 Editor Section
1913 ~~~~~~~~~~~~~~
1915 The editor section is used to manipulate the item - it may be a static
1916 display if the user doesn't have permission to edit the item.
1918 Here's an example of a basic editor template (this is the default
1919 "classic" template issue item edit form - from the "issue.item.html"
1920 template)::
1922  <table class="form">
1923  <tr>
1924   <th>Title</th>
1925   <td colspan="3" tal:content="structure python:context.title.field(size=60)">title</td>
1926  </tr>
1927  
1928  <tr>
1929   <th>Priority</th>
1930   <td tal:content="structure context/priority/menu">priority</td>
1931   <th>Status</th>
1932   <td tal:content="structure context/status/menu">status</td>
1933  </tr>
1934  
1935  <tr>
1936   <th>Superseder</th>
1937   <td>
1938    <span tal:replace="structure python:context.superseder.field(showid=1, size=20)" />
1939    <span tal:replace="structure python:db.issue.classhelp('id,title')" />
1940    <span tal:condition="context/superseder">
1941     <br>View: <span tal:replace="structure python:context.superseder.link(showid=1)" />
1942    </span>
1943   </td>
1944   <th>Nosy List</th>
1945   <td>
1946    <span tal:replace="structure context/nosy/field" />
1947    <span tal:replace="structure python:db.user.classhelp('username,realname,address,phone')" />
1948   </td>
1949  </tr>
1950  
1951  <tr>
1952   <th>Assigned To</th>
1953   <td tal:content="structure context/assignedto/menu">
1954    assignedto menu
1955   </td>
1956   <td>&nbsp;</td>
1957   <td>&nbsp;</td>
1958  </tr>
1959  
1960  <tr>
1961   <th>Change Note</th>
1962   <td colspan="3">
1963    <textarea name=":note" wrap="hard" rows="5" cols="60"></textarea>
1964   </td>
1965  </tr>
1966  
1967  <tr>
1968   <th>File</th>
1969   <td colspan="3"><input type="file" name=":file" size="40"></td>
1970  </tr>
1971  
1972  <tr>
1973   <td>&nbsp;</td>
1974   <td colspan="3" tal:content="structure context/submit">
1975    submit button will go here
1976   </td>
1977  </tr>
1978  </table>
1981 When a change is submitted, the system automatically generates a message
1982 describing the changed properties. As shown in the example, the editor
1983 template can use the ":note" and ":file" fields, which are added to the
1984 standard changenote message generated by Roundup.
1987 Form values
1988 :::::::::::
1990 We have a number of ways to pull properties out of the form in order to
1991 meet the various needs of:
1993 1. editing the current item (perhaps an issue item)
1994 2. editing information related to the current item (eg. messages or
1995    attached files)
1996 3. creating new information to be linked to the current item (eg. time
1997    spent on an issue)
1999 In the following, ``<bracketed>`` values are variable, ":" may be one of
2000 ":" or "@", and other text ("required") is fixed.
2002 Properties are specified as form variables:
2004 ``<propname>``
2005   property on the current context item
2007 ``<designator>:<propname>``
2008   property on the indicated item (for editing related information)
2010 ``<classname>-<N>:<propname>``
2011   property on the Nth new item of classname (generally for creating new
2012   items to attach to the current item)
2014 Once we have determined the "propname", we check to see if it is one of
2015 the special form values:
2017 ``@required``
2018   The named property values must be supplied or a ValueError will be
2019   raised.
2021 ``@remove@<propname>=id(s)``
2022   The ids will be removed from the multilink property.
2024 ``:add:<propname>=id(s)``
2025   The ids will be added to the multilink property.
2027 ``:link:<propname>=<designator>``
2028   Used to add a link to new items created during edit. These are
2029   collected and returned in ``all_links``. This will result in an
2030   additional linking operation (either Link set or Multilink append)
2031   after the edit/create is done using ``all_props`` in ``_editnodes``.
2032   The <propname> on the current item will be set/appended the id of the
2033   newly created item of class <designator> (where <designator> must be
2034   <classname>-<N>).
2036 Any of the form variables may be prefixed with a classname or
2037 designator.
2039 Two special form values are supported for backwards compatibility:
2041 ``:note``
2042   create a message (with content, author and date), linked to the
2043   context item. This is ALWAYS designated "msg-1".
2044 ``:file``
2045   create a file, attached to the current item and any message created by
2046   :note. This is ALWAYS designated "file-1".
2049 Spool Section
2050 ~~~~~~~~~~~~~
2052 The spool section lists related information like the messages and files
2053 of an issue.
2055 TODO
2058 History Section
2059 ~~~~~~~~~~~~~~~
2061 The final section displayed is the history of the item - its database
2062 journal. This is generally generated with the template::
2064  <tal:block tal:replace="structure context/history" />
2066 *To be done:*
2068 *The actual history entries of the item may be accessed for manual
2069 templating through the "journal" method of the item*::
2071  <tal:block tal:repeat="entry context/journal">
2072   a journal entry
2073  </tal:block>
2075 *where each journal entry is an HTMLJournalEntry.*
2077 Defining new web actions
2078 ------------------------
2080 You may define new actions to be triggered by the ``@action`` form variable.
2081 These are added to the tracker ``interfaces.py`` as ``Action`` classes that get
2082 called by the the ``Client`` class.
2084 Adding action classes takes three steps; first you `define the new
2085 action class`_, then you `register the action class`_ with the cgi
2086 interface so it may be triggered by the ``@action`` form variable.
2087 Finally you `use the new action`_ in your HTML form.
2089 See "`setting up a "wizard" (or "druid") for controlled adding of
2090 issues`_" for an example.
2093 Define the new action class
2094 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
2096 The action classes have the following interface::
2098  class MyAction(Action):
2099      def handle(self):
2100          ''' Perform some action. No return value is required.
2101          '''
2103 The *self.client* attribute is an instance of your tracker ``instance.Client``
2104 class - thus it's mostly implemented by ``roundup.cgi.Client``. See the
2105 docstring of that class for details of what it can do.
2107 The method will typically check the ``self.form`` variable's contents.
2108 It may then:
2110 - add information to ``self.client.ok_message`` or ``self.client.error_message``
2111 - change the ``self.client.template`` variable to alter what the user will see
2112   next
2113 - raise Unauthorised, SendStaticFile, SendFile, NotFound or Redirect
2114   exceptions (import them from roundup.cgi.exceptions)
2117 Register the action class
2118 ~~~~~~~~~~~~~~~~~~~~~~~~~~
2120 The class is now written, but isn't available to the user until you add it to
2121 the ``instance.Client`` class ``actions`` variable, like so::
2123     actions = client.Client.actions + (
2124         ('myaction', myActionClass),
2125     )
2127 This maps the action name "myaction" to the action class we defined.
2129 Use the new action
2130 ~~~~~~~~~~~~~~~~~~
2132 In your HTML form, add a hidden form element like so::
2134   <input type="hidden" name="@action" value="myaction">
2136 where "myaction" is the name you registered in the previous step.
2139 Examples
2140 ========
2142 .. contents::
2143    :local:
2144    :depth: 1
2147 Adding a new field to the classic schema
2148 ----------------------------------------
2150 This example shows how to add a new constrained property (i.e. a
2151 selection of distinct values) to your tracker.
2154 Introduction
2155 ~~~~~~~~~~~~
2157 To make the classic schema of roundup useful as a TODO tracking system
2158 for a group of systems administrators, it needed an extra data field per
2159 issue: a category.
2161 This would let sysadmins quickly list all TODOs in their particular area
2162 of interest without having to do complex queries, and without relying on
2163 the spelling capabilities of other sysadmins (a losing proposition at
2164 best).
2167 Adding a field to the database
2168 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
2170 This is the easiest part of the change. The category would just be a
2171 plain string, nothing fancy. To change what is in the database you need
2172 to add some lines to the ``open()`` function in ``dbinit.py``. Under the
2173 comment::
2175     # add any additional database schema configuration here
2177 add::
2179     category = Class(db, "category", name=String())
2180     category.setkey("name")
2182 Here we are setting up a chunk of the database which we are calling
2183 "category". It contains a string, which we are refering to as "name" for
2184 lack of a more imaginative title. (Since "name" is one of the properties
2185 that Roundup looks for on items if you do not set a key for them, it's
2186 probably a good idea to stick with it for new classes if at all
2187 appropriate.) Then we are setting the key of this chunk of the database
2188 to be that "name". This is equivalent to an index for database types.
2189 This also means that there can only be one category with a given name.
2191 Adding the above lines allows us to create categories, but they're not
2192 tied to the issues that we are going to be creating. It's just a list of
2193 categories off on its own, which isn't much use. We need to link it in
2194 with the issues. To do that, find the lines in the ``open()`` function
2195 in ``dbinit.py`` which set up the "issue" class, and then add a link to
2196 the category::
2198     issue = IssueClass(db, "issue", ... ,
2199         category=Multilink("category"), ... )
2201 The ``Multilink()`` means that each issue can have many categories. If
2202 you were adding something with a one-to-one relationship to issues (such
2203 as the "assignedto" property), use ``Link()`` instead.
2205 That is all you need to do to change the schema. The rest of the effort
2206 is fiddling around so you can actually use the new category.
2209 Populating the new category class
2210 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
2212 If you haven't initialised the database with the roundup-admin
2213 "initialise" command, then you can add the following to the tracker
2214 ``dbinit.py`` in the ``init()`` function under the comment::
2216     # add any additional database create steps here - but only if you
2217     # haven't initialised the database with the admin "initialise" command
2219 Add::
2221      category = db.getclass('category')
2222      category.create(name="scipy", order="1")
2223      category.create(name="chaco", order="2")
2224      category.create(name="weave", order="3")
2226 If the database has already been initalised, then you need to use the
2227 ``roundup-admin`` tool::
2229      % roundup-admin -i <tracker home>
2230      Roundup <version> ready for input.
2231      Type "help" for help.
2232      roundup> create category name=scipy order=1
2233      1
2234      roundup> create category name=chaco order=1
2235      2
2236      roundup> create category name=weave order=1
2237      3
2238      roundup> exit...
2239      There are unsaved changes. Commit them (y/N)? y
2241 TODO: explain why order=1 in each case. Also, does key get set to "name"
2242 automatically when added via roundup-admin?
2245 Setting up security on the new objects
2246 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
2248 By default only the admin user can look at and change objects. This
2249 doesn't suit us, as we want any user to be able to create new categories
2250 as required, and obviously everyone needs to be able to view the
2251 categories of issues for it to be useful.
2253 We therefore need to change the security of the category objects. This
2254 is also done in the ``open()`` function of ``dbinit.py``.
2256 There are currently two loops which set up permissions and then assign
2257 them to various roles. Simply add the new "category" to both lists::
2259     # new permissions for this schema
2260     for cl in 'issue', 'file', 'msg', 'user', 'category':
2261         db.security.addPermission(name="Edit", klass=cl,
2262             description="User is allowed to edit "+cl)
2263         db.security.addPermission(name="View", klass=cl,
2264             description="User is allowed to access "+cl)
2266     # Assign the access and edit permissions for issue, file and message
2267     # to regular users now
2268     for cl in 'issue', 'file', 'msg', 'category':
2269         p = db.security.getPermission('View', cl)
2270         db.security.addPermissionToRole('User', p)
2271         p = db.security.getPermission('Edit', cl)
2272         db.security.addPermissionToRole('User', p)
2274 So you are in effect doing the following (with 'cl' substituted by its
2275 value)::
2277     db.security.addPermission(name="Edit", klass='category',
2278         description="User is allowed to edit "+'category')
2279     db.security.addPermission(name="View", klass='category',
2280         description="User is allowed to access "+'category')
2282 which is creating two permission types; that of editing and viewing
2283 "category" objects respectively. Then the following lines assign those
2284 new permissions to the "User" role, so that normal users can view and
2285 edit "category" objects::
2287     p = db.security.getPermission('View', 'category')
2288     db.security.addPermissionToRole('User', p)
2290     p = db.security.getPermission('Edit', 'category')
2291     db.security.addPermissionToRole('User', p)
2293 This is all the work that needs to be done for the database. It will
2294 store categories, and let users view and edit them. Now on to the
2295 interface stuff.
2298 Changing the web left hand frame
2299 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
2301 We need to give the users the ability to create new categories, and the
2302 place to put the link to this functionality is in the left hand function
2303 bar, under the "Issues" area. The file that defines how this area looks
2304 is ``html/page``, which is what we are going to be editing next.
2306 If you look at this file you can see that it contains a lot of
2307 "classblock" sections which are chunks of HTML that will be included or
2308 excluded in the output depending on whether the condition in the
2309 classblock is met. Under the end of the classblock for issue is where we
2310 are going to add the category code::
2312   <p class="classblock"
2313      tal:condition="python:request.user.hasPermission('View', 'category')">
2314    <b>Categories</b><br>
2315    <a tal:condition="python:request.user.hasPermission('Edit', 'category')"
2316       href="category?@template=item">New Category<br></a>
2317   </p>
2319 The first two lines is the classblock definition, which sets up a
2320 condition that only users who have "View" permission for the "category"
2321 object will have this section included in their output. Next comes a
2322 plain "Categories" header in bold. Everyone who can view categories will
2323 get that.
2325 Next comes the link to the editing area of categories. This link will
2326 only appear if the condition - that the user has "Edit" permissions for
2327 the "category" objects - is matched. If they do have permission then
2328 they will get a link to another page which will let the user add new
2329 categories.
2331 Note that if you have permission to *view* but not to *edit* categories,
2332 then all you will see is a "Categories" header with nothing underneath
2333 it. This is obviously not very good interface design, but will do for
2334 now. I just claim that it is so I can add more links in this section
2335 later on. However to fix the problem you could change the condition in
2336 the classblock statement, so that only users with "Edit" permission
2337 would see the "Categories" stuff.
2340 Setting up a page to edit categories
2341 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
2343 We defined code in the previous section which let users with the
2344 appropriate permissions see a link to a page which would let them edit
2345 conditions. Now we have to write that page.
2347 The link was for the *item* template of the *category* object. This
2348 translates into Roundup looking for a file called ``category.item.html``
2349 in the ``html`` tracker directory. This is the file that we are going to
2350 write now.
2352 First we add an info tag in a comment which doesn't affect the outcome
2353 of the code at all, but is useful for debugging. If you load a page in a
2354 browser and look at the page source, you can see which sections come
2355 from which files by looking for these comments::
2357     <!-- category.item -->
2359 Next we need to add in the METAL macro stuff so we get the normal page
2360 trappings::
2362  <tal:block metal:use-macro="templates/page/macros/icing">
2363   <title metal:fill-slot="head_title">Category editing</title>
2364   <td class="page-header-top" metal:fill-slot="body_title">
2365    <h2>Category editing</h2>
2366   </td>
2367   <td class="content" metal:fill-slot="content">
2369 Next we need to setup up a standard HTML form, which is the whole
2370 purpose of this file. We link to some handy javascript which sends the
2371 form through only once. This is to stop users hitting the send button
2372 multiple times when they are impatient and thus having the form sent
2373 multiple times::
2375     <form method="POST" onSubmit="return submit_once()"
2376           enctype="multipart/form-data">
2378 Next we define some code which sets up the minimum list of fields that
2379 we require the user to enter. There will be only one field - "name" - so
2380 they better put something in it, otherwise the whole form is pointless::
2382     <input type="hidden" name="@required" value="name">
2384 To get everything to line up properly we will put everything in a table,
2385 and put a nice big header on it so the user has an idea what is
2386 happening::
2388     <table class="form">
2389      <tr><th class="header" colspan="2">Category</th></tr>
2391 Next, we need the field into which the user is going to enter the new
2392 category. The "context.name.field(size=60)" bit tells Roundup to
2393 generate a normal HTML field of size 60, and the contents of that field
2394 will be the "name" variable of the current context (which is
2395 "category"). The upshot of this is that when the user types something in
2396 to the form, a new category will be created with that name::
2398     <tr>
2399      <th>Name</th>
2400      <td tal:content="structure python:context.name.field(size=60)">
2401      name</td>
2402     </tr>
2404 Then a submit button so that the user can submit the new category::
2406     <tr>
2407      <td>&nbsp;</td>
2408      <td colspan="3" tal:content="structure context/submit">
2409       submit button will go here
2410      </td>
2411     </tr>
2413 Finally we finish off the tags we used at the start to do the METAL
2414 stuff::
2416   </td>
2417  </tal:block>
2419 So putting it all together, and closing the table and form we get::
2421  <!-- category.item -->
2422  <tal:block metal:use-macro="templates/page/macros/icing">
2423   <title metal:fill-slot="head_title">Category editing</title>
2424   <td class="page-header-top" metal:fill-slot="body_title">
2425    <h2>Category editing</h2>
2426   </td>
2427   <td class="content" metal:fill-slot="content">
2428    <form method="POST" onSubmit="return submit_once()"
2429          enctype="multipart/form-data">
2431     <table class="form">
2432      <tr><th class="header" colspan="2">Category</th></tr>
2434      <tr>
2435       <th>Name</th>
2436       <td tal:content="structure python:context.name.field(size=60)">
2437       name</td>
2438      </tr>
2440      <tr>
2441       <td>
2442         &nbsp;
2443         <input type="hidden" name="@required" value="name"> 
2444       </td>
2445       <td colspan="3" tal:content="structure context/submit">
2446        submit button will go here
2447       </td>
2448      </tr>
2449     </table>
2450    </form>
2451   </td>
2452  </tal:block>
2454 This is quite a lot to just ask the user one simple question, but there
2455 is a lot of setup for basically one line (the form line) to do its work.
2456 To add another field to "category" would involve one more line (well,
2457 maybe a few extra to get the formatting correct).
2460 Adding the category to the issue
2461 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
2463 We now have the ability to create issues to our heart's content, but
2464 that is pointless unless we can assign categories to issues.  Just like
2465 the ``html/category.item.html`` file was used to define how to add a new
2466 category, the ``html/issue.item.html`` is used to define how a new issue
2467 is created.
2469 Just like ``category.issue.html`` this file defines a form which has a
2470 table to lay things out. It doesn't matter where in the table we add new
2471 stuff, it is entirely up to your sense of aesthetics::
2473    <th>Category</th>
2474    <td><span tal:replace="structure context/category/field" />
2475        <span tal:replace="structure db/category/classhelp" />
2476    </td>
2478 First, we define a nice header so that the user knows what the next
2479 section is, then the middle line does what we are most interested in.
2480 This ``context/category/field`` gets replaced by a field which contains
2481 the category in the current context (the current context being the new
2482 issue).
2484 The classhelp lines generate a link (labelled "list") to a popup window
2485 which contains the list of currently known categories.
2488 Searching on categories
2489 ~~~~~~~~~~~~~~~~~~~~~~~
2491 We can add categories, and create issues with categories. The next
2492 obvious thing that we would like to be able to do, would be to search
2493 for issues based on their category, so that, for example, anyone working
2494 on the web server could look at all issues in the category "Web".
2496 If you look for "Search Issues" in the 'html/page.html' file, you will
2497 find that it looks something like 
2498 ``<a href="issue?@template=search">Search Issues</a>``. This shows us
2499 that when you click on "Search Issues" it will be looking for a
2500 ``issue.search.html`` file to display. So that is the file that we will
2501 change.
2503 If you look at this file it should be starting to seem familiar, although it
2504 does use some new macros. You can add the new category search code anywhere you
2505 like within that form::
2507   <tr tal:define="name string:category;
2508                   db_klass string:category;
2509                   db_content string:name;">
2510     <th>Priority:</th>
2511     <td metal:use-macro="search_select"></td>
2512     <td metal:use-macro="column_input"></td>
2513     <td metal:use-macro="sort_input"></td>
2514     <td metal:use-macro="group_input"></td>
2515   </tr>
2517 The definitions in the <tr> opening tag are used by the macros:
2519 - search_select expands to a drop-down box with all categories using db_klass
2520   and db_content.
2521 - column_input expands to a checkbox for selecting what columns should be
2522   displayed.
2523 - sort_input expands to a radio button for selecting what property should be
2524   sorted on.
2525 - group_input expands to a radio button for selecting what property should be
2526   group on.
2528 The category search code above would expand to the following::
2530   <tr>
2531     <th>Category:</th>
2532     <td>
2533       <select name="category">
2534         <option value="">don't care</option>
2535         <option value="">------------</option>      
2536         <option value="1">scipy</option>
2537         <option value="2">chaco</option>
2538         <option value="3">weave</option>
2539       </select>
2540     </td>
2541     <td><input type="checkbox" name=":columns" value="category"></td>
2542     <td><input type="radio" name=":sort" value="category"></td>
2543     <td><input type="radio" name=":group" value="category"></td>
2544   </tr>
2546 Adding category to the default view
2547 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
2549 We can now add categories, add issues with categories, and search for
2550 issues based on categories. This is everything that we need to do;
2551 however, there is some more icing that we would like. I think the
2552 category of an issue is important enough that it should be displayed by
2553 default when listing all the issues.
2555 Unfortunately, this is a bit less obvious than the previous steps. The
2556 code defining how the issues look is in ``html/issue.index.html``. This
2557 is a large table with a form down at the bottom for redisplaying and so
2558 forth. 
2560 Firstly we need to add an appropriate header to the start of the table::
2562     <th tal:condition="request/show/category">Category</th>
2564 The *condition* part of this statement is to avoid displaying the
2565 Category column if the user has selected not to see it.
2567 The rest of the table is a loop which will go through every issue that
2568 matches the display criteria. The loop variable is "i" - which means
2569 that every issue gets assigned to "i" in turn.
2571 The new part of code to display the category will look like this::
2573     <td tal:condition="request/show/category"
2574         tal:content="i/category"></td>
2576 The condition is the same as above: only display the condition when the
2577 user hasn't asked for it to be hidden. The next part is to set the
2578 content of the cell to be the category part of "i" - the current issue.
2580 Finally we have to edit ``html/page.html`` again. This time, we need to
2581 tell it that when the user clicks on "Unasigned Issues" or "All Issues",
2582 the category column should be included in the resulting list. If you
2583 scroll down the page file, you can see the links with lots of options.
2584 The option that we are interested in is the ``:columns=`` one which
2585 tells roundup which fields of the issue to display. Simply add
2586 "category" to that list and it all should work.
2589 Adding in state transition control
2590 ----------------------------------
2592 Sometimes tracker admins want to control the states that users may move
2593 issues to. You can do this by following these steps:
2595 1. make "status" a required variable. This is achieved by adding the
2596    following to the top of the form in the ``issue.item.html``
2597    template::
2599      <input type="hidden" name="@required" value="status">
2601    this will force users to select a status.
2603 2. add a Multilink property to the status class::
2605      stat = Class(db, "status", ... , transitions=Multilink('status'),
2606                   ...)
2608    and then edit the statuses already created, either:
2610    a. through the web using the class list -> status class editor, or
2611    b. using the roundup-admin "set" command.
2613 3. add an auditor module ``checktransition.py`` in your tracker's
2614    ``detectors`` directory, for example::
2616      def checktransition(db, cl, nodeid, newvalues):
2617          ''' Check that the desired transition is valid for the "status"
2618              property.
2619          '''
2620          if not newvalues.has_key('status'):
2621              return
2622          current = cl.get(nodeid, 'status')
2623          new = newvalues['status']
2624          if new == current:
2625              return
2626          ok = db.status.get(current, 'transitions')
2627          if new not in ok:
2628              raise ValueError, 'Status not allowed to move from "%s" to "%s"'%(
2629                  db.status.get(current, 'name'), db.status.get(new, 'name'))
2631      def init(db):
2632          db.issue.audit('set', checktransition)
2634 4. in the ``issue.item.html`` template, change the status editing bit
2635    from::
2637     <th>Status</th>
2638     <td tal:content="structure context/status/menu">status</td>
2640    to::
2642     <th>Status</th>
2643     <td>
2644      <select tal:condition="context/id" name="status">
2645       <tal:block tal:define="ok context/status/transitions"
2646                  tal:repeat="state db/status/list">
2647        <option tal:condition="python:state.id in ok"
2648                tal:attributes="
2649                     value state/id;
2650                     selected python:state.id == context.status.id"
2651                tal:content="state/name"></option>
2652       </tal:block>
2653      </select>
2654      <tal:block tal:condition="not:context/id"
2655                 tal:replace="structure context/status/menu" />
2656     </td>
2658    which displays only the allowed status to transition to.
2661 Displaying only message summaries in the issue display
2662 ------------------------------------------------------
2664 Alter the issue.item template section for messages to::
2666  <table class="messages" tal:condition="context/messages">
2667   <tr><th colspan="5" class="header">Messages</th></tr>
2668   <tr tal:repeat="msg context/messages">
2669    <td><a tal:attributes="href string:msg${msg/id}"
2670           tal:content="string:msg${msg/id}"></a></td>
2671    <td tal:content="msg/author">author</td>
2672    <td class="date" tal:content="msg/date/pretty">date</td>
2673    <td tal:content="msg/summary">summary</td>
2674    <td>
2675     <a tal:attributes="href string:?@remove@messages=${msg/id}&@action=edit">
2676     remove</a>
2677    </td>
2678   </tr>
2679  </table>
2681 Restricting the list of users that are assignable to a task
2682 -----------------------------------------------------------
2684 1. In your tracker's "dbinit.py", create a new Role, say "Developer"::
2686      db.security.addRole(name='Developer', description='A developer')
2688 2. Just after that, create a new Permission, say "Fixer", specific to
2689    "issue"::
2691      p = db.security.addPermission(name='Fixer', klass='issue',
2692          description='User is allowed to be assigned to fix issues')
2694 3. Then assign the new Permission to your "Developer" Role::
2696      db.security.addPermissionToRole('Developer', p)
2698 4. In the issue item edit page ("html/issue.item.html" in your tracker
2699    directory), use the new Permission in restricting the "assignedto"
2700    list::
2702     <select name="assignedto">
2703      <option value="-1">- no selection -</option>
2704      <tal:block tal:repeat="user db/user/list">
2705      <option tal:condition="python:user.hasPermission(
2706                                 'Fixer', context._classname)"
2707              tal:attributes="
2708                 value user/id;
2709                 selected python:user.id == context.assignedto"
2710              tal:content="user/realname"></option>
2711      </tal:block>
2712     </select>
2714 For extra security, you may wish to setup an auditor to enforce the
2715 Permission requirement (install this as "assignedtoFixer.py" in your
2716 tracker "detectors" directory)::
2718   def assignedtoMustBeFixer(db, cl, nodeid, newvalues):
2719       ''' Ensure the assignedto value in newvalues is a used with the
2720           Fixer Permission
2721       '''
2722       if not newvalues.has_key('assignedto'):
2723           # don't care
2724           return
2725   
2726       # get the userid
2727       userid = newvalues['assignedto']
2728       if not db.security.hasPermission('Fixer', userid, cl.classname):
2729           raise ValueError, 'You do not have permission to edit %s'%cl.classname
2731   def init(db):
2732       db.issue.audit('set', assignedtoMustBeFixer)
2733       db.issue.audit('create', assignedtoMustBeFixer)
2735 So now, if an edit action attempts to set "assignedto" to a user that
2736 doesn't have the "Fixer" Permission, the error will be raised.
2739 Setting up a "wizard" (or "druid") for controlled adding of issues
2740 ------------------------------------------------------------------
2742 1. Set up the page templates you wish to use for data input. My wizard
2743    is going to be a two-step process: first figuring out what category
2744    of issue the user is submitting, and then getting details specific to
2745    that category. The first page includes a table of help, explaining
2746    what the category names mean, and then the core of the form::
2748     <form method="POST" onSubmit="return submit_once()"
2749           enctype="multipart/form-data">
2750       <input type="hidden" name="@template" value="add_page1">
2751       <input type="hidden" name="@action" value="page1_submit">
2753       <strong>Category:</strong>
2754       <tal:block tal:replace="structure context/category/menu" />
2755       <input type="submit" value="Continue">
2756     </form>
2758    The next page has the usual issue entry information, with the
2759    addition of the following form fragments::
2761     <form method="POST" onSubmit="return submit_once()"
2762           enctype="multipart/form-data"
2763           tal:condition="context/is_edit_ok"
2764           tal:define="cat request/form/category/value">
2766       <input type="hidden" name="@template" value="add_page2">
2767       <input type="hidden" name="@required" value="title">
2768       <input type="hidden" name="category" tal:attributes="value cat">
2769        .
2770        .
2771        .
2772     </form>
2774    Note that later in the form, I test the value of "cat" include form
2775    elements that are appropriate. For exsample::
2777     <tal:block tal:condition="python:cat in '6 10 13 14 15 16 17'.split()">
2778      <tr>
2779       <th>Operating System</th>
2780       <td tal:content="structure context/os/field"></td>
2781      </tr>
2782      <tr>
2783       <th>Web Browser</th>
2784       <td tal:content="structure context/browser/field"></td>
2785      </tr>
2786     </tal:block>
2788    ... the above section will only be displayed if the category is one
2789    of 6, 10, 13, 14, 15, 16 or 17.
2791 3. Determine what actions need to be taken between the pages - these are
2792    usually to validate user choices and determine what page is next. Now encode
2793    those actions in a new ``Action`` class and insert hooks to those actions in
2794    the "actions" attribute on on the ``interfaces.Client`` class, like so (see 
2795    `defining new web actions`_)::
2797     class Page1SubmitAction(Action):
2798         def handle(self):
2799             ''' Verify that the user has selected a category, and then move
2800                 on to page 2.
2801             '''
2802             category = self.form['category'].value
2803             if category == '-1':
2804                 self.error_message.append('You must select a category of report')
2805                 return
2806             # everything's ok, move on to the next page
2807             self.template = 'add_page2'
2809     actions = client.Client.actions + (
2810         ('page1_submit', Page1SubmitAction),
2811     )
2813 4. Use the usual "new" action as the ``@action`` on the final page, and
2814    you're done (the standard context/submit method can do this for you).
2817 Using an external password validation source
2818 --------------------------------------------
2820 We have a centrally-managed password changing system for our users. This
2821 results in a UN*X passwd-style file that we use for verification of
2822 users. Entries in the file consist of ``name:password`` where the
2823 password is encrypted using the standard UN*X ``crypt()`` function (see
2824 the ``crypt`` module in your Python distribution). An example entry
2825 would be::
2827     admin:aamrgyQfDFSHw
2829 Each user of Roundup must still have their information stored in the
2830 Roundup database - we just use the passwd file to check their password.
2831 To do this, we add the following code to our ``Client`` class in the
2832 tracker home ``interfaces.py`` module::
2834     def verifyPassword(self, userid, password):
2835         # get the user's username
2836         username = self.db.user.get(userid, 'username')
2838         # the passwords are stored in the "passwd.txt" file in the
2839         # tracker home
2840         file = os.path.join(self.db.config.TRACKER_HOME, 'passwd.txt')
2842         # see if we can find a match
2843         for ent in [line.strip().split(':') for line in
2844                                             open(file).readlines()]:
2845             if ent[0] == username:
2846                 return crypt.crypt(password, ent[1][:2]) == ent[1]
2848         # user doesn't exist in the file
2849         return 0
2851 What this does is look through the file, line by line, looking for a
2852 name that matches.
2854 We also remove the redundant password fields from the ``user.item``
2855 template.
2858 Adding a "vacation" flag to users for stopping nosy messages
2859 ------------------------------------------------------------
2861 When users go on vacation and set up vacation email bouncing, you'll
2862 start to see a lot of messages come back through Roundup "Fred is on
2863 vacation". Not very useful, and relatively easy to stop.
2865 1. add a "vacation" flag to your users::
2867          user = Class(db, "user",
2868                     username=String(),   password=Password(),
2869                     address=String(),    realname=String(),
2870                     phone=String(),      organisation=String(),
2871                     alternate_addresses=String(),
2872                     roles=String(), queries=Multilink("query"),
2873                     vacation=Boolean())
2875 2. So that users may edit the vacation flags, add something like the
2876    following to your ``user.item`` template::
2878      <tr>
2879       <th>On Vacation</th> 
2880       <td tal:content="structure context/vacation/field">vacation</td> 
2881      </tr> 
2883 3. edit your detector ``nosyreactor.py`` so that the ``nosyreaction()``
2884    consists of::
2886     def nosyreaction(db, cl, nodeid, oldvalues):
2887         # send a copy of all new messages to the nosy list
2888         for msgid in determineNewMessages(cl, nodeid, oldvalues):
2889             try:
2890                 users = db.user
2891                 messages = db.msg
2893                 # figure the recipient ids
2894                 sendto = []
2895                 r = {}
2896                 recipients = messages.get(msgid, 'recipients')
2897                 for recipid in messages.get(msgid, 'recipients'):
2898                     r[recipid] = 1
2900                 # figure the author's id, and indicate they've received
2901                 # the message
2902                 authid = messages.get(msgid, 'author')
2904                 # possibly send the message to the author, as long as
2905                 # they aren't anonymous
2906                 if (db.config.MESSAGES_TO_AUTHOR == 'yes' and
2907                         users.get(authid, 'username') != 'anonymous'):
2908                     sendto.append(authid)
2909                 r[authid] = 1
2911                 # now figure the nosy people who weren't recipients
2912                 nosy = cl.get(nodeid, 'nosy')
2913                 for nosyid in nosy:
2914                     # Don't send nosy mail to the anonymous user (that
2915                     # user shouldn't appear in the nosy list, but just
2916                     # in case they do...)
2917                     if users.get(nosyid, 'username') == 'anonymous':
2918                         continue
2919                     # make sure they haven't seen the message already
2920                     if not r.has_key(nosyid):
2921                         # send it to them
2922                         sendto.append(nosyid)
2923                         recipients.append(nosyid)
2925                 # generate a change note
2926                 if oldvalues:
2927                     note = cl.generateChangeNote(nodeid, oldvalues)
2928                 else:
2929                     note = cl.generateCreateNote(nodeid)
2931                 # we have new recipients
2932                 if sendto:
2933                     # filter out the people on vacation
2934                     sendto = [i for i in sendto 
2935                               if not users.get(i, 'vacation', 0)]
2937                     # map userids to addresses
2938                     sendto = [users.get(i, 'address') for i in sendto]
2940                     # update the message's recipients list
2941                     messages.set(msgid, recipients=recipients)
2943                     # send the message
2944                     cl.send_message(nodeid, msgid, note, sendto)
2945             except roundupdb.MessageSendError, message:
2946                 raise roundupdb.DetectorError, message
2948    Note that this is the standard nosy reaction code, with the small
2949    addition of::
2951     # filter out the people on vacation
2952     sendto = [i for i in sendto if not users.get(i, 'vacation', 0)]
2954    which filters out the users that have the vacation flag set to true.
2957 Adding a time log to your issues
2958 --------------------------------
2960 We want to log the dates and amount of time spent working on issues, and
2961 be able to give a summary of the total time spent on a particular issue.
2963 1. Add a new class to your tracker ``dbinit.py``::
2965     # storage for time logging
2966     timelog = Class(db, "timelog", period=Interval())
2968    Note that we automatically get the date of the time log entry
2969    creation through the standard property "creation".
2971 2. Link to the new class from your issue class (again, in
2972    ``dbinit.py``)::
2974     issue = IssueClass(db, "issue", 
2975                     assignedto=Link("user"), topic=Multilink("keyword"),
2976                     priority=Link("priority"), status=Link("status"),
2977                     times=Multilink("timelog"))
2979    the "times" property is the new link to the "timelog" class.
2981 3. We'll need to let people add in times to the issue, so in the web
2982    interface we'll have a new entry field. This is a special field
2983    because unlike the other fields in the issue.item template, it
2984    affects a different item (a timelog item) and not the template's
2985    item, an issue. We have a special syntax for form fields that affect
2986    items other than the template default item (see the cgi 
2987    documentation on `special form variables`_). In particular, we add a
2988    field to capture a new timelog item's perdiod::
2990     <tr> 
2991      <th>Time Log</th> 
2992      <td colspan=3><input type="text" name="timelog-1@period" /> 
2993       <br />(enter as '3y 1m 4d 2:40:02' or parts thereof) 
2994      </td> 
2995     </tr> 
2996          
2997    and another hidden field that links that new timelog item (new
2998    because it's marked as having id "-1") to the issue item. It looks
2999    like this::
3001      <input type="hidden" name="@link@times" value="timelog-1" />
3003    On submission, the "-1" timelog item will be created and assigned a
3004    real item id. The "times" property of the issue will have the new id
3005    added to it.
3007 4. We want to display a total of the time log times that have been
3008    accumulated for an issue. To do this, we'll need to actually write
3009    some Python code, since it's beyond the scope of PageTemplates to
3010    perform such calculations. We do this by adding a method to the
3011    TemplatingUtils class in our tracker ``interfaces.py`` module::
3013     class TemplatingUtils:
3014         ''' Methods implemented on this class will be available to HTML
3015             templates through the 'utils' variable.
3016         '''
3017         def totalTimeSpent(self, times):
3018             ''' Call me with a list of timelog items (which have an
3019                 Interval "period" property)
3020             '''
3021             total = Interval('0d')
3022             for time in times:
3023                 total += time.period._value
3024             return total
3026    Replace the ``pass`` line if one appears in your TemplatingUtils
3027    class. As indicated in the docstrings, we will be able to access the
3028    ``totalTimeSpent`` method via the ``utils`` variable in our templates.
3030 5. Display the time log for an issue::
3032      <table class="otherinfo" tal:condition="context/times">
3033       <tr><th colspan="3" class="header">Time Log
3034        <tal:block
3035             tal:replace="python:utils.totalTimeSpent(context.times)" />
3036       </th></tr>
3037       <tr><th>Date</th><th>Period</th><th>Logged By</th></tr>
3038       <tr tal:repeat="time context/times">
3039        <td tal:content="time/creation"></td>
3040        <td tal:content="time/period"></td>
3041        <td tal:content="time/creator"></td>
3042       </tr>
3043      </table>
3045    I put this just above the Messages log in my issue display. Note our
3046    use of the ``totalTimeSpent`` method which will total up the times
3047    for the issue and return a new Interval. That will be automatically
3048    displayed in the template as text like "+ 1y 2:40" (1 year, 2 hours
3049    and 40 minutes).
3051 8. If you're using a persistent web server - roundup-server or
3052    mod_python for example - then you'll need to restart that to pick up
3053    the code changes. When that's done, you'll be able to use the new
3054    time logging interface.
3056 Using a UN*X passwd file as the user database
3057 ---------------------------------------------
3059 On some systems the primary store of users is the UN*X passwd file. It
3060 holds information on users such as their username, real name, password
3061 and primary user group.
3063 Roundup can use this store as its primary source of user information,
3064 but it needs additional information too - email address(es), roundup
3065 Roles, vacation flags, roundup hyperdb item ids, etc. Also, "retired"
3066 users must still exist in the user database, unlike some passwd files in
3067 which the users are removed when they no longer have access to a system.
3069 To make use of the passwd file, we therefore synchronise between the two
3070 user stores. We also use the passwd file to validate the user logins, as
3071 described in the previous example, `using an external password
3072 validation source`_. We keep the users lists in sync using a fairly
3073 simple script that runs once a day, or several times an hour if more
3074 immediate access is needed. In short, it:
3076 1. parses the passwd file, finding usernames, passwords and real names,
3077 2. compares that list to the current roundup user list:
3079    a. entries no longer in the passwd file are *retired*
3080    b. entries with mismatching real names are *updated*
3081    c. entries only exist in the passwd file are *created*
3083 3. send an email to administrators to let them know what's been done.
3085 The retiring and updating are simple operations, requiring only a call
3086 to ``retire()`` or ``set()``. The creation operation requires more
3087 information though - the user's email address and their roundup Roles.
3088 We're going to assume that the user's email address is the same as their
3089 login name, so we just append the domain name to that. The Roles are
3090 determined using the passwd group identifier - mapping their UN*X group
3091 to an appropriate set of Roles.
3093 The script to perform all this, broken up into its main components, is
3094 as follows. Firstly, we import the necessary modules and open the
3095 tracker we're to work on::
3097     import sys, os, smtplib
3098     from roundup import instance, date
3100     # open the tracker
3101     tracker_home = sys.argv[1]
3102     tracker = instance.open(tracker_home)
3104 Next we read in the *passwd* file from the tracker home::
3106     # read in the users
3107     file = os.path.join(tracker_home, 'users.passwd')
3108     users = [x.strip().split(':') for x in open(file).readlines()]
3110 Handle special users (those to ignore in the file, and those who don't
3111 appear in the file)::
3113     # users to not keep ever, pre-load with the users I know aren't
3114     # "real" users
3115     ignore = ['ekmmon', 'bfast', 'csrmail']
3117     # users to keep - pre-load with the roundup-specific users
3118     keep = ['comment_pool', 'network_pool', 'admin', 'dev-team',
3119             'cs_pool', 'anonymous', 'system_pool', 'automated']
3121 Now we map the UN*X group numbers to the Roles that users should have::
3123     roles = {
3124      '501': 'User,Tech',  # tech
3125      '502': 'User',       # finance
3126      '503': 'User,CSR',   # customer service reps
3127      '504': 'User',       # sales
3128      '505': 'User',       # marketing
3129     }
3131 Now we do all the work. Note that the body of the script (where we have
3132 the tracker database open) is wrapped in a ``try`` / ``finally`` clause,
3133 so that we always close the database cleanly when we're finished. So, we
3134 now do all the work::
3136     # open the database
3137     db = tracker.open('admin')
3138     try:
3139         # store away messages to send to the tracker admins
3140         msg = []
3142         # loop over the users list read in from the passwd file
3143         for user,passw,uid,gid,real,home,shell in users:
3144             if user in ignore:
3145                 # this user shouldn't appear in our tracker
3146                 continue
3147             keep.append(user)
3148             try:
3149                 # see if the user exists in the tracker
3150                 uid = db.user.lookup(user)
3152                 # yes, they do - now check the real name for correctness
3153                 if real != db.user.get(uid, 'realname'):
3154                     db.user.set(uid, realname=real)
3155                     msg.append('FIX %s - %s'%(user, real))
3156             except KeyError:
3157                 # nope, the user doesn't exist
3158                 db.user.create(username=user, realname=real,
3159                     address='%s@ekit-inc.com'%user, roles=roles[gid])
3160                 msg.append('ADD %s - %s (%s)'%(user, real, roles[gid]))
3162         # now check that all the users in the tracker are also in our
3163         # "keep" list - retire those who aren't
3164         for uid in db.user.list():
3165             user = db.user.get(uid, 'username')
3166             if user not in keep:
3167                 db.user.retire(uid)
3168                 msg.append('RET %s'%user)
3170         # if we did work, then send email to the tracker admins
3171         if msg:
3172             # create the email
3173             msg = '''Subject: %s user database maintenance
3175             %s
3176             '''%(db.config.TRACKER_NAME, '\n'.join(msg))
3178             # send the email
3179             smtp = smtplib.SMTP(db.config.MAILHOST)
3180             addr = db.config.ADMIN_EMAIL
3181             smtp.sendmail(addr, addr, msg)
3183         # now we're done - commit the changes
3184         db.commit()
3185     finally:
3186         # always close the database cleanly
3187         db.close()
3189 And that's it!
3192 Using an LDAP database for user information
3193 -------------------------------------------
3195 A script that reads users from an LDAP store using
3196 http://python-ldap.sf.net/ and then compares the list to the users in the
3197 roundup user database would be pretty easy to write. You'd then have it run
3198 once an hour / day (or on demand if you can work that into your LDAP store
3199 workflow). See the example `Using a UN*X passwd file as the user database`_
3200 for more information about doing this.
3202 To authenticate off the LDAP store (rather than using the passwords in the
3203 roundup user database) you'd use the same python-ldap module inside an
3204 extension to the cgi interface. You'd do this by adding a method called
3205 "verifyPassword" to the Client class in your tracker's interfaces.py
3206 module. The method is implemented by default as::
3208     def verifyPassword(self, userid, password):
3209         ''' Verify the password that the user has supplied
3210         '''
3211         stored = self.db.user.get(self.userid, 'password')
3212         if password == stored:
3213             return 1
3214         if not password and not stored:
3215             return 1
3216         return 0
3218 So you could reimplement this as something like::
3220     def verifyPassword(self, userid, password):
3221         ''' Verify the password that the user has supplied
3222         '''
3223         # look up some unique LDAP information about the user
3224         username = self.db.user.get(self.userid, 'username')
3225         # now verify the password supplied against the LDAP store
3228 Enabling display of either message summaries or the entire messages
3229 -------------------------------------------------------------------
3231 This is pretty simple - all we need to do is copy the code from the
3232 example `displaying only message summaries in the issue display`_ into
3233 our template alongside the summary display, and then introduce a switch
3234 that shows either one or the other. We'll use a new form variable,
3235 ``@whole_messages`` to achieve this::
3237  <table class="messages" tal:condition="context/messages">
3238   <tal:block tal:condition="not:request/form/@whole_messages/value | python:0">
3239    <tr><th colspan="3" class="header">Messages</th>
3240        <th colspan="2" class="header">
3241          <a href="?@whole_messages=yes">show entire messages</a>
3242        </th>
3243    </tr>
3244    <tr tal:repeat="msg context/messages">
3245     <td><a tal:attributes="href string:msg${msg/id}"
3246            tal:content="string:msg${msg/id}"></a></td>
3247     <td tal:content="msg/author">author</td>
3248     <td class="date" tal:content="msg/date/pretty">date</td>
3249     <td tal:content="msg/summary">summary</td>
3250     <td>
3251      <a tal:attributes="href string:?@remove@messages=${msg/id}&@action=edit">remove</a>
3252     </td>
3253    </tr>
3254   </tal:block>
3256   <tal:block tal:condition="request/form/@whole_messages/value | python:0">
3257    <tr><th colspan="2" class="header">Messages</th>
3258        <th class="header">
3259          <a href="?@whole_messages=">show only summaries</a>
3260        </th>
3261    </tr>
3262    <tal:block tal:repeat="msg context/messages">
3263     <tr>
3264      <th tal:content="msg/author">author</th>
3265      <th class="date" tal:content="msg/date/pretty">date</th>
3266      <th style="text-align: right">
3267       (<a tal:attributes="href string:?@remove@messages=${msg/id}&@action=edit">remove</a>)
3268      </th>
3269     </tr>
3270     <tr><td colspan="3" tal:content="msg/content"></td></tr>
3271    </tal:block>
3272   </tal:block>
3273  </table>
3276 Blocking issues that depend on other issues
3277 -------------------------------------------
3279 We needed the ability to mark certain issues as "blockers" - that is,
3280 they can't be resolved until another issue (the blocker) they rely on is
3281 resolved. To achieve this:
3283 1. Create a new property on the issue Class,
3284    ``blockers=Multilink("issue")``. Edit your tracker's dbinit.py file.
3285    Where the "issue" class is defined, something like::
3287     issue = IssueClass(db, "issue", 
3288                     assignedto=Link("user"), topic=Multilink("keyword"),
3289                     priority=Link("priority"), status=Link("status"))
3291    add the blockers entry like so::
3293     issue = IssueClass(db, "issue", 
3294                     blockers=Multilink("issue"),
3295                     assignedto=Link("user"), topic=Multilink("keyword"),
3296                     priority=Link("priority"), status=Link("status"))
3298 2. Add the new "blockers" property to the issue.item edit page, using
3299    something like::
3301     <th>Waiting On</th>
3302     <td>
3303      <span tal:replace="structure python:context.blockers.field(showid=1,
3304                                   size=20)" />
3305      <span tal:replace="structure python:db.issue.classhelp('id,title')" />
3306      <span tal:condition="context/blockers"
3307            tal:repeat="blk context/blockers">
3308       <br>View: <a tal:attributes="href string:issue${blk/id}"
3309                    tal:content="blk/id"></a>
3310      </span>
3312    You'll need to fiddle with your item page layout to find an
3313    appropriate place to put it - I'll leave that fun part up to you.
3314    Just make sure it appears in the first table, possibly somewhere near
3315    the "superseders" field.
3317 3. Create a new detector module (attached) which enforces the rules:
3319    - issues may not be resolved if they have blockers
3320    - when a blocker is resolved, it's removed from issues it blocks
3322    The contents of the detector should be something like this::
3324     def blockresolution(db, cl, nodeid, newvalues):
3325         ''' If the issue has blockers, don't allow it to be resolved.
3326         '''
3327         if nodeid is None:
3328             blockers = []
3329         else:
3330             blockers = cl.get(nodeid, 'blockers')
3331         blockers = newvalues.get('blockers', blockers)
3333         # don't do anything if there's no blockers or the status hasn't
3334         # changed
3335         if not blockers or not newvalues.has_key('status'):
3336             return
3338         # get the resolved state ID
3339         resolved_id = db.status.lookup('resolved')
3341         # format the info
3342         u = db.config.TRACKER_WEB
3343         s = ', '.join(['<a href="%sissue%s">%s</a>'%(
3344                         u,id,id) for id in blockers])
3345         if len(blockers) == 1:
3346             s = 'issue %s is'%s
3347         else:
3348             s = 'issues %s are'%s
3350         # ok, see if we're trying to resolve
3351         if newvalues['status'] == resolved_id:
3352             raise ValueError, "This issue can't be resolved until %s resolved."%s
3354     def resolveblockers(db, cl, nodeid, newvalues):
3355         ''' When we resolve an issue that's a blocker, remove it from the
3356             blockers list of the issue(s) it blocks.
3357         '''
3358         if not newvalues.has_key('status'):
3359             return
3361         # get the resolved state ID
3362         resolved_id = db.status.lookup('resolved')
3364         # interesting?
3365         if newvalues['status'] != resolved_id:
3366             return
3368         # yes - find all the blocked issues, if any, and remove me from
3369         # their blockers list
3370         issues = cl.find(blockers=nodeid)
3371         for issueid in issues:
3372             blockers = cl.get(issueid, 'blockers')
3373             if nodeid in blockers:
3374                 blockers.remove(nodeid)
3375                 cl.set(issueid, blockers=blockers)
3378     def init(db):
3379         # might, in an obscure situation, happen in a create
3380         db.issue.audit('create', blockresolution)
3381         db.issue.audit('set', blockresolution)
3383         # can only happen on a set
3384         db.issue.react('set', resolveblockers)
3386    Put the above code in a file called "blockers.py" in your tracker's
3387    "detectors" directory.
3389 4. Finally, and this is an optional step, modify the tracker web page
3390    URLs so they filter out issues with any blockers. You do this by
3391    adding an additional filter on "blockers" for the value "-1". For
3392    example, the existing "Show All" link in the "page" template (in the
3393    tracker's "html" directory) looks like this::
3395      <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>
3397    modify it to add the "blockers" info to the URL (note, both the
3398    ":filter" *and* "blockers" values must be specified)::
3400      <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>
3402 That's it. You should now be able to set blockers on your issues. Note
3403 that if you want to know whether an issue has any other issues dependent
3404 on it (i.e. it's in their blockers list) you can look at the journal
3405 history at the bottom of the issue page - look for a "link" event to
3406 another issue's "blockers" property.
3408 Add users to the nosy list based on the topic
3409 ---------------------------------------------
3411 We need the ability to automatically add users to the nosy list based
3412 on the occurence of a topic. Every user should be allowed to edit his
3413 own list of topics for which he wants to be added to the nosy list.
3415 Below will be showed that such a change can be performed with only
3416 minimal understanding of the roundup system, but with clever use
3417 of Copy and Paste.
3419 This requires three changes to the tracker: a change in the database to
3420 allow per-user recording of the lists of topics for which he wants to
3421 be put on the nosy list, a change in the user view allowing to edit
3422 this list of topics, and addition of an auditor which updates the nosy
3423 list when a topic is set.
3425 Adding the nosy topic list
3426 ~~~~~~~~~~~~~~~~~~~~~~~~~~
3428 The change in the database to make is that for any user there should be
3429 a list of topics for which he wants to be put on the nosy list. Adding
3430 a ``Multilink`` of ``keyword`` seem to fullfill this (note that within
3431 the code topics are called ``keywords``.) As such, all what has to be
3432 done is to add a new field to the definition of ``user`` within the
3433 file ``dbinit.py``.  We will call this new field ``nosy_keywords``, and
3434 the updated definition of user will be::
3436     user = Class(db, "user", 
3437                     username=String(),   password=Password(),
3438                     address=String(),    realname=String(), 
3439                     phone=String(),      organisation=String(),
3440                     alternate_addresses=String(),
3441                     queries=Multilink('query'), roles=String(),
3442                     timezone=String(),
3443                     nosy_keywords=Multilink('keyword'))
3444  
3445 Changing the user view to allow changing the nosy topic list
3446 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
3448 We want any user to be able to change the list of topics for which
3449 he will by default be added to the nosy list. We choose to add this
3450 to the user view, as is generated by the file ``html/user.item.html``.
3451 We easily can
3452 see that the topic field in the issue view has very similar editting
3453 requirements as our nosy topics, both being a list of topics. As
3454 such, we search for Topics in ``issue.item.html``, and extract the
3455 associated parts from there. We add this to ``user.item.html`` at the 
3456 bottom of the list of viewed items (i.e. just below the 'Alternate
3457 E-mail addresses' in the classic template)::
3459  <tr>
3460   <th>Nosy Topics</th>
3461   <td>
3462   <span tal:replace="structure context/nosy_keywords/field" />
3463   <span tal:replace="structure python:db.keyword.classhelp(property='nosy_keywords')" />
3464   </td>
3465  </tr>
3466   
3468 Addition of an auditor to update the nosy list
3469 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
3471 The more difficult part is the addition of the logic to actually
3472 at the users to the nosy list when it is required. 
3473 The choice is made to perform this action when the topics on an
3474 item are set, including when an item is created.
3475 Here we choose to start out with a copy of the 
3476 ``detectors/nosyreaction.py`` detector, which we copy to the file
3477 ``detectors/nosy_keyword_reaction.py``. 
3478 This looks like a good start as it also adds users
3479 to the nosy list. A look through the code reveals that the
3480 ``nosyreaction`` function actually is sending the e-mail, which
3481 we do not need. As such, we can change the init function to::
3483     def init(db):
3484         db.issue.audit('create', update_kw_nosy)
3485         db.issue.audit('set', update_kw_nosy)
3487 After that we rename the ``updatenosy`` function to ``update_kw_nosy``.
3488 The first two blocks of code in that function relate to settings
3489 ``current`` to a combination of the old and new nosy lists. This
3490 functionality is left in the new auditor. The following block of
3491 code, which in ``updatenosy`` handled adding the assignedto user(s)
3492 to the nosy list, should be replaced by a block of code to add the
3493 interested users to the nosy list. We choose here to loop over all
3494 new topics, than loop over all users,
3495 and assign the user to the nosy list when the topic in the user's
3496 nosy_keywords. The next part in ``updatenosy``, adding the author
3497 and/or recipients of a message to the nosy list, obviously is not
3498 relevant here and thus is deleted from the new auditor. The last
3499 part, copying the new nosy list to newvalues, does not have to be changed.
3500 This brings the following function::
3502     def update_kw_nosy(db, cl, nodeid, newvalues):
3503         '''Update the nosy list for changes to the topics
3504         '''
3505         # nodeid will be None if this is a new node
3506         current = {}
3507         if nodeid is None:
3508             ok = ('new', 'yes')
3509         else:
3510             ok = ('yes',)
3511             # old node, get the current values from the node if they haven't
3512             # changed
3513             if not newvalues.has_key('nosy'):
3514                 nosy = cl.get(nodeid, 'nosy')
3515                 for value in nosy:
3516                     if not current.has_key(value):
3517                         current[value] = 1
3519         # if the nosy list changed in this transaction, init from the new value
3520         if newvalues.has_key('nosy'):
3521             nosy = newvalues.get('nosy', [])
3522             for value in nosy:
3523                 if not db.hasnode('user', value):
3524                     continue
3525                 if not current.has_key(value):
3526                     current[value] = 1
3528         # add users with topic in nosy_keywords to the nosy list
3529         if newvalues.has_key('topic') and newvalues['topic'] is not None:
3530             topic_ids = newvalues['topic']
3531             for topic in topic_ids:
3532                 # loop over all users,
3533                 # and assign user to nosy when topic in nosy_keywords
3534                 for user_id in db.user.list():
3535                     nosy_kw = db.user.get(user_id, "nosy_keywords")
3536                     found = 0
3537                     for kw in nosy_kw:
3538                         if kw == topic:
3539                             found = 1
3540                     if found:
3541                         current[user_id] = 1
3543         # that's it, save off the new nosy list
3544         newvalues['nosy'] = current.keys()
3546 and these two function are the only ones needed in the file.
3548 TODO: update this example to use the find() Class method.
3550 Caveats
3551 ~~~~~~~
3553 A few problems with the design here can be noted:
3555 Multiple additions
3556     When a user, after automatic selection, is manually removed
3557     from the nosy list, he again is added to the nosy list when the
3558     topic list of the issue is updated. A better design might be
3559     to only check which topics are new compared to the old list
3560     of topics, and only add users when they have indicated
3561     interest on a new topic.
3563     The code could also be changed to only trigger on the create() event,
3564     rather than also on the set() event, thus only setting the nosy list
3565     when the issue is created.
3567 Scalability
3568     In the auditor there is a loop over all users. For a site with
3569     only few users this will pose no serious problem, however, with
3570     many users this will be a serious performance bottleneck.
3571     A way out will be to link from the topics to the users which
3572     selected these topics a nosy topics. This will eliminate the
3573     loop over all users.
3576 Adding action links to the index page
3577 -------------------------------------
3579 Add a column to the item.index.html template.
3581 Resolving the issue::
3583   <a tal:attributes="href
3584      string:issue${i/id}?:status=resolved&:action=edit">resolve</a>
3586 "Take" the issue::
3588   <a tal:attributes="href
3589      string:issue${i/id}?:assignedto=${request/user/id}&:action=edit">take</a>
3591 ... and so on
3593 Users may only edit their issues
3594 --------------------------------
3596 Users registering themselves are granted Provisional access - meaning they
3597 have access to edit the issues they submit, but not others. We create a new
3598 Role called "Provisional User" which is granted to newly-registered users,
3599 and has limited access. One of the Permissions they have is the new "Edit
3600 Own" on issues (regular users have "Edit".) We back up the permissions with
3601 an auditor.
3603 First up, we create the new Role and Permission structure in
3604 ``dbinit.py``::
3606     # New users not approved by the admin
3607     db.security.addRole(name='Provisional User',
3608         description='New user registered via web or email')
3609     p = db.security.addPermission(name='Edit Own', klass='issue',
3610         description='Can only edit own issues')
3611     db.security.addPermissionToRole('Provisional User', p)
3613     # Assign the access and edit Permissions for issue to new users now
3614     p = db.security.getPermission('View', 'issue')
3615     db.security.addPermissionToRole('Provisional User', p)
3616     p = db.security.getPermission('Edit', 'issue')
3617     db.security.addPermissionToRole('Provisional User', p)
3619     # and give the new users access to the web and email interface
3620     p = db.security.getPermission('Web Access')
3621     db.security.addPermissionToRole('Provisional User', p)
3622     p = db.security.getPermission('Email Access')
3623     db.security.addPermissionToRole('Provisional User', p)
3626 Then in the ``config.py`` we change the Role assigned to newly-registered
3627 users, replacing the existing ``'User'`` values::
3629     NEW_WEB_USER_ROLES = 'Provisional User'
3630     NEW_EMAIL_USER_ROLES = 'Provisional User'
3632 Finally we add a new *auditor* to the ``detectors`` directory called
3633 ``provisional_user_auditor.py``::
3635  def audit_provisionaluser(db, cl, nodeid, newvalues):
3636      ''' New users are only allowed to modify their own issues.
3637      '''
3638      if (db.getuid() != cl.get(nodeid, 'creator')
3639          and db.security.hasPermission('Edit Own', db.getuid(), cl.classname)):
3640          raise ValueError, ('You are only allowed to edit your own %s'
3641                             % cl.classname)
3643  def init(db):
3644      # fire before changes are made
3645      db.issue.audit('set', audit_provisionaluser)
3646      db.issue.audit('retire', audit_provisionaluser)
3647      db.issue.audit('restore', audit_provisionaluser)
3649 Note that some older trackers might also want to change the ``page.html``
3650 template as follows::
3652  <p class="classblock"
3653  -       tal:condition="python:request.user.username != 'anonymous'">
3654  +       tal:condition="python:request.user.hasPermission('View', 'user')">
3655      <b>Administration</b><br>
3656      <tal:block tal:condition="python:request.user.hasPermission('Edit', None)">
3657       <a href="home?:template=classlist">Class List</a><br>
3659 (note that the "-" indicates a removed line, and the "+" indicates an added
3660 line).
3663 Colouring the rows in the issue index according to priority
3664 -----------------------------------------------------------
3666 A simple ``tal:attributes`` statement will do the bulk of the work here. In
3667 the ``issue.index.html`` template, add to the ``<tr>`` that displays the
3668 actual rows of data::
3670    <tr tal:attributes="class string:priority-${i/priority/plain}">
3672 and then in your stylesheet (``style.css``) specify the colouring for the
3673 different priorities, like::
3675    tr.priority-critical td {
3676        background-color: red;
3677    }
3679    tr.priority-urgent td {
3680        background-color: orange;
3681    }
3683 and so on, with far less offensive colours :)
3685 Editing multiple items in an index view
3686 ---------------------------------------
3688 To edit the status of all items in the item index view, edit the
3689 ``issue.item.html``:
3691 1. add a form around the listing table, so at the top it reads::
3693     <form method="POST" tal:attributes="action request/classname">
3694      <table class="list">
3696    and at the bottom of that table::
3698      </table>
3699     </form
3701    making sure you match the ``</table>`` from the list table, not the
3702    navigation table or the subsequent form table.
3704 2. in the display for the issue property, change::
3706     <td tal:condition="request/show/status"
3707         tal:content="python:i.status.plain() or default">&nbsp;</td>
3709    to::
3711     <td tal:condition="request/show/status"
3712         tal:content="structure i/status/field">&nbsp;</td>
3714    this will result in an edit field for the status property.
3716 3. after the ``tal:block`` which lists the actual index items (marked by
3717    ``tal:repeat="i batch"``) add a new table row::
3719     <tr>
3720      <td tal:attributes="colspan python:len(request.columns)">
3721       <input type="submit" value=" Save Changes ">
3722       <input type="hidden" name="@action" value="edit">
3723       <tal:block replace="structure request/indexargs_form" />
3724      </td>
3725     </tr>
3727    which gives us a submit button, indicates that we are performing an edit
3728    on any changed statuses and the final block will make sure that the
3729    current index view parameters (filtering, columns, etc) will be used in 
3730    rendering the next page (the results of the editing).
3732 -------------------
3734 Back to `Table of Contents`_
3736 .. _`Table of Contents`: index.html
3737 .. _`design documentation`: design.html