Code

added another sample detector
[roundup.git] / doc / customizing.txt
1 ===================
2 Customising Roundup
3 ===================
5 :Version: $Revision: 1.133 $
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 **ERROR_MESSAGES_TO** - ``'user'``, ``'dispatcher'`` or ``'both'``
150  Sends error messages to the dispatcher, user, or both. It will use the
151  ``DISPATCHER_EMAIL`` address if set, otherwise it'll use the
152  ``ADMIN_EMAIL`` address.
154 **DISPATCHER_EMAIL** - ``''``
155   The email address that Roundup will issue all error messages to. This is
156   also useful if you want to switch your 'new message' notification to
157   a central user. 
159 **MESSAGES_TO_AUTHOR** - ``'new'``, ``'yes'`` or``'no'``
160  Send nosy messages to the author of the message?
161  If 'new' is used, then the author will only be sent the message when the
162  message creates a new issue. If 'yes' then the author will always be sent
163  a copy of the message they wrote.
165 **ADD_AUTHOR_TO_NOSY** - ``'new'``, ``'yes'`` or ``'no'``
166  Does the author of a message get placed on the nosy list automatically?
167  If ``'new'`` is used, then the author will only be added when a message
168  creates a new issue. If ``'yes'``, then the author will be added on followups
169  too. If ``'no'``, they're never added to the nosy.
171 **ADD_RECIPIENTS_TO_NOSY** - ``'new'``, ``'yes'`` or ``'no'``
172  Do the recipients (To:, Cc:) of a message get placed on the nosy list?
173  If ``'new'`` is used, then the recipients will only be added when a message
174  creates a new issue. If ``'yes'``, then the recipients will be added on
175  followups too. If ``'no'``, they're never added to the nosy.
177 **EMAIL_SIGNATURE_POSITION** - ``'top'``, ``'bottom'`` or ``'none'``
178  Where to place the email signature in messages that Roundup generates.
180 **EMAIL_KEEP_QUOTED_TEXT** - ``'yes'`` or ``'no'``
181  Keep email citations. Citations are the part of e-mail which the sender has
182  quoted in their reply to previous e-mail with ``>`` or ``|`` characters at
183  the start of the line.
185 **EMAIL_LEAVE_BODY_UNCHANGED** - ``'no'``
186  Preserve the email body as is. Enabiling this will cause the entire message
187  body to be stored, including all citations, signatures and Outlook-quoted
188  sections (ie. "Original Message" blocks). It should be either ``'yes'``
189  or ``'no'``.
191 **MAIL_DEFAULT_CLASS** - ``'issue'`` or ``''``
192  Default class to use in the mailgw if one isn't supplied in email
193  subjects. To disable, comment out the variable below or leave it blank.
195 **HTML_VERSION** -  ``'html4'`` or ``'xhtml'``
196  HTML version to generate. The templates are html4 by default. If you
197  wish to make them xhtml, then you'll need to change this var to 'xhtml'
198  too so all auto-generated HTML is compliant.
200 **EMAIL_CHARSET** - ``utf-8`` (or ``iso-8859-1`` for Eudora users)
201  Character set to encode email headers with. We use utf-8 by default, as
202  it's the most flexible. Some mail readers (eg. Eudora) can't cope with
203  that, so you might need to specify a more limited character set (eg.
204  'iso-8859-1'.
206 **DEFAULT_TIMEZONE** - ``0``
207  Numeric hour timezone offest to be used when displaying local times.
208  The default timezone is used when users do not choose their own in
209  their settings.
211 The default config.py is given below - as you
212 can see, the MAIL_DOMAIN must be edited before any interaction with the
213 tracker is attempted.::
215     # roundup home is this package's directory
216     TRACKER_HOME=os.path.split(__file__)[0]
218     # The SMTP mail host that roundup will use to send mail
219     MAILHOST = 'localhost'
221     # The domain name used for email addresses.
222     MAIL_DOMAIN = 'your.tracker.email.domain.example'
224     # This is the directory that the database is going to be stored in
225     DATABASE = os.path.join(TRACKER_HOME, 'db')
227     # This is the directory that the HTML templates reside in
228     TEMPLATES = os.path.join(TRACKER_HOME, 'html')
230     # A descriptive name for your roundup tracker
231     TRACKER_NAME = 'Roundup issue tracker'
233     # The email address that mail to roundup should go to
234     TRACKER_EMAIL = 'issue_tracker@%s'%MAIL_DOMAIN
236     # The web address that the tracker is viewable at. This will be
237     # included in information sent to users of the tracker. The URL MUST
238     # include the cgi-bin part or anything else that is required to get
239     # to the home page of the tracker. You MUST include a trailing '/'
240     # in the URL.
241     TRACKER_WEB = 'http://tracker.example/cgi-bin/roundup.cgi/bugs/'
243     # The email address that roundup will complain to if it runs into
244     # trouble
245     ADMIN_EMAIL = 'roundup-admin@%s'%MAIL_DOMAIN
247     # Additional text to include in the "name" part of the From: address
248     # used in nosy messages. If the sending user is "Foo Bar", the From:
249     # line is usually: "Foo Bar" <issue_tracker@tracker.example>
250     # the EMAIL_FROM_TAG goes inside the "Foo Bar" quotes like so:
251     #    "Foo Bar EMAIL_FROM_TAG" <issue_tracker@tracker.example>
252     EMAIL_FROM_TAG = ""
254     # Send nosy messages to the author of the message
255     MESSAGES_TO_AUTHOR = 'no'           # either 'yes' or 'no'
257     # Does the author of a message get placed on the nosy list
258     # automatically? If 'new' is used, then the author will only be
259     # added when a message creates a new issue. If 'yes', then the
260     # author will be added on followups too. If 'no', they're never
261     # added to the nosy.
262     ADD_AUTHOR_TO_NOSY = 'new'          # one of 'yes', 'no', 'new'
264     # Do the recipients (To:, Cc:) of a message get placed on the nosy
265     # list? If 'new' is used, then the recipients will only be added
266     # when a message creates a new issue. If 'yes', then the recipients
267     # will be added on followups too. If 'no', they're never added to
268     # the nosy.
269     ADD_RECIPIENTS_TO_NOSY = 'new'      # either 'yes', 'no', 'new'
271     # Where to place the email signature
272     EMAIL_SIGNATURE_POSITION = 'bottom' # one of 'top', 'bottom', 'none'
274     # Keep email citations
275     EMAIL_KEEP_QUOTED_TEXT = 'no'       # either 'yes' or 'no'
277     # Preserve the email body as is
278     EMAIL_LEAVE_BODY_UNCHANGED = 'no'   # either 'yes' or 'no'
280     # Default class to use in the mailgw if one isn't supplied in email
281     # subjects. To disable, comment out the variable below or leave it
282     # blank. Examples:
283     MAIL_DEFAULT_CLASS = 'issue'   # use "issue" class by default
284     #MAIL_DEFAULT_CLASS = ''        # disable (or just comment the var out)
286     # HTML version to generate. The templates are html4 by default. If you
287     # wish to make them xhtml, then you'll need to change this var to 'xhtml'
288     # too so all auto-generated HTML is compliant.
289     HTML_VERSION = 'html4'         # either 'html4' or 'xhtml'
291     # Character set to encode email headers with. We use utf-8 by default, as
292     # it's the most flexible. Some mail readers (eg. Eudora) can't cope with
293     # that, so you might need to specify a more limited character set (eg.
294     # 'iso-8859-1'.
295     EMAIL_CHARSET = 'utf-8'
296     #EMAIL_CHARSET = 'iso-8859-1'   # use this instead for Eudora users
298     # You may specify a different default timezone, for use when users do not
299     # choose their own in their settings.
300     DEFAULT_TIMEZONE = 0            # specify as numeric hour offest
302     # 
303     # SECURITY DEFINITIONS
304     #
305     # define the Roles that a user gets when they register with the
306     # tracker these are a comma-separated string of role names (e.g.
307     # 'Admin,User')
308     NEW_WEB_USER_ROLES = 'User'
309     NEW_EMAIL_USER_ROLES = 'User'
311 Tracker Schema
312 ==============
314 Note: if you modify the schema, you'll most likely need to edit the
315       `web interface`_ HTML template files and `detectors`_ to reflect
316       your changes.
318 A tracker schema defines what data is stored in the tracker's database.
319 Schemas are defined using Python code in the ``dbinit.py`` module of your
320 tracker.
322 The ``dbinit.py`` module
323 ------------------------
325 The ``dbinit.py`` module contains two functions:
327 **open**
328   This function defines what your tracker looks like on the inside, the
329   **schema** of the tracker. It defines the **Classes** and **properties**
330   on each class. It also defines the **security** for those Classes. The
331   next few sections describe how schemas work and what you can do with
332   them.
333 **init**
334   This function is responsible for setting up the initial state of your
335   tracker. It's called exactly once - but the ``roundup-admin initialise``
336   command.  See the start of the section on `database content`_ for more
337   info about how this works.
340 The "classic" schema
341 --------------------
343 The "classic" schema looks like this (see below for the meaning
344 of ``'setkey'``)::
346     pri = Class(db, "priority", name=String(), order=String())
347     pri.setkey("name")
349     stat = Class(db, "status", name=String(), order=String())
350     stat.setkey("name")
352     keyword = Class(db, "keyword", name=String())
353     keyword.setkey("name")
355     user = Class(db, "user", username=String(), organisation=String(),
356         password=String(), address=String(), realname=String(),
357         phone=String())
358     user.setkey("username")
360     msg = FileClass(db, "msg", author=Link("user"), summary=String(),
361         date=Date(), recipients=Multilink("user"),
362         files=Multilink("file"))
364     file = FileClass(db, "file", name=String(), type=String())
366     issue = IssueClass(db, "issue", topic=Multilink("keyword"),
367         status=Link("status"), assignedto=Link("user"),
368         priority=Link("priority"))
369     issue.setkey('title')
372 What you can't do to the schema
373 -------------------------------
375 You must never:
377 **Remove the users class**
378   This class is the only *required* class in Roundup. Similarly, its
379   username, password and address properties must never be removed.
381 **Change the type of a property**
382   Property types must *never* be changed - the database simply doesn't take
383   this kind of action into account. Note that you can't just remove a
384   property and re-add it as a new type either. If you wanted to make the
385   assignedto property a Multilink, you'd need to create a new property
386   assignedto_list and remove the old assignedto property.
389 What you can do to the schema
390 -----------------------------
392 Your schema may be changed at any time before or after the tracker has been
393 initialised (or used). You may:
395 **Add new properties to classes, or add whole new classes**
396   This is painless and easy to do - there are generally no repurcussions
397   from adding new information to a tracker's schema.
399 **Remove properties**
400   Removing properties is a little more tricky - you need to make sure that
401   the property is no longer used in the `web interface`_ *or* by the
402   detectors_.
406 Classes and Properties - creating a new information store
407 ---------------------------------------------------------
409 In the tracker above, we've defined 7 classes of information:
411   priority
412       Defines the possible levels of urgency for issues.
414   status
415       Defines the possible states of processing the issue may be in.
417   keyword
418       Initially empty, will hold keywords useful for searching issues.
420   user
421       Initially holding the "admin" user, will eventually have an entry
422       for all users using roundup.
424   msg
425       Initially empty, will hold all e-mail messages sent to or
426       generated by roundup.
428   file
429       Initially empty, will hold all files attached to issues.
431   issue
432       Initially empty, this is where the issue information is stored.
434 We define the "priority" and "status" classes to allow two things:
435 reduction in the amount of information stored on the issue and more
436 powerful, accurate searching of issues by priority and status. By only
437 requiring a link on the issue (which is stored as a single number) we
438 reduce the chance that someone mis-types a priority or status - or
439 simply makes a new one up.
442 Class and Items
443 ~~~~~~~~~~~~~~~
445 A Class defines a particular class (or type) of data that will be stored
446 in the database. A class comprises one or more properties, which gives
447 the information about the class items.
449 The actual data entered into the database, using ``class.create()``, are
450 called items. They have a special immutable property called ``'id'``. We
451 sometimes refer to this as the *itemid*.
454 Properties
455 ~~~~~~~~~~
457 A Class is comprised of one or more properties of the following types:
459 * String properties are for storing arbitrary-length strings.
460 * Password properties are for storing encoded arbitrary-length strings.
461   The default encoding is defined on the ``roundup.password.Password``
462   class.
463 * Date properties store date-and-time stamps. Their values are Timestamp
464   objects.
465 * Number properties store numeric values.
466 * Boolean properties store on/off, yes/no, true/false values.
467 * A Link property refers to a single other item selected from a
468   specified class. The class is part of the property; the value is an
469   integer, the id of the chosen item.
470 * A Multilink property refers to possibly many items in a specified
471   class. The value is a list of integers.
474 FileClass
475 ~~~~~~~~~
477 FileClasses save their "content" attribute off in a separate file from
478 the rest of the database. This reduces the number of large entries in
479 the database, which generally makes databases more efficient, and also
480 allows us to use command-line tools to operate on the files. They are
481 stored in the files sub-directory of the ``'db'`` directory in your
482 tracker.
485 IssueClass
486 ~~~~~~~~~~
488 IssueClasses automatically include the "messages", "files", "nosy", and
489 "superseder" properties.
491 The messages and files properties list the links to the messages and
492 files related to the issue. The nosy property is a list of links to
493 users who wish to be informed of changes to the issue - they get "CC'ed"
494 e-mails when messages are sent to or generated by the issue. The nosy
495 reactor (in the ``'detectors'`` directory) handles this action. The
496 superseder link indicates an issue which has superseded this one.
498 They also have the dynamically generated "creation", "activity" and
499 "creator" properties.
501 The value of the "creation" property is the date when an item was
502 created, and the value of the "activity" property is the date when any
503 property on the item was last edited (equivalently, these are the dates
504 on the first and last records in the item's journal). The "creator"
505 property holds a link to the user that created the issue.
508 setkey(property)
509 ~~~~~~~~~~~~~~~~
511 Select a String property of the class to be the key property. The key
512 property must be unique, and allows references to the items in the class
513 by the content of the key property. That is, we can refer to users by
514 their username: for example, let's say that there's an issue in roundup,
515 issue 23. There's also a user, richard, who happens to be user 2. To
516 assign an issue to him, we could do either of::
518      roundup-admin set issue23 assignedto=2
520 or::
522      roundup-admin set issue23 assignedto=richard
524 Note, the same thing can be done in the web and e-mail interfaces. 
526 If a class does not have an "order" property, the key is also used to
527 sort instances of the class when it is rendered in the user interface.
528 (If a class has no "order" property, sorting is by the labelproperty of
529 the class. This is computed, in order of precedence, as the key, the
530 "name", the "title", or the first property alphabetically.)
533 create(information)
534 ~~~~~~~~~~~~~~~~~~~
536 Create an item in the database. This is generally used to create items
537 in the "definitional" classes like "priority" and "status".
540 Examples of adding to your schema
541 ---------------------------------
543 TODO
546 Detectors - adding behaviour to your tracker
547 ============================================
548 .. _detectors:
550 Detectors are initialised every time you open your tracker database, so
551 you're free to add and remove them any time, even after the database is
552 initialised via the "roundup-admin initialise" command.
554 The detectors in your tracker fire *before* (**auditors**) and *after*
555 (**reactors**) changes to the contents of your database. They are Python
556 modules that sit in your tracker's ``detectors`` directory. You will
557 have some installed by default - have a look. You can write new
558 detectors or modify the existing ones. The existing detectors installed
559 for you are:
561 **nosyreaction.py**
562   This provides the automatic nosy list maintenance and email sending.
563   The nosy reactor (``nosyreaction``) fires when new messages are added
564   to issues. The nosy auditor (``updatenosy``) fires when issues are
565   changed, and figures out what changes need to be made to the nosy list
566   (such as adding new authors, etc.)
567 **statusauditor.py**
568   This provides the ``chatty`` auditor which changes the issue status
569   from ``unread`` or ``closed`` to ``chatting`` if new messages appear.
570   It also provides the ``presetunread`` auditor which pre-sets the
571   status to ``unread`` on new items if the status isn't explicitly
572   defined.
573 **messagesummary.py**
574   Generates the ``summary`` property for new messages based on the message
575   content.
576 **userauditor.py**
577   Verifies the content of some of the user fields (email addresses and
578   roles lists).
580 If you don't want this default behaviour, you're completely free to change
581 or remove these detectors.
583 See the detectors section in the `design document`__ for details of the
584 interface for detectors.
586 __ design.html
588 Additional Detectors Ready For Use
589 ----------------------------------
591 Sample additional detectors that have been found useful will appear in
592 the ``'detectors'`` directory of the Roundup distribution. If you want
593 to use one, copy it to the ``'detectors'`` of your tracker instance:
595 **newissuecopy.py**
596   This detector sends an email to a team address whenever a new issue is
597   created. The address is hard-coded into the detector, so edit it
598   before you use it (look for the text 'team@team.host') or you'll get
599   email errors!
600 **creator_resolution.py**
601   Catch attempts to set the status to "resolved" - if the assignedto
602   user isn't the creator, then set the status to "confirm-done". Note that
603   "classic" Roundup doesn't have that status, so you'll have to add it. If
604   you don't want to though, it'll just use "in-progress" instead.
605 **email_auditor.py**
606   If a file added to an issue is of type message/rfc822, we tack on the
607   extension .eml.
608   The reason for this is that Microsoft Internet Explorer will not open
609   things with a .eml attachment, as they deem it 'unsafe'. Worse yet,
610   they'll just give you an incomprehensible error message. For more 
611   information, see the detector code - it has a length explanation.
614 Auditor or Reactor?
615 -------------------
617 Generally speaking, the following rules should be observed:
619 **Auditors**
620   Are used for `vetoing creation of or changes to items`_. They might
621   also make automatic changes to item properties.
622 **Reactors**
623   Detect changes in the database and react accordingly. They should avoid
624   making changes to the database where possible, as this could create
625   detector loops.
628 Vetoing creation of or changes to items
629 ---------------------------------------
631 Auditors may raise the ``Reject`` exception to prevent the creation of
632 or changes to items in the database.  The mail gateway, for example, will
633 not attach files or messages to issues when the creation of those files or
634 messages are prevented through the ``Reject`` exception. It'll also not create
635 users if that creation is ``Reject``'ed too.
637 To use, simply add at the top of your auditor::
639    from roundup.exceptions import Reject
641 And then when your rejection criteria have been detected, simply::
643    raise Reject
646 Generating email from Roundup
647 -----------------------------
649 The module ``roundup.mailer`` contains most of the nuts-n-bolts required
650 to generate email messages from Roundup.
652 In addition, the ``IssueClass`` methods ``nosymessage()`` and
653 ``send_message()`` are used to generate nosy messages, and may generate
654 messages which only consist of a change note (ie. the message id parameter
655 is not required).
658 Database Content
659 ================
661 Note: if you modify the content of definitional classes, you'll most
662        likely need to edit the tracker `detectors`_ to reflect your
663        changes.
665 Customisation of the special "definitional" classes (eg. status,
666 priority, resolution, ...) may be done either before or after the
667 tracker is initialised. The actual method of doing so is completely
668 different in each case though, so be careful to use the right one.
670 **Changing content before tracker initialisation**
671     Edit the dbinit module in your tracker to alter the items created in
672     using the ``create()`` methods.
674 **Changing content after tracker initialisation**
675     As the "admin" user, click on the "class list" link in the web
676     interface to bring up a list of all database classes. Click on the
677     name of the class you wish to change the content of.
679     You may also use the ``roundup-admin`` interface's create, set and
680     retire methods to add, alter or remove items from the classes in
681     question.
683 See "`adding a new field to the classic schema`_" for an example that
684 requires database content changes.
687 Security / Access Controls
688 ==========================
690 A set of Permissions is built into the security module by default:
692 - Edit (everything)
693 - View (everything)
695 Every Class you define in your tracker's schema also gets an Edit and View
696 Permission of its own.
698 The default interfaces define:
700 - Web Registration
701 - Web Access
702 - Web Roles
703 - Email Registration
704 - Email Access
706 These are hooked into the default Roles:
708 - Admin (Edit everything, View everything, Web Roles)
709 - User (Web Access, Email Access)
710 - Anonymous (Web Registration, Email Registration)
712 And finally, the "admin" user gets the "Admin" Role, and the "anonymous"
713 user gets "Anonymous" assigned when the database is initialised on
714 installation. The two default schemas then define:
716 - Edit issue, View issue (both)
717 - Edit file, View file (both)
718 - Edit msg, View msg (both)
719 - Edit support, View support (extended only)
721 and assign those Permissions to the "User" Role. Put together, these
722 settings appear in the ``open()`` function of the tracker ``dbinit.py``
723 (the following is taken from the "minimal" template's ``dbinit.py``)::
725     #
726     # SECURITY SETTINGS
727     #
728     # and give the regular users access to the web and email interface
729     p = db.security.getPermission('Web Access')
730     db.security.addPermissionToRole('User', p)
731     p = db.security.getPermission('Email Access')
732     db.security.addPermissionToRole('User', p)
734     # May users view other user information? Comment these lines out
735     # if you don't want them to
736     p = db.security.getPermission('View', 'user')
737     db.security.addPermissionToRole('User', p)
739     # Assign the appropriate permissions to the anonymous user's
740     # Anonymous role. Choices here are:
741     # - Allow anonymous users to register through the web
742     p = db.security.getPermission('Web Registration')
743     db.security.addPermissionToRole('Anonymous', p)
744     # - Allow anonymous (new) users to register through the email
745     #   gateway
746     p = db.security.getPermission('Email Registration')
747     db.security.addPermissionToRole('Anonymous', p)
750 New User Roles
751 --------------
753 New users are assigned the Roles defined in the config file as:
755 - NEW_WEB_USER_ROLES
756 - NEW_EMAIL_USER_ROLES
759 Changing Access Controls
760 ------------------------
762 You may alter the configuration variables to change the Role that new
763 web or email users get, for example to not give them access to the web
764 interface if they register through email. 
766 You may use the ``roundup-admin`` "``security``" command to display the
767 current Role and Permission configuration in your tracker.
770 Adding a new Permission
771 ~~~~~~~~~~~~~~~~~~~~~~~
773 When adding a new Permission, you will need to:
775 1. add it to your tracker's dbinit so it is created, using
776    ``security.addPermission``, for example::
778     self.security.addPermission(name="View", klass='frozzle',
779         description="User is allowed to access frozzles")
781    will set up a new "View" permission on the Class "frozzle".
782 2. enable it for the Roles that should have it (verify with
783    "``roundup-admin security``")
784 3. add it to the relevant HTML interface templates
785 4. add it to the appropriate xxxPermission methods on in your tracker
786    interfaces module
789 Example Scenarios
790 ~~~~~~~~~~~~~~~~~
792 **automatic registration of users in the e-mail gateway**
793  By giving the "anonymous" user the "Email Registration" Role, any
794  unidentified user will automatically be registered with the tracker
795  (with no password, so they won't be able to log in through the web
796  until an admin sets their password). Note: this is the default
797  behaviour in the tracker templates that ship with Roundup.
799 **anonymous access through the e-mail gateway**
800  Give the "anonymous" user the "Email Access" and ("Edit", "issue")
801  Roles but do not not give them the "Email Registration" Role. This
802  means that when an unknown user sends email into the tracker, they're
803  automatically logged in as "anonymous". Since they don't have the
804  "Email Registration" Role, they won't be automatically registered, but
805  since "anonymous" has permission to use the gateway, they'll still be
806  able to submit issues. Note that the Sender information - their email
807  address - will not be available - they're *anonymous*.
809 **only developers may be assigned issues**
810  Create a new Permission called "Fixer" for the "issue" class. Create a
811  new Role "Developer" which has that Permission, and assign that to the
812  appropriate users. Filter the list of users available in the assignedto
813  list to include only those users. Enforce the Permission with an
814  auditor. See the example 
815  `restricting the list of users that are assignable to a task`_.
817 **only managers may sign off issues as complete**
818  Create a new Permission called "Closer" for the "issue" class. Create a
819  new Role "Manager" which has that Permission, and assign that to the
820  appropriate users. In your web interface, only display the "resolved"
821  issue state option when the user has the "Closer" Permissions. Enforce
822  the Permission with an auditor. This is very similar to the previous
823  example, except that the web interface check would look like::
825    <option tal:condition="python:request.user.hasPermission('Closer')"
826            value="resolved">Resolved</option>
827  
828 **don't give web access to users who register through email**
829  Create a new Role called "Email User" which has all the Permissions of
830  the normal "User" Role minus the "Web Access" Permission. This will
831  allow users to send in emails to the tracker, but not access the web
832  interface.
834 **let some users edit the details of all users**
835  Create a new Role called "User Admin" which has the Permission for
836  editing users::
838     db.security.addRole(name='User Admin', description='Managing users')
839     p = db.security.getPermission('Edit', 'user')
840     db.security.addPermissionToRole('User Admin', p)
842  and assign the Role to the users who need the permission.
845 Web Interface
846 =============
848 .. contents::
849    :local:
851 The web interface is provided by the ``roundup.cgi.client`` module and
852 is used by ``roundup.cgi``, ``roundup-server`` and ``ZRoundup``
853 (``ZRoundup``  is broken, until further notice). In all cases, we
854 determine which tracker is being accessed (the first part of the URL
855 path inside the scope of the CGI handler) and pass control on to the
856 tracker ``interfaces.Client`` class - which uses the ``Client`` class
857 from ``roundup.cgi.client`` - which handles the rest of the access
858 through its ``main()`` method. This means that you can do pretty much
859 anything you want as a web interface to your tracker.
861 Repercussions of changing the tracker schema
862 ---------------------------------------------
864 If you choose to change the `tracker schema`_ you will need to ensure
865 the web interface knows about it:
867 1. Index, item and search pages for the relevant classes may need to
868    have properties added or removed,
869 2. The "page" template may require links to be changed, as might the
870    "home" page's content arguments.
872 How requests are processed
873 --------------------------
875 The basic processing of a web request proceeds as follows:
877 1. figure out who we are, defaulting to the "anonymous" user
878 2. figure out what the request is for - we call this the "context"
879 3. handle any requested action (item edit, search, ...)
880 4. render the template requested by the context, resulting in HTML
881    output
883 In some situations, exceptions occur:
885 - HTTP Redirect  (generally raised by an action)
886 - SendFile       (generally raised by ``determine_context``)
887     here we serve up a FileClass "content" property
888 - SendStaticFile (generally raised by ``determine_context``)
889     here we serve up a file from the tracker "html" directory
890 - Unauthorised   (generally raised by an action)
891     here the action is cancelled, the request is rendered and an error
892     message is displayed indicating that permission was not granted for
893     the action to take place
894 - NotFound       (raised wherever it needs to be)
895     this exception percolates up to the CGI interface that called the
896     client
898 Determining web context
899 -----------------------
901 To determine the "context" of a request, we look at the URL and the
902 special request variable ``@template``. The URL path after the tracker
903 identifier is examined. Typical URL paths look like:
905 1.  ``/tracker/issue``
906 2.  ``/tracker/issue1``
907 3.  ``/tracker/@file/style.css``
908 4.  ``/cgi-bin/roundup.cgi/tracker/file1``
909 5.  ``/cgi-bin/roundup.cgi/tracker/file1/kitten.png``
911 where the "tracker identifier" is "tracker" in the above cases. That means
912 we're looking at "issue", "issue1", "@file/style.css", "file1" and
913 "file1/kitten.png" in the cases above. The path is generally only one
914 entry long - longer paths are handled differently.
916 a. if there is no path, then we are in the "home" context.
917 b. if the path starts with "@file" (as in example 3,
918    "/tracker/@file/style.css"), then the additional path entry,
919    "style.css" specifies the filename of a static file we're to serve up
920    from the tracker "html" directory. Raises a SendStaticFile exception.
921 c. if there is something in the path (as in example 1, "issue"), it
922    identifies the tracker class we're to display.
923 d. if the path is an item designator (as in examples 2 and 4, "issue1"
924    and "file1"), then we're to display a specific item.
925 e. if the path starts with an item designator and is longer than one
926    entry (as in example 5, "file1/kitten.png"), then we're assumed to be
927    handling an item of a ``FileClass``, and the extra path information
928    gives the filename that the client is going to label the download
929    with (i.e. "file1/kitten.png" is nicer to download than "file1").
930    This raises a ``SendFile`` exception.
932 Both b. and e. stop before we bother to determine the template we're
933 going to use. That's because they don't actually use templates.
935 The template used is specified by the ``@template`` CGI variable, which
936 defaults to:
938 - only classname suplied:        "index"
939 - full item designator supplied: "item"
942 Serving static content
943 ----------------------
945 See the previous section `determining web context`_ where it describes
946 ``@file`` paths.
949 Performing actions in web requests
950 ----------------------------------
952 When a user requests a web page, they may optionally also request for an
953 action to take place. As described in `how requests are processed`_, the
954 action is performed before the requested page is generated. Actions are
955 triggered by using a ``@action`` CGI variable, where the value is one
956 of:
958 **login**
959  Attempt to log a user in.
961 **logout**
962  Log the user out - make them "anonymous".
964 **register**
965  Attempt to create a new user based on the contents of the form and then
966  log them in.
968 **edit**
969  Perform an edit of an item in the database. There are some `special form
970  variables`_ you may use.
972 **new**
973  Add a new item to the database. You may use the same `special form
974  variables`_ as in the "edit" action.
976 **retire**
977  Retire the item in the database.
979 **editCSV**
980  Performs an edit of all of a class' items in one go. See also the
981  *class*.csv templating method which generates the CSV data to be
982  edited, and the ``'_generic.index'`` template which uses both of these
983  features.
985 **search**
986  Mangle some of the form variables:
988  - Set the form ":filter" variable based on the values of the filter
989    variables - if they're set to anything other than "dontcare" then add
990    them to :filter.
992  - Also handle the ":queryname" variable and save off the query to the
993    user's query list.
995 Each of the actions is implemented by a corresponding ``*XxxAction*`` (where
996 "Xxx" is the name of the action) class in the ``roundup.cgi.actions`` module.
997 These classes are registered with ``roundup.cgi.client.Client`` which also
998 happens to be available in your tracker instance as ``interfaces.Client``. So
999 if you need to define new actions, you may add them there (see `defining new
1000 web actions`_).
1002 Each action class also has a ``*permission*`` method which determines whether
1003 the action is permissible given the current user. The base permission checks
1004 are:
1006 **login**
1007  Determine whether the user has permission to log in. Base behaviour is
1008  to check the user has "Web Access".
1009 **logout**
1010  No permission checks are made.
1011 **register**
1012  Determine whether the user has permission to register. Base behaviour
1013  is to check the user has the "Web Registration" Permission.
1014 **edit**
1015  Determine whether the user has permission to edit this item. Base
1016  behaviour is to check whether the user can edit this class. If we're
1017  editing the "user" class, users are allowed to edit their own details -
1018  unless they try to edit the "roles" property, which requires the
1019  special Permission "Web Roles".
1020 **new**
1021  Determine whether the user has permission to create (or edit) this
1022  item. Base behaviour is to check the user can edit this class. No
1023  additional property checks are made. Additionally, new user items may
1024  be created if the user has the "Web Registration" Permission.
1025 **editCSV**
1026  Determine whether the user has permission to edit this class. Base
1027  behaviour is to check whether the user may edit this class.
1028 **search**
1029  Determine whether the user has permission to search this class. Base
1030  behaviour is to check whether the user may view this class.
1033 Special form variables
1034 ----------------------
1036 Item properties and their values are edited with html FORM
1037 variables and their values. You can:
1039 - Change the value of some property of the current item.
1040 - Create a new item of any class, and edit the new item's
1041   properties,
1042 - Attach newly created items to a multilink property of the
1043   current item.
1044 - Remove items from a multilink property of the current item.
1045 - Specify that some properties are required for the edit
1046   operation to be successful.
1048 In the following, <bracketed> values are variable, "@" may be
1049 either ":" or "@", and other text "required" is fixed.
1051 Most properties are specified as form variables:
1053 ``<propname>``
1054   property on the current context item
1056 ``<designator>"@"<propname>``
1057   property on the indicated item (for editing related information)
1059 Designators name a specific item of a class.
1061 ``<classname><N>``
1062     Name an existing item of class <classname>.
1064 ``<classname>"-"<N>``
1065     Name the <N>th new item of class <classname>. If the form
1066     submission is successful, a new item of <classname> is
1067     created. Within the submitted form, a particular
1068     designator of this form always refers to the same new
1069     item.
1071 Once we have determined the "propname", we look at it to see
1072 if it's special:
1074 ``@required``
1075     The associated form value is a comma-separated list of
1076     property names that must be specified when the form is
1077     submitted for the edit operation to succeed.  
1079     When the <designator> is missing, the properties are
1080     for the current context item.  When <designator> is
1081     present, they are for the item specified by
1082     <designator>.
1084     The "@required" specifier must come before any of the
1085     properties it refers to are assigned in the form.
1087 ``@remove@<propname>=id(s)`` or ``@add@<propname>=id(s)``
1088     The "@add@" and "@remove@" edit actions apply only to
1089     Multilink properties.  The form value must be a
1090     comma-separate list of keys for the class specified by
1091     the simple form variable.  The listed items are added
1092     to (respectively, removed from) the specified
1093     property.
1095 ``@link@<propname>=<designator>``
1096     If the edit action is "@link@", the simple form
1097     variable must specify a Link or Multilink property.
1098     The form value is a comma-separated list of
1099     designators.  The item corresponding to each
1100     designator is linked to the property given by simple
1101     form variable.
1103 None of the above (ie. just a simple form value)
1104     The value of the form variable is converted
1105     appropriately, depending on the type of the property.
1107     For a Link('klass') property, the form value is a
1108     single key for 'klass', where the key field is
1109     specified in dbinit.py.  
1111     For a Multilink('klass') property, the form value is a
1112     comma-separated list of keys for 'klass', where the
1113     key field is specified in dbinit.py.  
1115     Note that for simple-form-variables specifiying Link
1116     and Multilink properties, the linked-to class must
1117     have a key field.
1119     For a String() property specifying a filename, the
1120     file named by the form value is uploaded. This means we
1121     try to set additional properties "filename" and "type" (if
1122     they are valid for the class).  Otherwise, the property
1123     is set to the form value.
1125     For Date(), Interval(), Boolean(), and Number()
1126     properties, the form value is converted to the
1127     appropriate
1129 Any of the form variables may be prefixed with a classname or
1130 designator.
1132 Two special form values are supported for backwards compatibility:
1134 @note
1135     This is equivalent to::
1137         @link@messages=msg-1
1138         msg-1@content=value
1140     except that in addition, the "author" and "date" properties of
1141     "msg-1" are set to the userid of the submitter, and the current
1142     time, respectively.
1144 @file
1145     This is equivalent to::
1147         @link@files=file-1
1148         file-1@content=value
1150     The String content value is handled as described above for file
1151     uploads.
1153 If both the "@note" and "@file" form variables are
1154 specified, the action::
1156         @link@msg-1@files=file-1
1158 is also performed.
1160 We also check that FileClass items have a "content" property with
1161 actual content, otherwise we remove them from all_props before
1162 returning.
1166 Default templates
1167 -----------------
1169 The default templates are html4 compliant. If you wish to change them to be
1170 xhtml compliant, you'll need to change the ``HTML_VERSION`` configuration
1171 variable in ``config.py`` to ``'xhtml'`` instead of ``'html4'``.
1173 Most customisation of the web view can be done by modifying the
1174 templates in the tracker ``'html'`` directory. There are several types
1175 of files in there. The *minimal* template includes:
1177 **page.html**
1178   This template usually defines the overall look of your tracker. When
1179   you view an issue, it appears inside this template. When you view an
1180   index, it also appears inside this template. This template defines a
1181   macro called "icing" which is used by almost all other templates as a
1182   coating for their content, using its "content" slot. It also defines
1183   the "head_title" and "body_title" slots to allow setting of the page
1184   title.
1185 **home.html**
1186   the default page displayed when no other page is indicated by the user
1187 **home.classlist.html**
1188   a special version of the default page that lists the classes in the
1189   tracker
1190 **classname.item.html**
1191   displays an item of the *classname* class
1192 **classname.index.html**
1193   displays a list of *classname* items
1194 **classname.search.html**
1195   displays a search page for *classname* items
1196 **_generic.index.html**
1197   used to display a list of items where there is no
1198   ``*classname*.index`` available
1199 **_generic.help.html**
1200   used to display a "class help" page where there is no
1201   ``*classname*.help``
1202 **user.register.html**
1203   a special page just for the user class, that renders the registration
1204   page
1205 **style.css.html**
1206   a static file that is served up as-is
1208 The *classic* template has a number of additional templates.
1210 Note: Remember that you can create any template extension you want to,
1211 so if you just want to play around with the templating for new issues,
1212 you can copy the current "issue.item" template to "issue.test", and then
1213 access the test template using the "@template" URL argument::
1215    http://your.tracker.example/tracker/issue?@template=test
1217 and it won't affect your users using the "issue.item" template.
1220 How the templates work
1221 ----------------------
1224 Basic Templating Actions
1225 ~~~~~~~~~~~~~~~~~~~~~~~~
1227 Roundup's templates consist of special attributes on the HTML tags.
1228 These attributes form the Template Attribute Language, or TAL. The basic
1229 TAL commands are:
1231 **tal:define="variable expression; variable expression; ..."**
1232    Define a new variable that is local to this tag and its contents. For
1233    example::
1235       <html tal:define="title request/description">
1236        <head><title tal:content="title"></title></head>
1237       </html>
1239    In this example, the variable "title" is defined as the result of the
1240    expression "request/description". The "tal:content" command inside the
1241    <html> tag may then use the "title" variable.
1243 **tal:condition="expression"**
1244    Only keep this tag and its contents if the expression is true. For
1245    example::
1247      <p tal:condition="python:request.user.hasPermission('View', 'issue')">
1248       Display some issue information.
1249      </p>
1251    In the example, the <p> tag and its contents are only displayed if
1252    the user has the "View" permission for issues. We consider the number
1253    zero, a blank string, an empty list, and the built-in variable
1254    nothing to be false values. Nearly every other value is true,
1255    including non-zero numbers, and strings with anything in them (even
1256    spaces!).
1258 **tal:repeat="variable expression"**
1259    Repeat this tag and its contents for each element of the sequence
1260    that the expression returns, defining a new local variable and a
1261    special "repeat" variable for each element. For example::
1263      <tr tal:repeat="u user/list">
1264       <td tal:content="u/id"></td>
1265       <td tal:content="u/username"></td>
1266       <td tal:content="u/realname"></td>
1267      </tr>
1269    The example would iterate over the sequence of users returned by
1270    "user/list" and define the local variable "u" for each entry.
1272 **tal:replace="expression"**
1273    Replace this tag with the result of the expression. For example::
1275     <span tal:replace="request/user/realname" />
1277    The example would replace the <span> tag and its contents with the
1278    user's realname. If the user's realname was "Bruce", then the
1279    resultant output would be "Bruce".
1281 **tal:content="expression"**
1282    Replace the contents of this tag with the result of the expression.
1283    For example::
1285     <span tal:content="request/user/realname">user's name appears here
1286     </span>
1288    The example would replace the contents of the <span> tag with the
1289    user's realname. If the user's realname was "Bruce" then the
1290    resultant output would be "<span>Bruce</span>".
1292 **tal:attributes="attribute expression; attribute expression; ..."**
1293    Set attributes on this tag to the results of expressions. For
1294    example::
1296      <a tal:attributes="href string:user${request/user/id}">My Details</a>
1298    In the example, the "href" attribute of the <a> tag is set to the
1299    value of the "string:user${request/user/id}" expression, which will
1300    be something like "user123".
1302 **tal:omit-tag="expression"**
1303    Remove this tag (but not its contents) if the expression is true. For
1304    example::
1306       <span tal:omit-tag="python:1">Hello, world!</span>
1308    would result in output of::
1310       Hello, world!
1312 Note that the commands on a given tag are evaulated in the order above,
1313 so *define* comes before *condition*, and so on.
1315 Additionally, you may include tags such as <tal:block>, which are
1316 removed from output. Its content is kept, but the tag itself is not (so
1317 don't go using any "tal:attributes" commands on it). This is useful for
1318 making arbitrary blocks of HTML conditional or repeatable (very handy
1319 for repeating multiple table rows, which would othewise require an
1320 illegal tag placement to effect the repeat).
1323 Templating Expressions
1324 ~~~~~~~~~~~~~~~~~~~~~~
1326 The expressions you may use in the attribute values may be one of the
1327 following forms:
1329 **Path Expressions** - eg. ``item/status/checklist``
1330    These are object attribute / item accesses. Roughly speaking, the
1331    path ``item/status/checklist`` is broken into parts ``item``,
1332    ``status`` and ``checklist``. The ``item`` part is the root of the
1333    expression. We then look for a ``status`` attribute on ``item``, or
1334    failing that, a ``status`` item (as in ``item['status']``). If that
1335    fails, the path expression fails. When we get to the end, the object
1336    we're left with is evaluated to get a string - if it is a method, it
1337    is called; if it is an object, it is stringified. Path expressions
1338    may have an optional ``path:`` prefix, but they are the default
1339    expression type, so it's not necessary.
1341    If an expression evaluates to ``default``, then the expression is
1342    "cancelled" - whatever HTML already exists in the template will
1343    remain (tag content in the case of ``tal:content``, attributes in the
1344    case of ``tal:attributes``).
1346    If an expression evaluates to ``nothing`` then the target of the
1347    expression is removed (tag content in the case of ``tal:content``,
1348    attributes in the case of ``tal:attributes`` and the tag itself in
1349    the case of ``tal:replace``).
1351    If an element in the path may not exist, then you can use the ``|``
1352    operator in the expression to provide an alternative. So, the
1353    expression ``request/form/foo/value | default`` would simply leave
1354    the current HTML in place if the "foo" form variable doesn't exist.
1356    You may use the python function ``path``, as in
1357    ``path("item/status")``, to embed path expressions in Python
1358    expressions.
1360 **String Expressions** - eg. ``string:hello ${user/name}`` 
1361    These expressions are simple string interpolations - though they can
1362    be just plain strings with no interpolation if you want. The
1363    expression in the ``${ ... }`` is just a path expression as above.
1365 **Python Expressions** - eg. ``python: 1+1`` 
1366    These expressions give the full power of Python. All the "root level"
1367    variables are available, so ``python:item.status.checklist()`` would
1368    be equivalent to ``item/status/checklist``, assuming that
1369    ``checklist`` is a method.
1371 Modifiers:
1373 **structure** - eg. ``structure python:msg.content.plain(hyperlink=1)``
1374    The result of expressions are normally *escaped* to be safe for HTML
1375    display (all "<", ">" and "&" are turned into special entities). The
1376    ``structure`` expression modifier turns off this escaping - the
1377    result of the expression is now assumed to be HTML, which is passed
1378    to the web browser for rendering.
1380 **not:** - eg. ``not:python:1=1``
1381    This simply inverts the logical true/false value of another
1382    expression.
1385 Template Macros
1386 ~~~~~~~~~~~~~~~
1388 Macros are used in Roundup to save us from repeating the same common
1389 page stuctures over and over. The most common (and probably only) macro
1390 you'll use is the "icing" macro defined in the "page" template.
1392 Macros are generated and used inside your templates using special
1393 attributes similar to the `basic templating actions`_. In this case,
1394 though, the attributes belong to the Macro Expansion Template Attribute
1395 Language, or METAL. The macro commands are:
1397 **metal:define-macro="macro name"**
1398   Define that the tag and its contents are now a macro that may be
1399   inserted into other templates using the *use-macro* command. For
1400   example::
1402     <html metal:define-macro="page">
1403      ...
1404     </html>
1406   defines a macro called "page" using the ``<html>`` tag and its
1407   contents. Once defined, macros are stored on the template they're
1408   defined on in the ``macros`` attribute. You can access them later on
1409   through the ``templates`` variable, eg. the most common
1410   ``templates/page/macros/icing`` to access the "page" macro of the
1411   "page" template.
1413 **metal:use-macro="path expression"**
1414   Use a macro, which is identified by the path expression (see above).
1415   This will replace the current tag with the identified macro contents.
1416   For example::
1418    <tal:block metal:use-macro="templates/page/macros/icing">
1419     ...
1420    </tal:block>
1422    will replace the tag and its contents with the "page" macro of the
1423    "page" template.
1425 **metal:define-slot="slot name"** and **metal:fill-slot="slot name"**
1426   To define *dynamic* parts of the macro, you define "slots" which may
1427   be filled when the macro is used with a *use-macro* command. For
1428   example, the ``templates/page/macros/icing`` macro defines a slot like
1429   so::
1431     <title metal:define-slot="head_title">title goes here</title>
1433   In your *use-macro* command, you may now use a *fill-slot* command
1434   like this::
1436     <title metal:fill-slot="head_title">My Title</title>
1438   where the tag that fills the slot completely replaces the one defined
1439   as the slot in the macro.
1441 Note that you may not mix METAL and TAL commands on the same tag, but
1442 TAL commands may be used freely inside METAL-using tags (so your
1443 *fill-slots* tags may have all manner of TAL inside them).
1446 Information available to templates
1447 ----------------------------------
1449 Note: this is implemented by
1450 ``roundup.cgi.templating.RoundupPageTemplate``
1452 The following variables are available to templates.
1454 **context**
1455   The current context. This is either None, a `hyperdb class wrapper`_
1456   or a `hyperdb item wrapper`_
1457 **request**
1458   Includes information about the current request, including:
1459    - the current index information (``filterspec``, ``filter`` args,
1460      ``properties``, etc) parsed out of the form. 
1461    - methods for easy filterspec link generation
1462    - *user*, the current user item as an HTMLItem instance
1463    - *form*
1464      The current CGI form information as a mapping of form argument name
1465      to value
1466 **config**
1467   This variable holds all the values defined in the tracker config.py
1468   file (eg. TRACKER_NAME, etc.)
1469 **db**
1470   The current database, used to access arbitrary database items.
1471 **templates**
1472   Access to all the tracker templates by name. Used mainly in
1473   *use-macro* commands.
1474 **utils**
1475   This variable makes available some utility functions like batching.
1476 **nothing**
1477   This is a special variable - if an expression evaluates to this, then
1478   the tag (in the case of a ``tal:replace``), its contents (in the case
1479   of ``tal:content``) or some attributes (in the case of
1480   ``tal:attributes``) will not appear in the the output. So, for
1481   example::
1483     <span tal:attributes="class nothing">Hello, World!</span>
1485   would result in::
1487     <span>Hello, World!</span>
1489 **default**
1490   Also a special variable - if an expression evaluates to this, then the
1491   existing HTML in the template will not be replaced or removed, it will
1492   remain. So::
1494     <span tal:replace="default">Hello, World!</span>
1496   would result in::
1498     <span>Hello, World!</span>
1501 The context variable
1502 ~~~~~~~~~~~~~~~~~~~~
1504 The *context* variable is one of three things based on the current
1505 context (see `determining web context`_ for how we figure this out):
1507 1. if we're looking at a "home" page, then it's None
1508 2. if we're looking at a specific hyperdb class, it's a
1509    `hyperdb class wrapper`_.
1510 3. if we're looking at a specific hyperdb item, it's a
1511    `hyperdb item wrapper`_.
1513 If the context is not None, we can access the properties of the class or
1514 item. The only real difference between cases 2 and 3 above are:
1516 1. the properties may have a real value behind them, and this will
1517    appear if the property is displayed through ``context/property`` or
1518    ``context/property/field``.
1519 2. the context's "id" property will be a false value in the second case,
1520    but a real, or true value in the third. Thus we can determine whether
1521    we're looking at a real item from the hyperdb by testing
1522    "context/id".
1524 Hyperdb class wrapper
1525 :::::::::::::::::::::
1527 Note: this is implemented by the ``roundup.cgi.templating.HTMLClass``
1528 class.
1530 This wrapper object provides access to a hyperb class. It is used
1531 primarily in both index view and new item views, but it's also usable
1532 anywhere else that you wish to access information about a class, or the
1533 items of a class, when you don't have a specific item of that class in
1534 mind.
1536 We allow access to properties. There will be no "id" property. The value
1537 accessed through the property will be the current value of the same name
1538 from the CGI form.
1540 There are several methods available on these wrapper objects:
1542 =========== =============================================================
1543 Method      Description
1544 =========== =============================================================
1545 properties  return a `hyperdb property wrapper`_ for all of this class's
1546             properties.
1547 list        lists all of the active (not retired) items in the class.
1548 csv         return the items of this class as a chunk of CSV text.
1549 propnames   lists the names of the properties of this class.
1550 filter      lists of items from this class, filtered and sorted by the
1551             current *request* filterspec/filter/sort/group args
1552 classhelp   display a link to a javascript popup containing this class'
1553             "help" template.
1554 submit      generate a submit button (and action hidden element)
1555 renderWith  render this class with the given template.
1556 history     returns 'New node - no history' :)
1557 is_edit_ok  is the user allowed to Edit the current class?
1558 is_view_ok  is the user allowed to View the current class?
1559 =========== =============================================================
1561 Note that if you have a property of the same name as one of the above
1562 methods, you'll need to access it using a python "item access"
1563 expression. For example::
1565    python:context['list']
1567 will access the "list" property, rather than the list method.
1570 Hyperdb item wrapper
1571 ::::::::::::::::::::
1573 Note: this is implemented by the ``roundup.cgi.templating.HTMLItem``
1574 class.
1576 This wrapper object provides access to a hyperb item.
1578 We allow access to properties. There will be no "id" property. The value
1579 accessed through the property will be the current value of the same name
1580 from the CGI form.
1582 There are several methods available on these wrapper objects:
1584 =============== ========================================================
1585 Method          Description
1586 =============== ========================================================
1587 submit          generate a submit button (and action hidden element)
1588 journal         return the journal of the current item (**not
1589                 implemented**)
1590 history         render the journal of the current item as HTML
1591 renderQueryForm specific to the "query" class - render the search form
1592                 for the query
1593 hasPermission   specific to the "user" class - determine whether the
1594                 user has a Permission
1595 is_edit_ok      is the user allowed to Edit the current item?
1596 is_view_ok      is the user allowed to View the current item?
1597 is_retired      is the item retired?
1598 download_url    generates a url-quoted link for download of FileClass
1599                 item contents (ie. file<id>/<name>)
1600 =============== ========================================================
1602 Note that if you have a property of the same name as one of the above
1603 methods, you'll need to access it using a python "item access"
1604 expression. For example::
1606    python:context['journal']
1608 will access the "journal" property, rather than the journal method.
1611 Hyperdb property wrapper
1612 ::::::::::::::::::::::::
1614 Note: this is implemented by subclasses of the
1615 ``roundup.cgi.templating.HTMLProperty`` class (``HTMLStringProperty``,
1616 ``HTMLNumberProperty``, and so on).
1618 This wrapper object provides access to a single property of a class. Its
1619 value may be either:
1621 1. if accessed through a `hyperdb item wrapper`_, then it's a value from
1622    the hyperdb
1623 2. if access through a `hyperdb class wrapper`_, then it's a value from
1624    the CGI form
1627 The property wrapper has some useful attributes:
1629 =============== ========================================================
1630 Attribute       Description
1631 =============== ========================================================
1632 _name           the name of the property
1633 _value          the value of the property if any - this is the actual
1634                 value retrieved from the hyperdb for this property
1635 =============== ========================================================
1637 There are several methods available on these wrapper objects:
1639 =========== ================================================================
1640 Method      Description
1641 =========== ================================================================
1642 plain       render a "plain" representation of the property. This method
1643             may take two arguments:
1645             escape
1646              If true, escape the text so it is HTML safe (default: no). The
1647              reason this defaults to off is that text is usually escaped
1648              at a later stage by the TAL commands, unless the "structure"
1649              option is used in the template. The following ``tal:content``
1650              expressions are all equivalent::
1651  
1652               "structure python:msg.content.plain(escape=1)"
1653               "python:msg.content.plain()"
1654               "msg/content/plain"
1655               "msg/content"
1657              Usually you'll only want to use the escape option in a
1658              complex expression.
1660             hyperlink
1661              If true, turn URLs, email addresses and hyperdb item
1662              designators in the text into hyperlinks (default: no). Note
1663              that you'll need to use the "structure" TAL option if you
1664              want to use this ``tal:content`` expression::
1665   
1666               "structure python:msg.content.plain(hyperlink=1)"
1668              Note also that the text is automatically HTML-escaped before
1669              the hyperlinking transformation.
1670 hyperlinked The same as msg.content.plain(hyperlink=1), but nicer::
1672               "structure msg/content/hyperlinked"
1674 field       render an appropriate form edit field for the property - for
1675             most types this is a text entry box, but for Booleans it's a
1676             tri-state yes/no/neither selection.
1677 stext       only on String properties - render the value of the property
1678             as StructuredText (requires the StructureText module to be
1679             installed separately)
1680 multiline   only on String properties - render a multiline form edit
1681             field for the property
1682 email       only on String properties - render the value of the property
1683             as an obscured email address
1684 confirm     only on Password properties - render a second form edit field
1685             for the property, used for confirmation that the user typed
1686             the password correctly. Generates a field with name
1687             "name:confirm".
1688 now         only on Date properties - return the current date as a new
1689             property
1690 reldate     only on Date properties - render the interval between the date
1691             and now
1692 local       only on Date properties - return this date as a new property
1693             with some timezone offset, for example::
1694             
1695                 python:context.creation.local(10)
1697             will render the date with a +10 hour offset.
1698 pretty      Date properties - render the date as "dd Mon YYYY" (eg. "19
1699             Mar 2004"). Takes an optional format argument, for example::
1701                 python:context.activity.pretty('%Y-%m-%d')
1703             Will format as "2004-03-19" instead.
1705             Interval properties - render the interval in a pretty
1706             format (eg. "yesterday")
1707 menu        only on Link and Multilink properties - render a form select
1708             list for this property
1709 reverse     only on Multilink properties - produce a list of the linked
1710             items in reverse order
1711 isset       returns True if the property has been set to a value
1712 =========== ================================================================
1714 All of the above functions perform checks for permissions required to
1715 display or edit the data they are manipulating. The simplest case is
1716 editing an issue title. Including the expression::
1718    context/title/field
1720 Will present the user with an edit field, if they have edit permission. If
1721 not, then they will be presented with a static display if they have view
1722 permission. If they don't even have view permission, then an error message
1723 is raised, preventing the display of the page, indicating that they don't
1724 have permission to view the information.
1727 The request variable
1728 ~~~~~~~~~~~~~~~~~~~~
1730 Note: this is implemented by the ``roundup.cgi.templating.HTMLRequest``
1731 class.
1733 The request variable is packed with information about the current
1734 request.
1736 .. taken from ``roundup.cgi.templating.HTMLRequest`` docstring
1738 =========== ============================================================
1739 Variable    Holds
1740 =========== ============================================================
1741 form        the CGI form as a cgi.FieldStorage
1742 env         the CGI environment variables
1743 base        the base URL for this tracker
1744 user        a HTMLUser instance for this user
1745 classname   the current classname (possibly None)
1746 template    the current template (suffix, also possibly None)
1747 form        the current CGI form variables in a FieldStorage
1748 =========== ============================================================
1750 **Index page specific variables (indexing arguments)**
1752 =========== ============================================================
1753 Variable    Holds
1754 =========== ============================================================
1755 columns     dictionary of the columns to display in an index page
1756 show        a convenience access to columns - request/show/colname will
1757             be true if the columns should be displayed, false otherwise
1758 sort        index sort column (direction, column name)
1759 group       index grouping property (direction, column name)
1760 filter      properties to filter the index on
1761 filterspec  values to filter the index on
1762 search_text text to perform a full-text search on for an index
1763 =========== ============================================================
1765 There are several methods available on the request variable:
1767 =============== ========================================================
1768 Method          Description
1769 =============== ========================================================
1770 description     render a description of the request - handle for the
1771                 page title
1772 indexargs_form  render the current index args as form elements
1773 indexargs_url   render the current index args as a URL
1774 base_javascript render some javascript that is used by other components
1775                 of the templating
1776 batch           run the current index args through a filter and return a
1777                 list of items (see `hyperdb item wrapper`_, and
1778                 `batching`_)
1779 =============== ========================================================
1781 The form variable
1782 :::::::::::::::::
1784 The form variable is a bit special because it's actually a python
1785 FieldStorage object. That means that you have two ways to access its
1786 contents. For example, to look up the CGI form value for the variable
1787 "name", use the path expression::
1789    request/form/name/value
1791 or the python expression::
1793    python:request.form['name'].value
1795 Note the "item" access used in the python case, and also note the
1796 explicit "value" attribute we have to access. That's because the form
1797 variables are stored as MiniFieldStorages. If there's more than one
1798 "name" value in the form, then the above will break since
1799 ``request/form/name`` is actually a *list* of MiniFieldStorages. So it's
1800 best to know beforehand what you're dealing with.
1803 The db variable
1804 ~~~~~~~~~~~~~~~
1806 Note: this is implemented by the ``roundup.cgi.templating.HTMLDatabase``
1807 class.
1809 Allows access to all hyperdb classes as attributes of this variable. If
1810 you want access to the "user" class, for example, you would use::
1812   db/user
1813   python:db.user
1815 Also, the current id of the current user is available as
1816 ``db.getuid()``. This isn't so useful in templates (where you have
1817 ``request/user``), but it can be useful in detectors or interfaces.
1819 The access results in a `hyperdb class wrapper`_.
1822 The templates variable
1823 ~~~~~~~~~~~~~~~~~~~~~~
1825 Note: this is implemented by the ``roundup.cgi.templating.Templates``
1826 class.
1828 This variable doesn't have any useful methods defined. It supports being
1829 used in expressions to access the templates, and consequently the
1830 template macros. You may access the templates using the following path
1831 expression::
1833    templates/name
1835 or the python expression::
1837    templates[name]
1839 where "name" is the name of the template you wish to access. The
1840 template has one useful attribute, namely "macros". To access a specific
1841 macro (called "macro_name"), use the path expression::
1843    templates/name/macros/macro_name
1845 or the python expression::
1847    templates[name].macros[macro_name]
1850 The utils variable
1851 ~~~~~~~~~~~~~~~~~~
1853 Note: this is implemented by the
1854 ``roundup.cgi.templating.TemplatingUtils`` class, but it may be extended
1855 as described below.
1857 =============== ========================================================
1858 Method          Description
1859 =============== ========================================================
1860 Batch           return a batch object using the supplied list
1861 url_quote       quote some text as safe for a URL (ie. space, %, ...)
1862 html_quote      quote some text as safe in HTML (ie. <, >, ...)
1863 =============== ========================================================
1865 You may add additional utility methods by writing them in your tracker
1866 ``interfaces.py`` module's ``TemplatingUtils`` class. See `adding a time
1867 log to your issues`_ for an example. The TemplatingUtils class itself
1868 will have a single attribute, ``client``, which may be used to access
1869 the ``client.db`` when you need to perform arbitrary database queries.
1871 Batching
1872 ::::::::
1874 Use Batch to turn a list of items, or item ids of a given class, into a
1875 series of batches. Its usage is::
1877     python:utils.Batch(sequence, size, start, end=0, orphan=0,
1878     overlap=0)
1880 or, to get the current index batch::
1882     request/batch
1884 The parameters are:
1886 ========= ==============================================================
1887 Parameter  Usage
1888 ========= ==============================================================
1889 sequence  a list of HTMLItems
1890 size      how big to make the sequence.
1891 start     where to start (0-indexed) in the sequence.
1892 end       where to end (0-indexed) in the sequence.
1893 orphan    if the next batch would contain less items than this value,
1894           then it is combined with this batch
1895 overlap   the number of items shared between adjacent batches
1896 ========= ==============================================================
1898 All of the parameters are assigned as attributes on the batch object. In
1899 addition, it has several more attributes:
1901 =============== ========================================================
1902 Attribute       Description
1903 =============== ========================================================
1904 start           indicates the start index of the batch. *Note: unlike
1905                 the argument, is a 1-based index (I know, lame)*
1906 first           indicates the start index of the batch *as a 0-based
1907                 index*
1908 length          the actual number of elements in the batch
1909 sequence_length the length of the original, unbatched, sequence.
1910 =============== ========================================================
1912 And several methods:
1914 =============== ========================================================
1915 Method          Description
1916 =============== ========================================================
1917 previous        returns a new Batch with the previous batch settings
1918 next            returns a new Batch with the next batch settings
1919 propchanged     detect if the named property changed on the current item
1920                 when compared to the last item
1921 =============== ========================================================
1923 An example of batching::
1925  <table class="otherinfo">
1926   <tr><th colspan="4" class="header">Existing Keywords</th></tr>
1927   <tr tal:define="keywords db/keyword/list"
1928       tal:repeat="start python:range(0, len(keywords), 4)">
1929    <td tal:define="batch python:utils.Batch(keywords, 4, start)"
1930        tal:repeat="keyword batch" tal:content="keyword/name">
1931        keyword here</td>
1932   </tr>
1933  </table>
1935 ... which will produce a table with four columns containing the items of
1936 the "keyword" class (well, their "name" anyway).
1938 Displaying Properties
1939 ---------------------
1941 Properties appear in the user interface in three contexts: in indices,
1942 in editors, and as search arguments. For each type of property, there
1943 are several display possibilities. For example, in an index view, a
1944 string property may just be printed as a plain string, but in an editor
1945 view, that property may be displayed in an editable field.
1948 Index Views
1949 -----------
1951 This is one of the class context views. It is also the default view for
1952 classes. The template used is "*classname*.index".
1955 Index View Specifiers
1956 ~~~~~~~~~~~~~~~~~~~~~
1958 An index view specifier (URL fragment) looks like this (whitespace has
1959 been added for clarity)::
1961      /issue?status=unread,in-progress,resolved&
1962             topic=security,ui&
1963             :group=+priority&
1964             :sort==activity&
1965             :filters=status,topic&
1966             :columns=title,status,fixer
1968 The index view is determined by two parts of the specifier: the layout
1969 part and the filter part. The layout part consists of the query
1970 parameters that begin with colons, and it determines the way that the
1971 properties of selected items are displayed. The filter part consists of
1972 all the other query parameters, and it determines the criteria by which
1973 items are selected for display. The filter part is interactively
1974 manipulated with the form widgets displayed in the filter section. The
1975 layout part is interactively manipulated by clicking on the column
1976 headings in the table.
1978 The filter part selects the union of the sets of items with values
1979 matching any specified Link properties and the intersection of the sets
1980 of items with values matching any specified Multilink properties.
1982 The example specifies an index of "issue" items. Only items with a
1983 "status" of either "unread" or "in-progress" or "resolved" are
1984 displayed, and only items with "topic" values including both "security"
1985 and "ui" are displayed. The items are grouped by priority, arranged in
1986 ascending order; and within groups, sorted by activity, arranged in
1987 descending order. The filter section shows filters for the "status" and
1988 "topic" properties, and the table includes columns for the "title",
1989 "status", and "fixer" properties.
1991 Searching Views
1992 ---------------
1994 Note: if you add a new column to the ``:columns`` form variable
1995       potentials then you will need to add the column to the appropriate
1996       `index views`_ template so that it is actually displayed.
1998 This is one of the class context views. The template used is typically
1999 "*classname*.search". The form on this page should have "search" as its
2000 ``@action`` variable. The "search" action:
2002 - sets up additional filtering, as well as performing indexed text
2003   searching
2004 - sets the ``:filter`` variable correctly
2005 - saves the query off if ``:query_name`` is set.
2007 The search page should lay out any fields that you wish to allow the
2008 user to search on. If your schema contains a large number of properties,
2009 you should be wary of making all of those properties available for
2010 searching, as this can cause confusion. If the additional properties are
2011 Strings, consider having their value indexed, and then they will be
2012 searchable using the full text indexed search. This is both faster, and
2013 more useful for the end user.
2015 The two special form values on search pages which are handled by the
2016 "search" action are:
2018 :search_text
2019   Text with which to perform a search of the text index. Results from
2020   that search will be used to limit the results of other filters (using
2021   an intersection operation)
2022 :query_name
2023   If supplied, the search parameters (including :search_text) will be
2024   saved off as a the query item and registered against the user's
2025   queries property. Note that the *classic* template schema has this
2026   ability, but the *minimal* template schema does not.
2029 Item Views
2030 ----------
2032 The basic view of a hyperdb item is provided by the "*classname*.item"
2033 template. It generally has three sections; an "editor", a "spool" and a
2034 "history" section.
2037 Editor Section
2038 ~~~~~~~~~~~~~~
2040 The editor section is used to manipulate the item - it may be a static
2041 display if the user doesn't have permission to edit the item.
2043 Here's an example of a basic editor template (this is the default
2044 "classic" template issue item edit form - from the "issue.item.html"
2045 template)::
2047  <table class="form">
2048  <tr>
2049   <th>Title</th>
2050   <td colspan="3" tal:content="structure python:context.title.field(size=60)">title</td>
2051  </tr>
2052  
2053  <tr>
2054   <th>Priority</th>
2055   <td tal:content="structure context/priority/menu">priority</td>
2056   <th>Status</th>
2057   <td tal:content="structure context/status/menu">status</td>
2058  </tr>
2059  
2060  <tr>
2061   <th>Superseder</th>
2062   <td>
2063    <span tal:replace="structure python:context.superseder.field(showid=1, size=20)" />
2064    <span tal:replace="structure python:db.issue.classhelp('id,title')" />
2065    <span tal:condition="context/superseder">
2066     <br>View: <span tal:replace="structure python:context.superseder.link(showid=1)" />
2067    </span>
2068   </td>
2069   <th>Nosy List</th>
2070   <td>
2071    <span tal:replace="structure context/nosy/field" />
2072    <span tal:replace="structure python:db.user.classhelp('username,realname,address,phone')" />
2073   </td>
2074  </tr>
2075  
2076  <tr>
2077   <th>Assigned To</th>
2078   <td tal:content="structure context/assignedto/menu">
2079    assignedto menu
2080   </td>
2081   <td>&nbsp;</td>
2082   <td>&nbsp;</td>
2083  </tr>
2084  
2085  <tr>
2086   <th>Change Note</th>
2087   <td colspan="3">
2088    <textarea name=":note" wrap="hard" rows="5" cols="60"></textarea>
2089   </td>
2090  </tr>
2091  
2092  <tr>
2093   <th>File</th>
2094   <td colspan="3"><input type="file" name=":file" size="40"></td>
2095  </tr>
2096  
2097  <tr>
2098   <td>&nbsp;</td>
2099   <td colspan="3" tal:content="structure context/submit">
2100    submit button will go here
2101   </td>
2102  </tr>
2103  </table>
2106 When a change is submitted, the system automatically generates a message
2107 describing the changed properties. As shown in the example, the editor
2108 template can use the ":note" and ":file" fields, which are added to the
2109 standard changenote message generated by Roundup.
2112 Form values
2113 :::::::::::
2115 We have a number of ways to pull properties out of the form in order to
2116 meet the various needs of:
2118 1. editing the current item (perhaps an issue item)
2119 2. editing information related to the current item (eg. messages or
2120    attached files)
2121 3. creating new information to be linked to the current item (eg. time
2122    spent on an issue)
2124 In the following, ``<bracketed>`` values are variable, ":" may be one of
2125 ":" or "@", and other text ("required") is fixed.
2127 Properties are specified as form variables:
2129 ``<propname>``
2130   property on the current context item
2132 ``<designator>:<propname>``
2133   property on the indicated item (for editing related information)
2135 ``<classname>-<N>:<propname>``
2136   property on the Nth new item of classname (generally for creating new
2137   items to attach to the current item)
2139 Once we have determined the "propname", we check to see if it is one of
2140 the special form values:
2142 ``@required``
2143   The named property values must be supplied or a ValueError will be
2144   raised.
2146 ``@remove@<propname>=id(s)``
2147   The ids will be removed from the multilink property.
2149 ``:add:<propname>=id(s)``
2150   The ids will be added to the multilink property.
2152 ``:link:<propname>=<designator>``
2153   Used to add a link to new items created during edit. These are
2154   collected and returned in ``all_links``. This will result in an
2155   additional linking operation (either Link set or Multilink append)
2156   after the edit/create is done using ``all_props`` in ``_editnodes``.
2157   The <propname> on the current item will be set/appended the id of the
2158   newly created item of class <designator> (where <designator> must be
2159   <classname>-<N>).
2161 Any of the form variables may be prefixed with a classname or
2162 designator.
2164 Two special form values are supported for backwards compatibility:
2166 ``:note``
2167   create a message (with content, author and date), linked to the
2168   context item. This is ALWAYS designated "msg-1".
2169 ``:file``
2170   create a file, attached to the current item and any message created by
2171   :note. This is ALWAYS designated "file-1".
2174 Spool Section
2175 ~~~~~~~~~~~~~
2177 The spool section lists related information like the messages and files
2178 of an issue.
2180 TODO
2183 History Section
2184 ~~~~~~~~~~~~~~~
2186 The final section displayed is the history of the item - its database
2187 journal. This is generally generated with the template::
2189  <tal:block tal:replace="structure context/history" />
2191 *To be done:*
2193 *The actual history entries of the item may be accessed for manual
2194 templating through the "journal" method of the item*::
2196  <tal:block tal:repeat="entry context/journal">
2197   a journal entry
2198  </tal:block>
2200 *where each journal entry is an HTMLJournalEntry.*
2202 Defining new web actions
2203 ------------------------
2205 You may define new actions to be triggered by the ``@action`` form variable.
2206 These are added to the tracker ``interfaces.py`` as ``Action`` classes that get
2207 called by the the ``Client`` class.
2209 Adding action classes takes three steps; first you `define the new
2210 action class`_, then you `register the action class`_ with the cgi
2211 interface so it may be triggered by the ``@action`` form variable.
2212 Finally you `use the new action`_ in your HTML form.
2214 See "`setting up a "wizard" (or "druid") for controlled adding of
2215 issues`_" for an example.
2218 Define the new action class
2219 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
2221 The action classes have the following interface::
2223  class MyAction(Action):
2224      def handle(self):
2225          ''' Perform some action. No return value is required.
2226          '''
2228 The *self.client* attribute is an instance of your tracker ``instance.Client``
2229 class - thus it's mostly implemented by ``roundup.cgi.client.Client``. See the
2230 docstring of that class for details of what it can do.
2232 The method will typically check the ``self.form`` variable's contents.
2233 It may then:
2235 - add information to ``self.client.ok_message`` or ``self.client.error_message``
2236 - change the ``self.client.template`` variable to alter what the user will see
2237   next
2238 - raise Unauthorised, SendStaticFile, SendFile, NotFound or Redirect
2239   exceptions (import them from roundup.cgi.exceptions)
2242 Register the action class
2243 ~~~~~~~~~~~~~~~~~~~~~~~~~~
2245 The class is now written, but isn't available to the user until you add it to
2246 the ``instance.Client`` class ``actions`` variable, like so::
2248     actions = client.Client.actions + (
2249         ('myaction', myActionClass),
2250     )
2252 This maps the action name "myaction" to the action class we defined.
2254 Use the new action
2255 ~~~~~~~~~~~~~~~~~~
2257 In your HTML form, add a hidden form element like so::
2259   <input type="hidden" name="@action" value="myaction">
2261 where "myaction" is the name you registered in the previous step.
2263 Actions may return content to the user
2264 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
2266 Actions generally perform some database manipulation and then pass control
2267 on to the rendering of a template in the current context (see `Determining
2268 web context`_ for how that works.) Some actions will want to generate the
2269 actual content returned to the user. Action methods may return their own
2270 content string to be displayed to the user, overriding the templating step.
2271 In this situation, we assume that the content is HTML by default. You may
2272 override the content type indicated to the user by calling ``setHeader``::
2274    self.client.setHeader('Content-Type', 'text/csv')
2276 This example indicates that the value sent back to the user is actually
2277 comma-separated value content (eg. something to be loaded into a
2278 spreadsheet or database).
2281 Examples
2282 ========
2284 .. contents::
2285    :local:
2286    :depth: 2
2289 Changing what's stored in the database
2290 --------------------------------------
2292 The following examples illustrate ways to change the information stored in
2293 the database.
2296 Adding a new field to the classic schema
2297 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
2299 This example shows how to add a new constrained property (i.e. a
2300 selection of distinct values) to your tracker.
2303 Introduction
2304 ::::::::::::
2306 To make the classic schema of roundup useful as a TODO tracking system
2307 for a group of systems administrators, it needed an extra data field per
2308 issue: a category.
2310 This would let sysadmins quickly list all TODOs in their particular area
2311 of interest without having to do complex queries, and without relying on
2312 the spelling capabilities of other sysadmins (a losing proposition at
2313 best).
2316 Adding a field to the database
2317 ::::::::::::::::::::::::::::::
2319 This is the easiest part of the change. The category would just be a
2320 plain string, nothing fancy. To change what is in the database you need
2321 to add some lines to the ``open()`` function in ``dbinit.py``. Under the
2322 comment::
2324     # add any additional database schema configuration here
2326 add::
2328     category = Class(db, "category", name=String())
2329     category.setkey("name")
2331 Here we are setting up a chunk of the database which we are calling
2332 "category". It contains a string, which we are refering to as "name" for
2333 lack of a more imaginative title. (Since "name" is one of the properties
2334 that Roundup looks for on items if you do not set a key for them, it's
2335 probably a good idea to stick with it for new classes if at all
2336 appropriate.) Then we are setting the key of this chunk of the database
2337 to be that "name". This is equivalent to an index for database types.
2338 This also means that there can only be one category with a given name.
2340 Adding the above lines allows us to create categories, but they're not
2341 tied to the issues that we are going to be creating. It's just a list of
2342 categories off on its own, which isn't much use. We need to link it in
2343 with the issues. To do that, find the lines in the ``open()`` function
2344 in ``dbinit.py`` which set up the "issue" class, and then add a link to
2345 the category::
2347     issue = IssueClass(db, "issue", ... ,
2348         category=Multilink("category"), ... )
2350 The ``Multilink()`` means that each issue can have many categories. If
2351 you were adding something with a one-to-one relationship to issues (such
2352 as the "assignedto" property), use ``Link()`` instead.
2354 That is all you need to do to change the schema. The rest of the effort
2355 is fiddling around so you can actually use the new category.
2358 Populating the new category class
2359 :::::::::::::::::::::::::::::::::
2361 If you haven't initialised the database with the roundup-admin
2362 "initialise" command, then you can add the following to the tracker
2363 ``dbinit.py`` in the ``init()`` function under the comment::
2365     # add any additional database create steps here - but only if you
2366     # haven't initialised the database with the admin "initialise" command
2368 Add::
2370      category = db.getclass('category')
2371      category.create(name="scipy", order="1")
2372      category.create(name="chaco", order="2")
2373      category.create(name="weave", order="3")
2375 If the database has already been initalised, then you need to use the
2376 ``roundup-admin`` tool::
2378      % roundup-admin -i <tracker home>
2379      Roundup <version> ready for input.
2380      Type "help" for help.
2381      roundup> create category name=scipy order=1
2382      1
2383      roundup> create category name=chaco order=1
2384      2
2385      roundup> create category name=weave order=1
2386      3
2387      roundup> exit...
2388      There are unsaved changes. Commit them (y/N)? y
2390 TODO: explain why order=1 in each case.
2393 Setting up security on the new objects
2394 ::::::::::::::::::::::::::::::::::::::
2396 By default only the admin user can look at and change objects. This
2397 doesn't suit us, as we want any user to be able to create new categories
2398 as required, and obviously everyone needs to be able to view the
2399 categories of issues for it to be useful.
2401 We therefore need to change the security of the category objects. This
2402 is also done in the ``open()`` function of ``dbinit.py``.
2404 There are currently two loops which set up permissions and then assign
2405 them to various roles. Simply add the new "category" to both lists::
2407     # new permissions for this schema
2408     for cl in 'issue', 'file', 'msg', 'user', 'category':
2409         db.security.addPermission(name="Edit", klass=cl,
2410             description="User is allowed to edit "+cl)
2411         db.security.addPermission(name="View", klass=cl,
2412             description="User is allowed to access "+cl)
2414     # Assign the access and edit permissions for issue, file and message
2415     # to regular users now
2416     for cl in 'issue', 'file', 'msg', 'category':
2417         p = db.security.getPermission('View', cl)
2418         db.security.addPermissionToRole('User', p)
2419         p = db.security.getPermission('Edit', cl)
2420         db.security.addPermissionToRole('User', p)
2422 So you are in effect doing the following (with 'cl' substituted by its
2423 value)::
2425     db.security.addPermission(name="Edit", klass='category',
2426         description="User is allowed to edit "+'category')
2427     db.security.addPermission(name="View", klass='category',
2428         description="User is allowed to access "+'category')
2430 which is creating two permission types; that of editing and viewing
2431 "category" objects respectively. Then the following lines assign those
2432 new permissions to the "User" role, so that normal users can view and
2433 edit "category" objects::
2435     p = db.security.getPermission('View', 'category')
2436     db.security.addPermissionToRole('User', p)
2438     p = db.security.getPermission('Edit', 'category')
2439     db.security.addPermissionToRole('User', p)
2441 This is all the work that needs to be done for the database. It will
2442 store categories, and let users view and edit them. Now on to the
2443 interface stuff.
2446 Changing the web left hand frame
2447 ::::::::::::::::::::::::::::::::
2449 We need to give the users the ability to create new categories, and the
2450 place to put the link to this functionality is in the left hand function
2451 bar, under the "Issues" area. The file that defines how this area looks
2452 is ``html/page``, which is what we are going to be editing next.
2454 If you look at this file you can see that it contains a lot of
2455 "classblock" sections which are chunks of HTML that will be included or
2456 excluded in the output depending on whether the condition in the
2457 classblock is met. Under the end of the classblock for issue is where we
2458 are going to add the category code::
2460   <p class="classblock"
2461      tal:condition="python:request.user.hasPermission('View', 'category')">
2462    <b>Categories</b><br>
2463    <a tal:condition="python:request.user.hasPermission('Edit', 'category')"
2464       href="category?@template=item">New Category<br></a>
2465   </p>
2467 The first two lines is the classblock definition, which sets up a
2468 condition that only users who have "View" permission for the "category"
2469 object will have this section included in their output. Next comes a
2470 plain "Categories" header in bold. Everyone who can view categories will
2471 get that.
2473 Next comes the link to the editing area of categories. This link will
2474 only appear if the condition - that the user has "Edit" permissions for
2475 the "category" objects - is matched. If they do have permission then
2476 they will get a link to another page which will let the user add new
2477 categories.
2479 Note that if you have permission to *view* but not to *edit* categories,
2480 then all you will see is a "Categories" header with nothing underneath
2481 it. This is obviously not very good interface design, but will do for
2482 now. I just claim that it is so I can add more links in this section
2483 later on. However to fix the problem you could change the condition in
2484 the classblock statement, so that only users with "Edit" permission
2485 would see the "Categories" stuff.
2488 Setting up a page to edit categories
2489 ::::::::::::::::::::::::::::::::::::
2491 We defined code in the previous section which let users with the
2492 appropriate permissions see a link to a page which would let them edit
2493 conditions. Now we have to write that page.
2495 The link was for the *item* template of the *category* object. This
2496 translates into Roundup looking for a file called ``category.item.html``
2497 in the ``html`` tracker directory. This is the file that we are going to
2498 write now.
2500 First we add an info tag in a comment which doesn't affect the outcome
2501 of the code at all, but is useful for debugging. If you load a page in a
2502 browser and look at the page source, you can see which sections come
2503 from which files by looking for these comments::
2505     <!-- category.item -->
2507 Next we need to add in the METAL macro stuff so we get the normal page
2508 trappings::
2510  <tal:block metal:use-macro="templates/page/macros/icing">
2511   <title metal:fill-slot="head_title">Category editing</title>
2512   <td class="page-header-top" metal:fill-slot="body_title">
2513    <h2>Category editing</h2>
2514   </td>
2515   <td class="content" metal:fill-slot="content">
2517 Next we need to setup up a standard HTML form, which is the whole
2518 purpose of this file. We link to some handy javascript which sends the
2519 form through only once. This is to stop users hitting the send button
2520 multiple times when they are impatient and thus having the form sent
2521 multiple times::
2523     <form method="POST" onSubmit="return submit_once()"
2524           enctype="multipart/form-data">
2526 Next we define some code which sets up the minimum list of fields that
2527 we require the user to enter. There will be only one field - "name" - so
2528 they better put something in it, otherwise the whole form is pointless::
2530     <input type="hidden" name="@required" value="name">
2532 To get everything to line up properly we will put everything in a table,
2533 and put a nice big header on it so the user has an idea what is
2534 happening::
2536     <table class="form">
2537      <tr><th class="header" colspan="2">Category</th></tr>
2539 Next, we need the field into which the user is going to enter the new
2540 category. The "context.name.field(size=60)" bit tells Roundup to
2541 generate a normal HTML field of size 60, and the contents of that field
2542 will be the "name" variable of the current context (which is
2543 "category"). The upshot of this is that when the user types something in
2544 to the form, a new category will be created with that name::
2546     <tr>
2547      <th>Name</th>
2548      <td tal:content="structure python:context.name.field(size=60)">
2549      name</td>
2550     </tr>
2552 Then a submit button so that the user can submit the new category::
2554     <tr>
2555      <td>&nbsp;</td>
2556      <td colspan="3" tal:content="structure context/submit">
2557       submit button will go here
2558      </td>
2559     </tr>
2561 Finally we finish off the tags we used at the start to do the METAL
2562 stuff::
2564   </td>
2565  </tal:block>
2567 So putting it all together, and closing the table and form we get::
2569  <!-- category.item -->
2570  <tal:block metal:use-macro="templates/page/macros/icing">
2571   <title metal:fill-slot="head_title">Category editing</title>
2572   <td class="page-header-top" metal:fill-slot="body_title">
2573    <h2>Category editing</h2>
2574   </td>
2575   <td class="content" metal:fill-slot="content">
2576    <form method="POST" onSubmit="return submit_once()"
2577          enctype="multipart/form-data">
2579     <table class="form">
2580      <tr><th class="header" colspan="2">Category</th></tr>
2582      <tr>
2583       <th>Name</th>
2584       <td tal:content="structure python:context.name.field(size=60)">
2585       name</td>
2586      </tr>
2588      <tr>
2589       <td>
2590         &nbsp;
2591         <input type="hidden" name="@required" value="name"> 
2592       </td>
2593       <td colspan="3" tal:content="structure context/submit">
2594        submit button will go here
2595       </td>
2596      </tr>
2597     </table>
2598    </form>
2599   </td>
2600  </tal:block>
2602 This is quite a lot to just ask the user one simple question, but there
2603 is a lot of setup for basically one line (the form line) to do its work.
2604 To add another field to "category" would involve one more line (well,
2605 maybe a few extra to get the formatting correct).
2608 Adding the category to the issue
2609 ::::::::::::::::::::::::::::::::
2611 We now have the ability to create issues to our heart's content, but
2612 that is pointless unless we can assign categories to issues.  Just like
2613 the ``html/category.item.html`` file was used to define how to add a new
2614 category, the ``html/issue.item.html`` is used to define how a new issue
2615 is created.
2617 Just like ``category.issue.html`` this file defines a form which has a
2618 table to lay things out. It doesn't matter where in the table we add new
2619 stuff, it is entirely up to your sense of aesthetics::
2621    <th>Category</th>
2622    <td><span tal:replace="structure context/category/field" />
2623        <span tal:replace="structure db/category/classhelp" />
2624    </td>
2626 First, we define a nice header so that the user knows what the next
2627 section is, then the middle line does what we are most interested in.
2628 This ``context/category/field`` gets replaced by a field which contains
2629 the category in the current context (the current context being the new
2630 issue).
2632 The classhelp lines generate a link (labelled "list") to a popup window
2633 which contains the list of currently known categories.
2636 Searching on categories
2637 :::::::::::::::::::::::
2639 We can add categories, and create issues with categories. The next
2640 obvious thing that we would like to be able to do, would be to search
2641 for issues based on their category, so that, for example, anyone working
2642 on the web server could look at all issues in the category "Web".
2644 If you look for "Search Issues" in the 'html/page.html' file, you will
2645 find that it looks something like 
2646 ``<a href="issue?@template=search">Search Issues</a>``. This shows us
2647 that when you click on "Search Issues" it will be looking for a
2648 ``issue.search.html`` file to display. So that is the file that we will
2649 change.
2651 If you look at this file it should be starting to seem familiar, although it
2652 does use some new macros. You can add the new category search code anywhere you
2653 like within that form::
2655   <tr tal:define="name string:category;
2656                   db_klass string:category;
2657                   db_content string:name;">
2658     <th>Priority:</th>
2659     <td metal:use-macro="search_select"></td>
2660     <td metal:use-macro="column_input"></td>
2661     <td metal:use-macro="sort_input"></td>
2662     <td metal:use-macro="group_input"></td>
2663   </tr>
2665 The definitions in the <tr> opening tag are used by the macros:
2667 - search_select expands to a drop-down box with all categories using db_klass
2668   and db_content.
2669 - column_input expands to a checkbox for selecting what columns should be
2670   displayed.
2671 - sort_input expands to a radio button for selecting what property should be
2672   sorted on.
2673 - group_input expands to a radio button for selecting what property should be
2674   group on.
2676 The category search code above would expand to the following::
2678   <tr>
2679     <th>Category:</th>
2680     <td>
2681       <select name="category">
2682         <option value="">don't care</option>
2683         <option value="">------------</option>      
2684         <option value="1">scipy</option>
2685         <option value="2">chaco</option>
2686         <option value="3">weave</option>
2687       </select>
2688     </td>
2689     <td><input type="checkbox" name=":columns" value="category"></td>
2690     <td><input type="radio" name=":sort" value="category"></td>
2691     <td><input type="radio" name=":group" value="category"></td>
2692   </tr>
2694 Adding category to the default view
2695 :::::::::::::::::::::::::::::::::::
2697 We can now add categories, add issues with categories, and search for
2698 issues based on categories. This is everything that we need to do;
2699 however, there is some more icing that we would like. I think the
2700 category of an issue is important enough that it should be displayed by
2701 default when listing all the issues.
2703 Unfortunately, this is a bit less obvious than the previous steps. The
2704 code defining how the issues look is in ``html/issue.index.html``. This
2705 is a large table with a form down at the bottom for redisplaying and so
2706 forth. 
2708 Firstly we need to add an appropriate header to the start of the table::
2710     <th tal:condition="request/show/category">Category</th>
2712 The *condition* part of this statement is to avoid displaying the
2713 Category column if the user has selected not to see it.
2715 The rest of the table is a loop which will go through every issue that
2716 matches the display criteria. The loop variable is "i" - which means
2717 that every issue gets assigned to "i" in turn.
2719 The new part of code to display the category will look like this::
2721     <td tal:condition="request/show/category"
2722         tal:content="i/category"></td>
2724 The condition is the same as above: only display the condition when the
2725 user hasn't asked for it to be hidden. The next part is to set the
2726 content of the cell to be the category part of "i" - the current issue.
2728 Finally we have to edit ``html/page.html`` again. This time, we need to
2729 tell it that when the user clicks on "Unasigned Issues" or "All Issues",
2730 the category column should be included in the resulting list. If you
2731 scroll down the page file, you can see the links with lots of options.
2732 The option that we are interested in is the ``:columns=`` one which
2733 tells roundup which fields of the issue to display. Simply add
2734 "category" to that list and it all should work.
2736 Adding a time log to your issues
2737 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
2739 We want to log the dates and amount of time spent working on issues, and
2740 be able to give a summary of the total time spent on a particular issue.
2742 1. Add a new class to your tracker ``dbinit.py``::
2744     # storage for time logging
2745     timelog = Class(db, "timelog", period=Interval())
2747    Note that we automatically get the date of the time log entry
2748    creation through the standard property "creation".
2750 2. Link to the new class from your issue class (again, in
2751    ``dbinit.py``)::
2753     issue = IssueClass(db, "issue", 
2754                     assignedto=Link("user"), topic=Multilink("keyword"),
2755                     priority=Link("priority"), status=Link("status"),
2756                     times=Multilink("timelog"))
2758    the "times" property is the new link to the "timelog" class.
2760 3. We'll need to let people add in times to the issue, so in the web
2761    interface we'll have a new entry field. This is a special field
2762    because unlike the other fields in the issue.item template, it
2763    affects a different item (a timelog item) and not the template's
2764    item, an issue. We have a special syntax for form fields that affect
2765    items other than the template default item (see the cgi 
2766    documentation on `special form variables`_). In particular, we add a
2767    field to capture a new timelog item's perdiod::
2769     <tr> 
2770      <th>Time Log</th> 
2771      <td colspan=3><input type="text" name="timelog-1@period" /> 
2772       <br />(enter as '3y 1m 4d 2:40:02' or parts thereof) 
2773      </td> 
2774     </tr> 
2775          
2776    and another hidden field that links that new timelog item (new
2777    because it's marked as having id "-1") to the issue item. It looks
2778    like this::
2780      <input type="hidden" name="@link@times" value="timelog-1" />
2782    On submission, the "-1" timelog item will be created and assigned a
2783    real item id. The "times" property of the issue will have the new id
2784    added to it.
2786 4. We want to display a total of the time log times that have been
2787    accumulated for an issue. To do this, we'll need to actually write
2788    some Python code, since it's beyond the scope of PageTemplates to
2789    perform such calculations. We do this by adding a method to the
2790    TemplatingUtils class in our tracker ``interfaces.py`` module::
2792     class TemplatingUtils:
2793         ''' Methods implemented on this class will be available to HTML
2794             templates through the 'utils' variable.
2795         '''
2796         def totalTimeSpent(self, times):
2797             ''' Call me with a list of timelog items (which have an
2798                 Interval "period" property)
2799             '''
2800             total = Interval('0d')
2801             for time in times:
2802                 total += time.period._value
2803             return total
2805    Replace the ``pass`` line if one appears in your TemplatingUtils
2806    class. As indicated in the docstrings, we will be able to access the
2807    ``totalTimeSpent`` method via the ``utils`` variable in our templates.
2809 5. Display the time log for an issue::
2811      <table class="otherinfo" tal:condition="context/times">
2812       <tr><th colspan="3" class="header">Time Log
2813        <tal:block
2814             tal:replace="python:utils.totalTimeSpent(context.times)" />
2815       </th></tr>
2816       <tr><th>Date</th><th>Period</th><th>Logged By</th></tr>
2817       <tr tal:repeat="time context/times">
2818        <td tal:content="time/creation"></td>
2819        <td tal:content="time/period"></td>
2820        <td tal:content="time/creator"></td>
2821       </tr>
2822      </table>
2824    I put this just above the Messages log in my issue display. Note our
2825    use of the ``totalTimeSpent`` method which will total up the times
2826    for the issue and return a new Interval. That will be automatically
2827    displayed in the template as text like "+ 1y 2:40" (1 year, 2 hours
2828    and 40 minutes).
2830 8. If you're using a persistent web server - roundup-server or
2831    mod_python for example - then you'll need to restart that to pick up
2832    the code changes. When that's done, you'll be able to use the new
2833    time logging interface.
2836 Tracking different types of issues
2837 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
2839 Sometimes you will want to track different types of issues - developer,
2840 customer support, systems, sales leads, etc. A single Roundup tracker is
2841 able to support multiple types of issues. This example demonstrates adding
2842 a customer support issue class to a tracker.
2844 1. Figure out what information you're going to want to capture. OK, so
2845    this is obvious, but sometimes it's better to actually sit down for a
2846    while and think about the schema you're going to implement.
2848 2. Add the new issue class to your tracker's ``dbinit.py`` - in this
2849    example, we're adding a "system support" class. Just after the "issue"
2850    class definition in the "open" function, add::
2852     support = IssueClass(db, "support", 
2853                     assignedto=Link("user"), topic=Multilink("keyword"),
2854                     status=Link("status"), deadline=Date(),
2855                     affects=Multilink("system"))
2857 3. Copy the existing "issue.*" (item, search and index) templates in the
2858    tracker's "html" to "support.*". Edit them so they use the properties
2859    defined in the "support" class. Be sure to check for hidden form
2860    variables like "required" to make sure they have the correct set of
2861    required properties.
2863 4. Edit the modules in the "detectors", adding lines to their "init"
2864    functions where appropriate. Look for "audit" and "react" registrations
2865    on the "issue" class, and duplicate them for "support".
2867 5. Create a new sidebar box for the new support class. Duplicate the
2868    existing issues one, changing the "issue" class name to "support".
2870 6. Re-start your tracker and start using the new "support" class.
2873 Optionally, you might want to restrict the users able to access this new
2874 class to just the users with a new "SysAdmin" Role. To do this, we add
2875 some security declarations::
2877     p = db.security.getPermission('View', 'support')
2878     db.security.addPermissionToRole('SysAdmin', p)
2879     p = db.security.getPermission('Edit', 'support')
2880     db.security.addPermissionToRole('SysAdmin', p)
2882 You would then (as an "admin" user) edit the details of the appropriate
2883 users, and add "SysAdmin" to their Roles list.
2885 Alternatively, you might want to change the Edit/View permissions granted
2886 for the "issue" class so that it's only available to users with the "System"
2887 or "Developer" Role, and then the new class you're adding is available to
2888 all with the "User" Role.
2891 Using External User Databases
2892 -----------------------------
2894 Using an external password validation source
2895 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
2897 We have a centrally-managed password changing system for our users. This
2898 results in a UN*X passwd-style file that we use for verification of
2899 users. Entries in the file consist of ``name:password`` where the
2900 password is encrypted using the standard UN*X ``crypt()`` function (see
2901 the ``crypt`` module in your Python distribution). An example entry
2902 would be::
2904     admin:aamrgyQfDFSHw
2906 Each user of Roundup must still have their information stored in the Roundup
2907 database - we just use the passwd file to check their password. To do this, we
2908 need to override the standard ``verifyPassword`` method defined in
2909 ``roundup.cgi.actions.LoginAction`` and register the new class with our
2910 ``Client`` class in the tracker home ``interfaces.py`` module::
2912     from roundup.cgi.actions import LoginAction    
2914     class ExternalPasswordLoginAction(LoginAction):
2915         def verifyPassword(self, userid, password):
2916             # get the user's username
2917             username = self.db.user.get(userid, 'username')
2919             # the passwords are stored in the "passwd.txt" file in the
2920             # tracker home
2921             file = os.path.join(self.db.config.TRACKER_HOME, 'passwd.txt')
2923             # see if we can find a match
2924             for ent in [line.strip().split(':') for line in
2925                                                 open(file).readlines()]:
2926                 if ent[0] == username:
2927                     return crypt.crypt(password, ent[1][:2]) == ent[1]
2929             # user doesn't exist in the file
2930             return 0
2932     class Client(client.Client):
2933         actions = client.Client.actions + (
2934             ('login', ExternalPasswordLoginAction)
2935         )
2937 What this does is look through the file, line by line, looking for a
2938 name that matches.
2940 We also remove the redundant password fields from the ``user.item``
2941 template.
2944 Using a UN*X passwd file as the user database
2945 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
2947 On some systems the primary store of users is the UN*X passwd file. It
2948 holds information on users such as their username, real name, password
2949 and primary user group.
2951 Roundup can use this store as its primary source of user information,
2952 but it needs additional information too - email address(es), roundup
2953 Roles, vacation flags, roundup hyperdb item ids, etc. Also, "retired"
2954 users must still exist in the user database, unlike some passwd files in
2955 which the users are removed when they no longer have access to a system.
2957 To make use of the passwd file, we therefore synchronise between the two
2958 user stores. We also use the passwd file to validate the user logins, as
2959 described in the previous example, `using an external password
2960 validation source`_. We keep the users lists in sync using a fairly
2961 simple script that runs once a day, or several times an hour if more
2962 immediate access is needed. In short, it:
2964 1. parses the passwd file, finding usernames, passwords and real names,
2965 2. compares that list to the current roundup user list:
2967    a. entries no longer in the passwd file are *retired*
2968    b. entries with mismatching real names are *updated*
2969    c. entries only exist in the passwd file are *created*
2971 3. send an email to administrators to let them know what's been done.
2973 The retiring and updating are simple operations, requiring only a call
2974 to ``retire()`` or ``set()``. The creation operation requires more
2975 information though - the user's email address and their roundup Roles.
2976 We're going to assume that the user's email address is the same as their
2977 login name, so we just append the domain name to that. The Roles are
2978 determined using the passwd group identifier - mapping their UN*X group
2979 to an appropriate set of Roles.
2981 The script to perform all this, broken up into its main components, is
2982 as follows. Firstly, we import the necessary modules and open the
2983 tracker we're to work on::
2985     import sys, os, smtplib
2986     from roundup import instance, date
2988     # open the tracker
2989     tracker_home = sys.argv[1]
2990     tracker = instance.open(tracker_home)
2992 Next we read in the *passwd* file from the tracker home::
2994     # read in the users
2995     file = os.path.join(tracker_home, 'users.passwd')
2996     users = [x.strip().split(':') for x in open(file).readlines()]
2998 Handle special users (those to ignore in the file, and those who don't
2999 appear in the file)::
3001     # users to not keep ever, pre-load with the users I know aren't
3002     # "real" users
3003     ignore = ['ekmmon', 'bfast', 'csrmail']
3005     # users to keep - pre-load with the roundup-specific users
3006     keep = ['comment_pool', 'network_pool', 'admin', 'dev-team',
3007             'cs_pool', 'anonymous', 'system_pool', 'automated']
3009 Now we map the UN*X group numbers to the Roles that users should have::
3011     roles = {
3012      '501': 'User,Tech',  # tech
3013      '502': 'User',       # finance
3014      '503': 'User,CSR',   # customer service reps
3015      '504': 'User',       # sales
3016      '505': 'User',       # marketing
3017     }
3019 Now we do all the work. Note that the body of the script (where we have
3020 the tracker database open) is wrapped in a ``try`` / ``finally`` clause,
3021 so that we always close the database cleanly when we're finished. So, we
3022 now do all the work::
3024     # open the database
3025     db = tracker.open('admin')
3026     try:
3027         # store away messages to send to the tracker admins
3028         msg = []
3030         # loop over the users list read in from the passwd file
3031         for user,passw,uid,gid,real,home,shell in users:
3032             if user in ignore:
3033                 # this user shouldn't appear in our tracker
3034                 continue
3035             keep.append(user)
3036             try:
3037                 # see if the user exists in the tracker
3038                 uid = db.user.lookup(user)
3040                 # yes, they do - now check the real name for correctness
3041                 if real != db.user.get(uid, 'realname'):
3042                     db.user.set(uid, realname=real)
3043                     msg.append('FIX %s - %s'%(user, real))
3044             except KeyError:
3045                 # nope, the user doesn't exist
3046                 db.user.create(username=user, realname=real,
3047                     address='%s@ekit-inc.com'%user, roles=roles[gid])
3048                 msg.append('ADD %s - %s (%s)'%(user, real, roles[gid]))
3050         # now check that all the users in the tracker are also in our
3051         # "keep" list - retire those who aren't
3052         for uid in db.user.list():
3053             user = db.user.get(uid, 'username')
3054             if user not in keep:
3055                 db.user.retire(uid)
3056                 msg.append('RET %s'%user)
3058         # if we did work, then send email to the tracker admins
3059         if msg:
3060             # create the email
3061             msg = '''Subject: %s user database maintenance
3063             %s
3064             '''%(db.config.TRACKER_NAME, '\n'.join(msg))
3066             # send the email
3067             smtp = smtplib.SMTP(db.config.MAILHOST)
3068             addr = db.config.ADMIN_EMAIL
3069             smtp.sendmail(addr, addr, msg)
3071         # now we're done - commit the changes
3072         db.commit()
3073     finally:
3074         # always close the database cleanly
3075         db.close()
3077 And that's it!
3080 Using an LDAP database for user information
3081 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
3083 A script that reads users from an LDAP store using
3084 http://python-ldap.sf.net/ and then compares the list to the users in the
3085 roundup user database would be pretty easy to write. You'd then have it run
3086 once an hour / day (or on demand if you can work that into your LDAP store
3087 workflow). See the example `Using a UN*X passwd file as the user database`_
3088 for more information about doing this.
3090 To authenticate off the LDAP store (rather than using the passwords in the
3091 roundup user database) you'd use the same python-ldap module inside an
3092 extension to the cgi interface. You'd do this by overriding the method called
3093 "verifyPassword" on the LoginAction class in your tracker's interfaces.py
3094 module (see `using an external password validation source`_). The method is
3095 implemented by default as::
3097     def verifyPassword(self, userid, password):
3098         ''' Verify the password that the user has supplied
3099         '''
3100         stored = self.db.user.get(self.userid, 'password')
3101         if password == stored:
3102             return 1
3103         if not password and not stored:
3104             return 1
3105         return 0
3107 So you could reimplement this as something like::
3109     def verifyPassword(self, userid, password):
3110         ''' Verify the password that the user has supplied
3111         '''
3112         # look up some unique LDAP information about the user
3113         username = self.db.user.get(self.userid, 'username')
3114         # now verify the password supplied against the LDAP store
3117 Changes to Tracker Behaviour
3118 ----------------------------
3120 Stop "nosy" messages going to people on vacation
3121 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
3123 When users go on vacation and set up vacation email bouncing, you'll
3124 start to see a lot of messages come back through Roundup "Fred is on
3125 vacation". Not very useful, and relatively easy to stop.
3127 1. add a "vacation" flag to your users::
3129          user = Class(db, "user",
3130                     username=String(),   password=Password(),
3131                     address=String(),    realname=String(),
3132                     phone=String(),      organisation=String(),
3133                     alternate_addresses=String(),
3134                     roles=String(), queries=Multilink("query"),
3135                     vacation=Boolean())
3137 2. So that users may edit the vacation flags, add something like the
3138    following to your ``user.item`` template::
3140      <tr>
3141       <th>On Vacation</th> 
3142       <td tal:content="structure context/vacation/field">vacation</td> 
3143      </tr> 
3145 3. edit your detector ``nosyreactor.py`` so that the ``nosyreaction()``
3146    consists of::
3148     def nosyreaction(db, cl, nodeid, oldvalues):
3149         users = db.user
3150         messages = db.msg
3151         # send a copy of all new messages to the nosy list
3152         for msgid in determineNewMessages(cl, nodeid, oldvalues):
3153             try:
3154                 # figure the recipient ids
3155                 sendto = []
3156                 seen_message = {}
3157                 recipients = messages.get(msgid, 'recipients')
3158                 for recipid in messages.get(msgid, 'recipients'):
3159                     seen_message[recipid] = 1
3161                 # figure the author's id, and indicate they've received
3162                 # the message
3163                 authid = messages.get(msgid, 'author')
3165                 # possibly send the message to the author, as long as
3166                 # they aren't anonymous
3167                 if (db.config.MESSAGES_TO_AUTHOR == 'yes' and
3168                         users.get(authid, 'username') != 'anonymous'):
3169                     sendto.append(authid)
3170                 seen_message[authid] = 1
3172                 # now figure the nosy people who weren't recipients
3173                 nosy = cl.get(nodeid, 'nosy')
3174                 for nosyid in nosy:
3175                     # Don't send nosy mail to the anonymous user (that
3176                     # user shouldn't appear in the nosy list, but just
3177                     # in case they do...)
3178                     if users.get(nosyid, 'username') == 'anonymous':
3179                         continue
3180                     # make sure they haven't seen the message already
3181                     if not seen_message.has_key(nosyid):
3182                         # send it to them
3183                         sendto.append(nosyid)
3184                         recipients.append(nosyid)
3186                 # generate a change note
3187                 if oldvalues:
3188                     note = cl.generateChangeNote(nodeid, oldvalues)
3189                 else:
3190                     note = cl.generateCreateNote(nodeid)
3192                 # we have new recipients
3193                 if sendto:
3194                     # filter out the people on vacation
3195                     sendto = [i for i in sendto 
3196                               if not users.get(i, 'vacation', 0)]
3198                     # map userids to addresses
3199                     sendto = [users.get(i, 'address') for i in sendto]
3201                     # update the message's recipients list
3202                     messages.set(msgid, recipients=recipients)
3204                     # send the message
3205                     cl.send_message(nodeid, msgid, note, sendto)
3206             except roundupdb.MessageSendError, message:
3207                 raise roundupdb.DetectorError, message
3209    Note that this is the standard nosy reaction code, with the small
3210    addition of::
3212     # filter out the people on vacation
3213     sendto = [i for i in sendto if not users.get(i, 'vacation', 0)]
3215    which filters out the users that have the vacation flag set to true.
3217 Adding in state transition control
3218 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
3220 Sometimes tracker admins want to control the states that users may move
3221 issues to. You can do this by following these steps:
3223 1. make "status" a required variable. This is achieved by adding the
3224    following to the top of the form in the ``issue.item.html``
3225    template::
3227      <input type="hidden" name="@required" value="status">
3229    this will force users to select a status.
3231 2. add a Multilink property to the status class::
3233      stat = Class(db, "status", ... , transitions=Multilink('status'),
3234                   ...)
3236    and then edit the statuses already created, either:
3238    a. through the web using the class list -> status class editor, or
3239    b. using the roundup-admin "set" command.
3241 3. add an auditor module ``checktransition.py`` in your tracker's
3242    ``detectors`` directory, for example::
3244      def checktransition(db, cl, nodeid, newvalues):
3245          ''' Check that the desired transition is valid for the "status"
3246              property.
3247          '''
3248          if not newvalues.has_key('status'):
3249              return
3250          current = cl.get(nodeid, 'status')
3251          new = newvalues['status']
3252          if new == current:
3253              return
3254          ok = db.status.get(current, 'transitions')
3255          if new not in ok:
3256              raise ValueError, 'Status not allowed to move from "%s" to "%s"'%(
3257                  db.status.get(current, 'name'), db.status.get(new, 'name'))
3259      def init(db):
3260          db.issue.audit('set', checktransition)
3262 4. in the ``issue.item.html`` template, change the status editing bit
3263    from::
3265     <th>Status</th>
3266     <td tal:content="structure context/status/menu">status</td>
3268    to::
3270     <th>Status</th>
3271     <td>
3272      <select tal:condition="context/id" name="status">
3273       <tal:block tal:define="ok context/status/transitions"
3274                  tal:repeat="state db/status/list">
3275        <option tal:condition="python:state.id in ok"
3276                tal:attributes="
3277                     value state/id;
3278                     selected python:state.id == context.status.id"
3279                tal:content="state/name"></option>
3280       </tal:block>
3281      </select>
3282      <tal:block tal:condition="not:context/id"
3283                 tal:replace="structure context/status/menu" />
3284     </td>
3286    which displays only the allowed status to transition to.
3289 Blocking issues that depend on other issues
3290 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
3292 We needed the ability to mark certain issues as "blockers" - that is,
3293 they can't be resolved until another issue (the blocker) they rely on is
3294 resolved. To achieve this:
3296 1. Create a new property on the issue Class,
3297    ``blockers=Multilink("issue")``. Edit your tracker's dbinit.py file.
3298    Where the "issue" class is defined, something like::
3300     issue = IssueClass(db, "issue", 
3301                     assignedto=Link("user"), topic=Multilink("keyword"),
3302                     priority=Link("priority"), status=Link("status"))
3304    add the blockers entry like so::
3306     issue = IssueClass(db, "issue", 
3307                     blockers=Multilink("issue"),
3308                     assignedto=Link("user"), topic=Multilink("keyword"),
3309                     priority=Link("priority"), status=Link("status"))
3311 2. Add the new "blockers" property to the issue.item edit page, using
3312    something like::
3314     <th>Waiting On</th>
3315     <td>
3316      <span tal:replace="structure python:context.blockers.field(showid=1,
3317                                   size=20)" />
3318      <span tal:replace="structure python:db.issue.classhelp('id,title')" />
3319      <span tal:condition="context/blockers"
3320            tal:repeat="blk context/blockers">
3321       <br>View: <a tal:attributes="href string:issue${blk/id}"
3322                    tal:content="blk/id"></a>
3323      </span>
3325    You'll need to fiddle with your item page layout to find an
3326    appropriate place to put it - I'll leave that fun part up to you.
3327    Just make sure it appears in the first table, possibly somewhere near
3328    the "superseders" field.
3330 3. Create a new detector module (attached) which enforces the rules:
3332    - issues may not be resolved if they have blockers
3333    - when a blocker is resolved, it's removed from issues it blocks
3335    The contents of the detector should be something like this::
3337     def blockresolution(db, cl, nodeid, newvalues):
3338         ''' If the issue has blockers, don't allow it to be resolved.
3339         '''
3340         if nodeid is None:
3341             blockers = []
3342         else:
3343             blockers = cl.get(nodeid, 'blockers')
3344         blockers = newvalues.get('blockers', blockers)
3346         # don't do anything if there's no blockers or the status hasn't
3347         # changed
3348         if not blockers or not newvalues.has_key('status'):
3349             return
3351         # get the resolved state ID
3352         resolved_id = db.status.lookup('resolved')
3354         # format the info
3355         u = db.config.TRACKER_WEB
3356         s = ', '.join(['<a href="%sissue%s">%s</a>'%(
3357                         u,id,id) for id in blockers])
3358         if len(blockers) == 1:
3359             s = 'issue %s is'%s
3360         else:
3361             s = 'issues %s are'%s
3363         # ok, see if we're trying to resolve
3364         if newvalues['status'] == resolved_id:
3365             raise ValueError, "This issue can't be resolved until %s resolved."%s
3367     def resolveblockers(db, cl, nodeid, newvalues):
3368         ''' When we resolve an issue that's a blocker, remove it from the
3369             blockers list of the issue(s) it blocks.
3370         '''
3371         if not newvalues.has_key('status'):
3372             return
3374         # get the resolved state ID
3375         resolved_id = db.status.lookup('resolved')
3377         # interesting?
3378         if newvalues['status'] != resolved_id:
3379             return
3381         # yes - find all the blocked issues, if any, and remove me from
3382         # their blockers list
3383         issues = cl.find(blockers=nodeid)
3384         for issueid in issues:
3385             blockers = cl.get(issueid, 'blockers')
3386             if nodeid in blockers:
3387                 blockers.remove(nodeid)
3388                 cl.set(issueid, blockers=blockers)
3391     def init(db):
3392         # might, in an obscure situation, happen in a create
3393         db.issue.audit('create', blockresolution)
3394         db.issue.audit('set', blockresolution)
3396         # can only happen on a set
3397         db.issue.react('set', resolveblockers)
3399    Put the above code in a file called "blockers.py" in your tracker's
3400    "detectors" directory.
3402 4. Finally, and this is an optional step, modify the tracker web page
3403    URLs so they filter out issues with any blockers. You do this by
3404    adding an additional filter on "blockers" for the value "-1". For
3405    example, the existing "Show All" link in the "page" template (in the
3406    tracker's "html" directory) looks like this::
3408      <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>
3410    modify it to add the "blockers" info to the URL (note, both the
3411    ":filter" *and* "blockers" values must be specified)::
3413      <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>
3415 That's it. You should now be able to set blockers on your issues. Note
3416 that if you want to know whether an issue has any other issues dependent
3417 on it (i.e. it's in their blockers list) you can look at the journal
3418 history at the bottom of the issue page - look for a "link" event to
3419 another issue's "blockers" property.
3421 Add users to the nosy list based on the topic
3422 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
3424 We need the ability to automatically add users to the nosy list based
3425 on the occurence of a topic. Every user should be allowed to edit his
3426 own list of topics for which he wants to be added to the nosy list.
3428 Below will be showed that such a change can be performed with only
3429 minimal understanding of the roundup system, but with clever use
3430 of Copy and Paste.
3432 This requires three changes to the tracker: a change in the database to
3433 allow per-user recording of the lists of topics for which he wants to
3434 be put on the nosy list, a change in the user view allowing to edit
3435 this list of topics, and addition of an auditor which updates the nosy
3436 list when a topic is set.
3438 Adding the nosy topic list
3439 ::::::::::::::::::::::::::
3441 The change in the database to make is that for any user there should be
3442 a list of topics for which he wants to be put on the nosy list. Adding
3443 a ``Multilink`` of ``keyword`` seem to fullfill this (note that within
3444 the code topics are called ``keywords``.) As such, all what has to be
3445 done is to add a new field to the definition of ``user`` within the
3446 file ``dbinit.py``.  We will call this new field ``nosy_keywords``, and
3447 the updated definition of user will be::
3449     user = Class(db, "user", 
3450                     username=String(),   password=Password(),
3451                     address=String(),    realname=String(), 
3452                     phone=String(),      organisation=String(),
3453                     alternate_addresses=String(),
3454                     queries=Multilink('query'), roles=String(),
3455                     timezone=String(),
3456                     nosy_keywords=Multilink('keyword'))
3457  
3458 Changing the user view to allow changing the nosy topic list
3459 ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
3461 We want any user to be able to change the list of topics for which
3462 he will by default be added to the nosy list. We choose to add this
3463 to the user view, as is generated by the file ``html/user.item.html``.
3464 We easily can
3465 see that the topic field in the issue view has very similar editting
3466 requirements as our nosy topics, both being a list of topics. As
3467 such, we search for Topics in ``issue.item.html``, and extract the
3468 associated parts from there. We add this to ``user.item.html`` at the 
3469 bottom of the list of viewed items (i.e. just below the 'Alternate
3470 E-mail addresses' in the classic template)::
3472  <tr>
3473   <th>Nosy Topics</th>
3474   <td>
3475   <span tal:replace="structure context/nosy_keywords/field" />
3476   <span tal:replace="structure python:db.keyword.classhelp(property='nosy_keywords')" />
3477   </td>
3478  </tr>
3479   
3481 Addition of an auditor to update the nosy list
3482 ::::::::::::::::::::::::::::::::::::::::::::::
3484 The more difficult part is the addition of the logic to actually
3485 at the users to the nosy list when it is required. 
3486 The choice is made to perform this action when the topics on an
3487 item are set, including when an item is created.
3488 Here we choose to start out with a copy of the 
3489 ``detectors/nosyreaction.py`` detector, which we copy to the file
3490 ``detectors/nosy_keyword_reaction.py``. 
3491 This looks like a good start as it also adds users
3492 to the nosy list. A look through the code reveals that the
3493 ``nosyreaction`` function actually is sending the e-mail, which
3494 we do not need. As such, we can change the init function to::
3496     def init(db):
3497         db.issue.audit('create', update_kw_nosy)
3498         db.issue.audit('set', update_kw_nosy)
3500 After that we rename the ``updatenosy`` function to ``update_kw_nosy``.
3501 The first two blocks of code in that function relate to settings
3502 ``current`` to a combination of the old and new nosy lists. This
3503 functionality is left in the new auditor. The following block of
3504 code, which in ``updatenosy`` handled adding the assignedto user(s)
3505 to the nosy list, should be replaced by a block of code to add the
3506 interested users to the nosy list. We choose here to loop over all
3507 new topics, than loop over all users,
3508 and assign the user to the nosy list when the topic in the user's
3509 nosy_keywords. The next part in ``updatenosy``, adding the author
3510 and/or recipients of a message to the nosy list, obviously is not
3511 relevant here and thus is deleted from the new auditor. The last
3512 part, copying the new nosy list to newvalues, does not have to be changed.
3513 This brings the following function::
3515     def update_kw_nosy(db, cl, nodeid, newvalues):
3516         '''Update the nosy list for changes to the topics
3517         '''
3518         # nodeid will be None if this is a new node
3519         current = {}
3520         if nodeid is None:
3521             ok = ('new', 'yes')
3522         else:
3523             ok = ('yes',)
3524             # old node, get the current values from the node if they haven't
3525             # changed
3526             if not newvalues.has_key('nosy'):
3527                 nosy = cl.get(nodeid, 'nosy')
3528                 for value in nosy:
3529                     if not current.has_key(value):
3530                         current[value] = 1
3532         # if the nosy list changed in this transaction, init from the new value
3533         if newvalues.has_key('nosy'):
3534             nosy = newvalues.get('nosy', [])
3535             for value in nosy:
3536                 if not db.hasnode('user', value):
3537                     continue
3538                 if not current.has_key(value):
3539                     current[value] = 1
3541         # add users with topic in nosy_keywords to the nosy list
3542         if newvalues.has_key('topic') and newvalues['topic'] is not None:
3543             topic_ids = newvalues['topic']
3544             for topic in topic_ids:
3545                 # loop over all users,
3546                 # and assign user to nosy when topic in nosy_keywords
3547                 for user_id in db.user.list():
3548                     nosy_kw = db.user.get(user_id, "nosy_keywords")
3549                     found = 0
3550                     for kw in nosy_kw:
3551                         if kw == topic:
3552                             found = 1
3553                     if found:
3554                         current[user_id] = 1
3556         # that's it, save off the new nosy list
3557         newvalues['nosy'] = current.keys()
3559 and these two function are the only ones needed in the file.
3561 TODO: update this example to use the find() Class method.
3563 Caveats
3564 :::::::
3566 A few problems with the design here can be noted:
3568 Multiple additions
3569     When a user, after automatic selection, is manually removed
3570     from the nosy list, he again is added to the nosy list when the
3571     topic list of the issue is updated. A better design might be
3572     to only check which topics are new compared to the old list
3573     of topics, and only add users when they have indicated
3574     interest on a new topic.
3576     The code could also be changed to only trigger on the create() event,
3577     rather than also on the set() event, thus only setting the nosy list
3578     when the issue is created.
3580 Scalability
3581     In the auditor there is a loop over all users. For a site with
3582     only few users this will pose no serious problem, however, with
3583     many users this will be a serious performance bottleneck.
3584     A way out will be to link from the topics to the users which
3585     selected these topics a nosy topics. This will eliminate the
3586     loop over all users.
3588 Changes to Security and Permissions
3589 -----------------------------------
3591 Restricting the list of users that are assignable to a task
3592 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
3594 1. In your tracker's "dbinit.py", create a new Role, say "Developer"::
3596      db.security.addRole(name='Developer', description='A developer')
3598 2. Just after that, create a new Permission, say "Fixer", specific to
3599    "issue"::
3601      p = db.security.addPermission(name='Fixer', klass='issue',
3602          description='User is allowed to be assigned to fix issues')
3604 3. Then assign the new Permission to your "Developer" Role::
3606      db.security.addPermissionToRole('Developer', p)
3608 4. In the issue item edit page ("html/issue.item.html" in your tracker
3609    directory), use the new Permission in restricting the "assignedto"
3610    list::
3612     <select name="assignedto">
3613      <option value="-1">- no selection -</option>
3614      <tal:block tal:repeat="user db/user/list">
3615      <option tal:condition="python:user.hasPermission(
3616                                 'Fixer', context._classname)"
3617              tal:attributes="
3618                 value user/id;
3619                 selected python:user.id == context.assignedto"
3620              tal:content="user/realname"></option>
3621      </tal:block>
3622     </select>
3624 For extra security, you may wish to setup an auditor to enforce the
3625 Permission requirement (install this as "assignedtoFixer.py" in your
3626 tracker "detectors" directory)::
3628   def assignedtoMustBeFixer(db, cl, nodeid, newvalues):
3629       ''' Ensure the assignedto value in newvalues is a used with the
3630           Fixer Permission
3631       '''
3632       if not newvalues.has_key('assignedto'):
3633           # don't care
3634           return
3635   
3636       # get the userid
3637       userid = newvalues['assignedto']
3638       if not db.security.hasPermission('Fixer', userid, cl.classname):
3639           raise ValueError, 'You do not have permission to edit %s'%cl.classname
3641   def init(db):
3642       db.issue.audit('set', assignedtoMustBeFixer)
3643       db.issue.audit('create', assignedtoMustBeFixer)
3645 So now, if an edit action attempts to set "assignedto" to a user that
3646 doesn't have the "Fixer" Permission, the error will be raised.
3648 Users may only edit their issues
3649 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
3651 Users registering themselves are granted Provisional access - meaning they
3652 have access to edit the issues they submit, but not others. We create a new
3653 Role called "Provisional User" which is granted to newly-registered users,
3654 and has limited access. One of the Permissions they have is the new "Edit
3655 Own" on issues (regular users have "Edit".) We back up the permissions with
3656 an auditor.
3658 First up, we create the new Role and Permission structure in
3659 ``dbinit.py``::
3661     # New users not approved by the admin
3662     db.security.addRole(name='Provisional User',
3663         description='New user registered via web or email')
3664     p = db.security.addPermission(name='Edit Own', klass='issue',
3665         description='Can only edit own issues')
3666     db.security.addPermissionToRole('Provisional User', p)
3668     # Assign the access and edit Permissions for issue to new users now
3669     p = db.security.getPermission('View', 'issue')
3670     db.security.addPermissionToRole('Provisional User', p)
3671     p = db.security.getPermission('Edit', 'issue')
3672     db.security.addPermissionToRole('Provisional User', p)
3674     # and give the new users access to the web and email interface
3675     p = db.security.getPermission('Web Access')
3676     db.security.addPermissionToRole('Provisional User', p)
3677     p = db.security.getPermission('Email Access')
3678     db.security.addPermissionToRole('Provisional User', p)
3681 Then in the ``config.py`` we change the Role assigned to newly-registered
3682 users, replacing the existing ``'User'`` values::
3684     NEW_WEB_USER_ROLES = 'Provisional User'
3685     NEW_EMAIL_USER_ROLES = 'Provisional User'
3687 Finally we add a new *auditor* to the ``detectors`` directory called
3688 ``provisional_user_auditor.py``::
3690  def audit_provisionaluser(db, cl, nodeid, newvalues):
3691      ''' New users are only allowed to modify their own issues.
3692      '''
3693      if (db.getuid() != cl.get(nodeid, 'creator')
3694          and db.security.hasPermission('Edit Own', db.getuid(), cl.classname)):
3695          raise ValueError, ('You are only allowed to edit your own %s'
3696                             % cl.classname)
3698  def init(db):
3699      # fire before changes are made
3700      db.issue.audit('set', audit_provisionaluser)
3701      db.issue.audit('retire', audit_provisionaluser)
3702      db.issue.audit('restore', audit_provisionaluser)
3704 Note that some older trackers might also want to change the ``page.html``
3705 template as follows::
3707  <p class="classblock"
3708  -       tal:condition="python:request.user.username != 'anonymous'">
3709  +       tal:condition="python:request.user.hasPermission('View', 'user')">
3710      <b>Administration</b><br>
3711      <tal:block tal:condition="python:request.user.hasPermission('Edit', None)">
3712       <a href="home?:template=classlist">Class List</a><br>
3714 (note that the "-" indicates a removed line, and the "+" indicates an added
3715 line).
3718 Changes to the Web User Interface
3719 ---------------------------------
3721 Adding action links to the index page
3722 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
3724 Add a column to the item.index.html template.
3726 Resolving the issue::
3728   <a tal:attributes="href
3729      string:issue${i/id}?:status=resolved&:action=edit">resolve</a>
3731 "Take" the issue::
3733   <a tal:attributes="href
3734      string:issue${i/id}?:assignedto=${request/user/id}&:action=edit">take</a>
3736 ... and so on
3738 Colouring the rows in the issue index according to priority
3739 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
3741 A simple ``tal:attributes`` statement will do the bulk of the work here. In
3742 the ``issue.index.html`` template, add to the ``<tr>`` that displays the
3743 actual rows of data::
3745    <tr tal:attributes="class string:priority-${i/priority/plain}">
3747 and then in your stylesheet (``style.css``) specify the colouring for the
3748 different priorities, like::
3750    tr.priority-critical td {
3751        background-color: red;
3752    }
3754    tr.priority-urgent td {
3755        background-color: orange;
3756    }
3758 and so on, with far less offensive colours :)
3760 Editing multiple items in an index view
3761 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
3763 To edit the status of all items in the item index view, edit the
3764 ``issue.item.html``:
3766 1. add a form around the listing table, so at the top it reads::
3768     <form method="POST" tal:attributes="action request/classname">
3769      <table class="list">
3771    and at the bottom of that table::
3773      </table>
3774     </form
3776    making sure you match the ``</table>`` from the list table, not the
3777    navigation table or the subsequent form table.
3779 2. in the display for the issue property, change::
3781     <td tal:condition="request/show/status"
3782         tal:content="python:i.status.plain() or default">&nbsp;</td>
3784    to::
3786     <td tal:condition="request/show/status"
3787         tal:content="structure i/status/field">&nbsp;</td>
3789    this will result in an edit field for the status property.
3791 3. after the ``tal:block`` which lists the actual index items (marked by
3792    ``tal:repeat="i batch"``) add a new table row::
3794     <tr>
3795      <td tal:attributes="colspan python:len(request.columns)">
3796       <input type="submit" value=" Save Changes ">
3797       <input type="hidden" name="@action" value="edit">
3798       <tal:block replace="structure request/indexargs_form" />
3799      </td>
3800     </tr>
3802    which gives us a submit button, indicates that we are performing an edit
3803    on any changed statuses and the final block will make sure that the
3804    current index view parameters (filtering, columns, etc) will be used in 
3805    rendering the next page (the results of the editing).
3808 Displaying only message summaries in the issue display
3809 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
3811 Alter the issue.item template section for messages to::
3813  <table class="messages" tal:condition="context/messages">
3814   <tr><th colspan="5" class="header">Messages</th></tr>
3815   <tr tal:repeat="msg context/messages">
3816    <td><a tal:attributes="href string:msg${msg/id}"
3817           tal:content="string:msg${msg/id}"></a></td>
3818    <td tal:content="msg/author">author</td>
3819    <td class="date" tal:content="msg/date/pretty">date</td>
3820    <td tal:content="msg/summary">summary</td>
3821    <td>
3822     <a tal:attributes="href string:?@remove@messages=${msg/id}&@action=edit">
3823     remove</a>
3824    </td>
3825   </tr>
3826  </table>
3829 Enabling display of either message summaries or the entire messages
3830 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
3832 This is pretty simple - all we need to do is copy the code from the
3833 example `displaying only message summaries in the issue display`_ into
3834 our template alongside the summary display, and then introduce a switch
3835 that shows either one or the other. We'll use a new form variable,
3836 ``@whole_messages`` to achieve this::
3838  <table class="messages" tal:condition="context/messages">
3839   <tal:block tal:condition="not:request/form/@whole_messages/value | python:0">
3840    <tr><th colspan="3" class="header">Messages</th>
3841        <th colspan="2" class="header">
3842          <a href="?@whole_messages=yes">show entire messages</a>
3843        </th>
3844    </tr>
3845    <tr tal:repeat="msg context/messages">
3846     <td><a tal:attributes="href string:msg${msg/id}"
3847            tal:content="string:msg${msg/id}"></a></td>
3848     <td tal:content="msg/author">author</td>
3849     <td class="date" tal:content="msg/date/pretty">date</td>
3850     <td tal:content="msg/summary">summary</td>
3851     <td>
3852      <a tal:attributes="href string:?@remove@messages=${msg/id}&@action=edit">remove</a>
3853     </td>
3854    </tr>
3855   </tal:block>
3857   <tal:block tal:condition="request/form/@whole_messages/value | python:0">
3858    <tr><th colspan="2" class="header">Messages</th>
3859        <th class="header">
3860          <a href="?@whole_messages=">show only summaries</a>
3861        </th>
3862    </tr>
3863    <tal:block tal:repeat="msg context/messages">
3864     <tr>
3865      <th tal:content="msg/author">author</th>
3866      <th class="date" tal:content="msg/date/pretty">date</th>
3867      <th style="text-align: right">
3868       (<a tal:attributes="href string:?@remove@messages=${msg/id}&@action=edit">remove</a>)
3869      </th>
3870     </tr>
3871     <tr><td colspan="3" tal:content="msg/content"></td></tr>
3872    </tal:block>
3873   </tal:block>
3874  </table>
3876 Setting up a "wizard" (or "druid") for controlled adding of issues
3877 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
3879 1. Set up the page templates you wish to use for data input. My wizard
3880    is going to be a two-step process: first figuring out what category
3881    of issue the user is submitting, and then getting details specific to
3882    that category. The first page includes a table of help, explaining
3883    what the category names mean, and then the core of the form::
3885     <form method="POST" onSubmit="return submit_once()"
3886           enctype="multipart/form-data">
3887       <input type="hidden" name="@template" value="add_page1">
3888       <input type="hidden" name="@action" value="page1_submit">
3890       <strong>Category:</strong>
3891       <tal:block tal:replace="structure context/category/menu" />
3892       <input type="submit" value="Continue">
3893     </form>
3895    The next page has the usual issue entry information, with the
3896    addition of the following form fragments::
3898     <form method="POST" onSubmit="return submit_once()"
3899           enctype="multipart/form-data"
3900           tal:condition="context/is_edit_ok"
3901           tal:define="cat request/form/category/value">
3903       <input type="hidden" name="@template" value="add_page2">
3904       <input type="hidden" name="@required" value="title">
3905       <input type="hidden" name="category" tal:attributes="value cat">
3906        .
3907        .
3908        .
3909     </form>
3911    Note that later in the form, I test the value of "cat" include form
3912    elements that are appropriate. For example::
3914     <tal:block tal:condition="python:cat in '6 10 13 14 15 16 17'.split()">
3915      <tr>
3916       <th>Operating System</th>
3917       <td tal:content="structure context/os/field"></td>
3918      </tr>
3919      <tr>
3920       <th>Web Browser</th>
3921       <td tal:content="structure context/browser/field"></td>
3922      </tr>
3923     </tal:block>
3925    ... the above section will only be displayed if the category is one
3926    of 6, 10, 13, 14, 15, 16 or 17.
3928 3. Determine what actions need to be taken between the pages - these are
3929    usually to validate user choices and determine what page is next. Now encode
3930    those actions in a new ``Action`` class and insert hooks to those actions in
3931    the "actions" attribute on on the ``interfaces.Client`` class, like so (see 
3932    `defining new web actions`_)::
3934     class Page1SubmitAction(Action):
3935         def handle(self):
3936             ''' Verify that the user has selected a category, and then move
3937                 on to page 2.
3938             '''
3939             category = self.form['category'].value
3940             if category == '-1':
3941                 self.error_message.append('You must select a category of report')
3942                 return
3943             # everything's ok, move on to the next page
3944             self.template = 'add_page2'
3946     actions = client.Client.actions + (
3947         ('page1_submit', Page1SubmitAction),
3948     )
3950 4. Use the usual "new" action as the ``@action`` on the final page, and
3951    you're done (the standard context/submit method can do this for you).
3955 -------------------
3957 Back to `Table of Contents`_
3959 .. _`Table of Contents`: index.html
3960 .. _`design documentation`: design.html