1 ===================
2 Customising Roundup
3 ===================
5 :Version: $Revision: 1.127 $
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 Sample additional detectors that have been found useful will appear in
589 the ``'detectors'`` directory of the Roundup distribution. If you want
590 to use one, copy it to the ``'detectors'`` of your tracker instance:
592 **newissuecopy.py**
593 This detector sends an email to a team address whenever a new issue is
594 created. The address is hard-coded into the detector, so edit it
595 before you use it (look for the text 'team@team.host') or you'll get
596 email errors!
598 The detector code::
600 from roundup import roundupdb
602 def newissuecopy(db, cl, nodeid, oldvalues):
603 ''' Copy a message about new issues to a team address.
604 '''
605 # so use all the messages in the create
606 change_note = cl.generateCreateNote(nodeid)
608 # send a copy to the nosy list
609 for msgid in cl.get(nodeid, 'messages'):
610 try:
611 # note: last arg must be a list
612 cl.send_message(nodeid, msgid, change_note,
613 ['team@team.host'])
614 except roundupdb.MessageSendError, message:
615 raise roundupdb.DetectorError, message
617 def init(db):
618 db.issue.react('create', newissuecopy)
621 Auditor or Reactor?
622 -------------------
624 Generally speaking, the following rules should be observed:
626 **Auditors**
627 Are used for `vetoing creation of or changes to items`_. They might
628 also make automatic changes to item properties.
629 **Reactors**
630 Detect changes in the database and react accordingly. They should avoid
631 making changes to the database where possible, as this could create
632 detector loops.
635 Vetoing creation of or changes to items
636 ---------------------------------------
638 Auditors may raise the ``Reject`` exception to prevent the creation of
639 or changes to items in the database. The mail gateway, for example, will
640 not attach files or messages to issues when the creation of those files or
641 messages are prevented through the ``Reject`` exception. It'll also not create
642 users if that creation is ``Reject``'ed too.
644 To use, simply add at the top of your auditor::
646 from roundup.exceptions import Reject
648 And then when your rejection criteria have been detected, simply::
650 raise Reject
653 Generating email from Roundup
654 -----------------------------
656 The module ``roundup.mailer`` contains most of the nuts-n-bolts required
657 to generate email messages from Roundup.
659 In addition, the ``IssueClass`` methods ``nosymessage()`` and
660 ``send_message()`` are used to generate nosy messages, and may generate
661 messages which only consist of a change note (ie. the message id parameter
662 is not required).
665 Database Content
666 ================
668 Note: if you modify the content of definitional classes, you'll most
669 likely need to edit the tracker `detectors`_ to reflect your
670 changes.
672 Customisation of the special "definitional" classes (eg. status,
673 priority, resolution, ...) may be done either before or after the
674 tracker is initialised. The actual method of doing so is completely
675 different in each case though, so be careful to use the right one.
677 **Changing content before tracker initialisation**
678 Edit the dbinit module in your tracker to alter the items created in
679 using the ``create()`` methods.
681 **Changing content after tracker initialisation**
682 As the "admin" user, click on the "class list" link in the web
683 interface to bring up a list of all database classes. Click on the
684 name of the class you wish to change the content of.
686 You may also use the ``roundup-admin`` interface's create, set and
687 retire methods to add, alter or remove items from the classes in
688 question.
690 See "`adding a new field to the classic schema`_" for an example that
691 requires database content changes.
694 Security / Access Controls
695 ==========================
697 A set of Permissions is built into the security module by default:
699 - Edit (everything)
700 - View (everything)
702 Every Class you define in your tracker's schema also gets an Edit and View
703 Permission of its own.
705 The default interfaces define:
707 - Web Registration
708 - Web Access
709 - Web Roles
710 - Email Registration
711 - Email Access
713 These are hooked into the default Roles:
715 - Admin (Edit everything, View everything, Web Roles)
716 - User (Web Access, Email Access)
717 - Anonymous (Web Registration, Email Registration)
719 And finally, the "admin" user gets the "Admin" Role, and the "anonymous"
720 user gets "Anonymous" assigned when the database is initialised on
721 installation. The two default schemas then define:
723 - Edit issue, View issue (both)
724 - Edit file, View file (both)
725 - Edit msg, View msg (both)
726 - Edit support, View support (extended only)
728 and assign those Permissions to the "User" Role. Put together, these
729 settings appear in the ``open()`` function of the tracker ``dbinit.py``
730 (the following is taken from the "minimal" template's ``dbinit.py``)::
732 #
733 # SECURITY SETTINGS
734 #
735 # and give the regular users access to the web and email interface
736 p = db.security.getPermission('Web Access')
737 db.security.addPermissionToRole('User', p)
738 p = db.security.getPermission('Email Access')
739 db.security.addPermissionToRole('User', p)
741 # May users view other user information? Comment these lines out
742 # if you don't want them to
743 p = db.security.getPermission('View', 'user')
744 db.security.addPermissionToRole('User', p)
746 # Assign the appropriate permissions to the anonymous user's
747 # Anonymous role. Choices here are:
748 # - Allow anonymous users to register through the web
749 p = db.security.getPermission('Web Registration')
750 db.security.addPermissionToRole('Anonymous', p)
751 # - Allow anonymous (new) users to register through the email
752 # gateway
753 p = db.security.getPermission('Email Registration')
754 db.security.addPermissionToRole('Anonymous', p)
757 New User Roles
758 --------------
760 New users are assigned the Roles defined in the config file as:
762 - NEW_WEB_USER_ROLES
763 - NEW_EMAIL_USER_ROLES
766 Changing Access Controls
767 ------------------------
769 You may alter the configuration variables to change the Role that new
770 web or email users get, for example to not give them access to the web
771 interface if they register through email.
773 You may use the ``roundup-admin`` "``security``" command to display the
774 current Role and Permission configuration in your tracker.
777 Adding a new Permission
778 ~~~~~~~~~~~~~~~~~~~~~~~
780 When adding a new Permission, you will need to:
782 1. add it to your tracker's dbinit so it is created, using
783 ``security.addPermission``, for example::
785 self.security.addPermission(name="View", klass='frozzle',
786 description="User is allowed to access frozzles")
788 will set up a new "View" permission on the Class "frozzle".
789 2. enable it for the Roles that should have it (verify with
790 "``roundup-admin security``")
791 3. add it to the relevant HTML interface templates
792 4. add it to the appropriate xxxPermission methods on in your tracker
793 interfaces module
796 Example Scenarios
797 ~~~~~~~~~~~~~~~~~
799 **automatic registration of users in the e-mail gateway**
800 By giving the "anonymous" user the "Email Registration" Role, any
801 unidentified user will automatically be registered with the tracker
802 (with no password, so they won't be able to log in through the web
803 until an admin sets their password). Note: this is the default
804 behaviour in the tracker templates that ship with Roundup.
806 **anonymous access through the e-mail gateway**
807 Give the "anonymous" user the "Email Access" and ("Edit", "issue")
808 Roles but do not not give them the "Email Registration" Role. This
809 means that when an unknown user sends email into the tracker, they're
810 automatically logged in as "anonymous". Since they don't have the
811 "Email Registration" Role, they won't be automatically registered, but
812 since "anonymous" has permission to use the gateway, they'll still be
813 able to submit issues. Note that the Sender information - their email
814 address - will not be available - they're *anonymous*.
816 **only developers may be assigned issues**
817 Create a new Permission called "Fixer" for the "issue" class. Create a
818 new Role "Developer" which has that Permission, and assign that to the
819 appropriate users. Filter the list of users available in the assignedto
820 list to include only those users. Enforce the Permission with an
821 auditor. See the example
822 `restricting the list of users that are assignable to a task`_.
824 **only managers may sign off issues as complete**
825 Create a new Permission called "Closer" for the "issue" class. Create a
826 new Role "Manager" which has that Permission, and assign that to the
827 appropriate users. In your web interface, only display the "resolved"
828 issue state option when the user has the "Closer" Permissions. Enforce
829 the Permission with an auditor. This is very similar to the previous
830 example, except that the web interface check would look like::
832 <option tal:condition="python:request.user.hasPermission('Closer')"
833 value="resolved">Resolved</option>
835 **don't give web access to users who register through email**
836 Create a new Role called "Email User" which has all the Permissions of
837 the normal "User" Role minus the "Web Access" Permission. This will
838 allow users to send in emails to the tracker, but not access the web
839 interface.
841 **let some users edit the details of all users**
842 Create a new Role called "User Admin" which has the Permission for
843 editing users::
845 db.security.addRole(name='User Admin', description='Managing users')
846 p = db.security.getPermission('Edit', 'user')
847 db.security.addPermissionToRole('User Admin', p)
849 and assign the Role to the users who need the permission.
852 Web Interface
853 =============
855 .. contents::
856 :local:
857 :depth: 1
859 The web interface is provided by the ``roundup.cgi.client`` module and
860 is used by ``roundup.cgi``, ``roundup-server`` and ``ZRoundup``
861 (``ZRoundup`` is broken, until further notice). In all cases, we
862 determine which tracker is being accessed (the first part of the URL
863 path inside the scope of the CGI handler) and pass control on to the
864 tracker ``interfaces.Client`` class - which uses the ``Client`` class
865 from ``roundup.cgi.client`` - which handles the rest of the access
866 through its ``main()`` method. This means that you can do pretty much
867 anything you want as a web interface to your tracker.
869 Repercussions of changing the tracker schema
870 ---------------------------------------------
872 If you choose to change the `tracker schema`_ you will need to ensure
873 the web interface knows about it:
875 1. Index, item and search pages for the relevant classes may need to
876 have properties added or removed,
877 2. The "page" template may require links to be changed, as might the
878 "home" page's content arguments.
880 How requests are processed
881 --------------------------
883 The basic processing of a web request proceeds as follows:
885 1. figure out who we are, defaulting to the "anonymous" user
886 2. figure out what the request is for - we call this the "context"
887 3. handle any requested action (item edit, search, ...)
888 4. render the template requested by the context, resulting in HTML
889 output
891 In some situations, exceptions occur:
893 - HTTP Redirect (generally raised by an action)
894 - SendFile (generally raised by ``determine_context``)
895 here we serve up a FileClass "content" property
896 - SendStaticFile (generally raised by ``determine_context``)
897 here we serve up a file from the tracker "html" directory
898 - Unauthorised (generally raised by an action)
899 here the action is cancelled, the request is rendered and an error
900 message is displayed indicating that permission was not granted for
901 the action to take place
902 - NotFound (raised wherever it needs to be)
903 this exception percolates up to the CGI interface that called the
904 client
906 Determining web context
907 -----------------------
909 To determine the "context" of a request, we look at the URL and the
910 special request variable ``@template``. The URL path after the tracker
911 identifier is examined. Typical URL paths look like:
913 1. ``/tracker/issue``
914 2. ``/tracker/issue1``
915 3. ``/tracker/@file/style.css``
916 4. ``/cgi-bin/roundup.cgi/tracker/file1``
917 5. ``/cgi-bin/roundup.cgi/tracker/file1/kitten.png``
919 where the "tracker identifier" is "tracker" in the above cases. That means
920 we're looking at "issue", "issue1", "@file/style.css", "file1" and
921 "file1/kitten.png" in the cases above. The path is generally only one
922 entry long - longer paths are handled differently.
924 a. if there is no path, then we are in the "home" context.
925 b. if the path starts with "@file" (as in example 3,
926 "/tracker/@file/style.css"), then the additional path entry,
927 "style.css" specifies the filename of a static file we're to serve up
928 from the tracker "html" directory. Raises a SendStaticFile exception.
929 c. if there is something in the path (as in example 1, "issue"), it
930 identifies the tracker class we're to display.
931 d. if the path is an item designator (as in examples 2 and 4, "issue1"
932 and "file1"), then we're to display a specific item.
933 e. if the path starts with an item designator and is longer than one
934 entry (as in example 5, "file1/kitten.png"), then we're assumed to be
935 handling an item of a ``FileClass``, and the extra path information
936 gives the filename that the client is going to label the download
937 with (i.e. "file1/kitten.png" is nicer to download than "file1").
938 This raises a ``SendFile`` exception.
940 Both b. and e. stop before we bother to determine the template we're
941 going to use. That's because they don't actually use templates.
943 The template used is specified by the ``@template`` CGI variable, which
944 defaults to:
946 - only classname suplied: "index"
947 - full item designator supplied: "item"
950 Serving static content
951 ----------------------
953 See the previous section `determining web context`_ where it describes
954 ``@file`` paths.
957 Performing actions in web requests
958 ----------------------------------
960 When a user requests a web page, they may optionally also request for an
961 action to take place. As described in `how requests are processed`_, the
962 action is performed before the requested page is generated. Actions are
963 triggered by using a ``@action`` CGI variable, where the value is one
964 of:
966 **login**
967 Attempt to log a user in.
969 **logout**
970 Log the user out - make them "anonymous".
972 **register**
973 Attempt to create a new user based on the contents of the form and then
974 log them in.
976 **edit**
977 Perform an edit of an item in the database. There are some `special form
978 variables`_ you may use.
980 **new**
981 Add a new item to the database. You may use the same `special form
982 variables`_ as in the "edit" action.
984 **retire**
985 Retire the item in the database.
987 **editCSV**
988 Performs an edit of all of a class' items in one go. See also the
989 *class*.csv templating method which generates the CSV data to be
990 edited, and the ``'_generic.index'`` template which uses both of these
991 features.
993 **search**
994 Mangle some of the form variables:
996 - Set the form ":filter" variable based on the values of the filter
997 variables - if they're set to anything other than "dontcare" then add
998 them to :filter.
1000 - Also handle the ":queryname" variable and save off the query to the
1001 user's query list.
1003 Each of the actions is implemented by a corresponding ``*XxxAction*`` (where
1004 "Xxx" is the name of the action) class in the ``roundup.cgi.actions`` module.
1005 These classes are registered with ``roundup.cgi.client.Client`` which also
1006 happens to be available in your tracker instance as ``interfaces.Client``. So
1007 if you need to define new actions, you may add them there (see `defining new
1008 web actions`_).
1010 Each action class also has a ``*permission*`` method which determines whether
1011 the action is permissible given the current user. The base permission checks
1012 are:
1014 **login**
1015 Determine whether the user has permission to log in. Base behaviour is
1016 to check the user has "Web Access".
1017 **logout**
1018 No permission checks are made.
1019 **register**
1020 Determine whether the user has permission to register. Base behaviour
1021 is to check the user has the "Web Registration" Permission.
1022 **edit**
1023 Determine whether the user has permission to edit this item. Base
1024 behaviour is to check whether the user can edit this class. If we're
1025 editing the "user" class, users are allowed to edit their own details -
1026 unless they try to edit the "roles" property, which requires the
1027 special Permission "Web Roles".
1028 **new**
1029 Determine whether the user has permission to create (or edit) this
1030 item. Base behaviour is to check the user can edit this class. No
1031 additional property checks are made. Additionally, new user items may
1032 be created if the user has the "Web Registration" Permission.
1033 **editCSV**
1034 Determine whether the user has permission to edit this class. Base
1035 behaviour is to check whether the user may edit this class.
1036 **search**
1037 Determine whether the user has permission to search this class. Base
1038 behaviour is to check whether the user may view this class.
1041 Special form variables
1042 ----------------------
1044 Item properties and their values are edited with html FORM
1045 variables and their values. You can:
1047 - Change the value of some property of the current item.
1048 - Create a new item of any class, and edit the new item's
1049 properties,
1050 - Attach newly created items to a multilink property of the
1051 current item.
1052 - Remove items from a multilink property of the current item.
1053 - Specify that some properties are required for the edit
1054 operation to be successful.
1056 In the following, <bracketed> values are variable, "@" may be
1057 either ":" or "@", and other text "required" is fixed.
1059 Most properties are specified as form variables:
1061 ``<propname>``
1062 property on the current context item
1064 ``<designator>"@"<propname>``
1065 property on the indicated item (for editing related information)
1067 Designators name a specific item of a class.
1069 ``<classname><N>``
1070 Name an existing item of class <classname>.
1072 ``<classname>"-"<N>``
1073 Name the <N>th new item of class <classname>. If the form
1074 submission is successful, a new item of <classname> is
1075 created. Within the submitted form, a particular
1076 designator of this form always refers to the same new
1077 item.
1079 Once we have determined the "propname", we look at it to see
1080 if it's special:
1082 ``@required``
1083 The associated form value is a comma-separated list of
1084 property names that must be specified when the form is
1085 submitted for the edit operation to succeed.
1087 When the <designator> is missing, the properties are
1088 for the current context item. When <designator> is
1089 present, they are for the item specified by
1090 <designator>.
1092 The "@required" specifier must come before any of the
1093 properties it refers to are assigned in the form.
1095 ``@remove@<propname>=id(s)`` or ``@add@<propname>=id(s)``
1096 The "@add@" and "@remove@" edit actions apply only to
1097 Multilink properties. The form value must be a
1098 comma-separate list of keys for the class specified by
1099 the simple form variable. The listed items are added
1100 to (respectively, removed from) the specified
1101 property.
1103 ``@link@<propname>=<designator>``
1104 If the edit action is "@link@", the simple form
1105 variable must specify a Link or Multilink property.
1106 The form value is a comma-separated list of
1107 designators. The item corresponding to each
1108 designator is linked to the property given by simple
1109 form variable.
1111 None of the above (ie. just a simple form value)
1112 The value of the form variable is converted
1113 appropriately, depending on the type of the property.
1115 For a Link('klass') property, the form value is a
1116 single key for 'klass', where the key field is
1117 specified in dbinit.py.
1119 For a Multilink('klass') property, the form value is a
1120 comma-separated list of keys for 'klass', where the
1121 key field is specified in dbinit.py.
1123 Note that for simple-form-variables specifiying Link
1124 and Multilink properties, the linked-to class must
1125 have a key field.
1127 For a String() property specifying a filename, the
1128 file named by the form value is uploaded. This means we
1129 try to set additional properties "filename" and "type" (if
1130 they are valid for the class). Otherwise, the property
1131 is set to the form value.
1133 For Date(), Interval(), Boolean(), and Number()
1134 properties, the form value is converted to the
1135 appropriate
1137 Any of the form variables may be prefixed with a classname or
1138 designator.
1140 Two special form values are supported for backwards compatibility:
1142 @note
1143 This is equivalent to::
1145 @link@messages=msg-1
1146 msg-1@content=value
1148 except that in addition, the "author" and "date" properties of
1149 "msg-1" are set to the userid of the submitter, and the current
1150 time, respectively.
1152 @file
1153 This is equivalent to::
1155 @link@files=file-1
1156 file-1@content=value
1158 The String content value is handled as described above for file
1159 uploads.
1161 If both the "@note" and "@file" form variables are
1162 specified, the action::
1164 @link@msg-1@files=file-1
1166 is also performed.
1168 We also check that FileClass items have a "content" property with
1169 actual content, otherwise we remove them from all_props before
1170 returning.
1174 Default templates
1175 -----------------
1177 The default templates are html4 compliant. If you wish to change them to be
1178 xhtml compliant, you'll need to change the ``HTML_VERSION`` configuration
1179 variable in ``config.py`` to ``'xhtml'`` instead of ``'html4'``.
1181 Most customisation of the web view can be done by modifying the
1182 templates in the tracker ``'html'`` directory. There are several types
1183 of files in there. The *minimal* template includes:
1185 **page.html**
1186 This template usually defines the overall look of your tracker. When
1187 you view an issue, it appears inside this template. When you view an
1188 index, it also appears inside this template. This template defines a
1189 macro called "icing" which is used by almost all other templates as a
1190 coating for their content, using its "content" slot. It also defines
1191 the "head_title" and "body_title" slots to allow setting of the page
1192 title.
1193 **home.html**
1194 the default page displayed when no other page is indicated by the user
1195 **home.classlist.html**
1196 a special version of the default page that lists the classes in the
1197 tracker
1198 **classname.item.html**
1199 displays an item of the *classname* class
1200 **classname.index.html**
1201 displays a list of *classname* items
1202 **classname.search.html**
1203 displays a search page for *classname* items
1204 **_generic.index.html**
1205 used to display a list of items where there is no
1206 ``*classname*.index`` available
1207 **_generic.help.html**
1208 used to display a "class help" page where there is no
1209 ``*classname*.help``
1210 **user.register.html**
1211 a special page just for the user class, that renders the registration
1212 page
1213 **style.css.html**
1214 a static file that is served up as-is
1216 The *classic* template has a number of additional templates.
1218 Note: Remember that you can create any template extension you want to,
1219 so if you just want to play around with the templating for new issues,
1220 you can copy the current "issue.item" template to "issue.test", and then
1221 access the test template using the "@template" URL argument::
1223 http://your.tracker.example/tracker/issue?@template=test
1225 and it won't affect your users using the "issue.item" template.
1228 How the templates work
1229 ----------------------
1232 Basic Templating Actions
1233 ~~~~~~~~~~~~~~~~~~~~~~~~
1235 Roundup's templates consist of special attributes on the HTML tags.
1236 These attributes form the Template Attribute Language, or TAL. The basic
1237 TAL commands are:
1239 **tal:define="variable expression; variable expression; ..."**
1240 Define a new variable that is local to this tag and its contents. For
1241 example::
1243 <html tal:define="title request/description">
1244 <head><title tal:content="title"></title></head>
1245 </html>
1247 In this example, the variable "title" is defined as the result of the
1248 expression "request/description". The "tal:content" command inside the
1249 <html> tag may then use the "title" variable.
1251 **tal:condition="expression"**
1252 Only keep this tag and its contents if the expression is true. For
1253 example::
1255 <p tal:condition="python:request.user.hasPermission('View', 'issue')">
1256 Display some issue information.
1257 </p>
1259 In the example, the <p> tag and its contents are only displayed if
1260 the user has the "View" permission for issues. We consider the number
1261 zero, a blank string, an empty list, and the built-in variable
1262 nothing to be false values. Nearly every other value is true,
1263 including non-zero numbers, and strings with anything in them (even
1264 spaces!).
1266 **tal:repeat="variable expression"**
1267 Repeat this tag and its contents for each element of the sequence
1268 that the expression returns, defining a new local variable and a
1269 special "repeat" variable for each element. For example::
1271 <tr tal:repeat="u user/list">
1272 <td tal:content="u/id"></td>
1273 <td tal:content="u/username"></td>
1274 <td tal:content="u/realname"></td>
1275 </tr>
1277 The example would iterate over the sequence of users returned by
1278 "user/list" and define the local variable "u" for each entry.
1280 **tal:replace="expression"**
1281 Replace this tag with the result of the expression. For example::
1283 <span tal:replace="request/user/realname" />
1285 The example would replace the <span> tag and its contents with the
1286 user's realname. If the user's realname was "Bruce", then the
1287 resultant output would be "Bruce".
1289 **tal:content="expression"**
1290 Replace the contents of this tag with the result of the expression.
1291 For example::
1293 <span tal:content="request/user/realname">user's name appears here
1294 </span>
1296 The example would replace the contents of the <span> tag with the
1297 user's realname. If the user's realname was "Bruce" then the
1298 resultant output would be "<span>Bruce</span>".
1300 **tal:attributes="attribute expression; attribute expression; ..."**
1301 Set attributes on this tag to the results of expressions. For
1302 example::
1304 <a tal:attributes="href string:user${request/user/id}">My Details</a>
1306 In the example, the "href" attribute of the <a> tag is set to the
1307 value of the "string:user${request/user/id}" expression, which will
1308 be something like "user123".
1310 **tal:omit-tag="expression"**
1311 Remove this tag (but not its contents) if the expression is true. For
1312 example::
1314 <span tal:omit-tag="python:1">Hello, world!</span>
1316 would result in output of::
1318 Hello, world!
1320 Note that the commands on a given tag are evaulated in the order above,
1321 so *define* comes before *condition*, and so on.
1323 Additionally, you may include tags such as <tal:block>, which are
1324 removed from output. Its content is kept, but the tag itself is not (so
1325 don't go using any "tal:attributes" commands on it). This is useful for
1326 making arbitrary blocks of HTML conditional or repeatable (very handy
1327 for repeating multiple table rows, which would othewise require an
1328 illegal tag placement to effect the repeat).
1331 Templating Expressions
1332 ~~~~~~~~~~~~~~~~~~~~~~
1334 The expressions you may use in the attribute values may be one of the
1335 following forms:
1337 **Path Expressions** - eg. ``item/status/checklist``
1338 These are object attribute / item accesses. Roughly speaking, the
1339 path ``item/status/checklist`` is broken into parts ``item``,
1340 ``status`` and ``checklist``. The ``item`` part is the root of the
1341 expression. We then look for a ``status`` attribute on ``item``, or
1342 failing that, a ``status`` item (as in ``item['status']``). If that
1343 fails, the path expression fails. When we get to the end, the object
1344 we're left with is evaluated to get a string - if it is a method, it
1345 is called; if it is an object, it is stringified. Path expressions
1346 may have an optional ``path:`` prefix, but they are the default
1347 expression type, so it's not necessary.
1349 If an expression evaluates to ``default``, then the expression is
1350 "cancelled" - whatever HTML already exists in the template will
1351 remain (tag content in the case of ``tal:content``, attributes in the
1352 case of ``tal:attributes``).
1354 If an expression evaluates to ``nothing`` then the target of the
1355 expression is removed (tag content in the case of ``tal:content``,
1356 attributes in the case of ``tal:attributes`` and the tag itself in
1357 the case of ``tal:replace``).
1359 If an element in the path may not exist, then you can use the ``|``
1360 operator in the expression to provide an alternative. So, the
1361 expression ``request/form/foo/value | default`` would simply leave
1362 the current HTML in place if the "foo" form variable doesn't exist.
1364 You may use the python function ``path``, as in
1365 ``path("item/status")``, to embed path expressions in Python
1366 expressions.
1368 **String Expressions** - eg. ``string:hello ${user/name}``
1369 These expressions are simple string interpolations - though they can
1370 be just plain strings with no interpolation if you want. The
1371 expression in the ``${ ... }`` is just a path expression as above.
1373 **Python Expressions** - eg. ``python: 1+1``
1374 These expressions give the full power of Python. All the "root level"
1375 variables are available, so ``python:item.status.checklist()`` would
1376 be equivalent to ``item/status/checklist``, assuming that
1377 ``checklist`` is a method.
1379 Modifiers:
1381 **structure** - eg. ``structure python:msg.content.plain(hyperlink=1)``
1382 The result of expressions are normally *escaped* to be safe for HTML
1383 display (all "<", ">" and "&" are turned into special entities). The
1384 ``structure`` expression modifier turns off this escaping - the
1385 result of the expression is now assumed to be HTML, which is passed
1386 to the web browser for rendering.
1388 **not:** - eg. ``not:python:1=1``
1389 This simply inverts the logical true/false value of another
1390 expression.
1393 Template Macros
1394 ~~~~~~~~~~~~~~~
1396 Macros are used in Roundup to save us from repeating the same common
1397 page stuctures over and over. The most common (and probably only) macro
1398 you'll use is the "icing" macro defined in the "page" template.
1400 Macros are generated and used inside your templates using special
1401 attributes similar to the `basic templating actions`_. In this case,
1402 though, the attributes belong to the Macro Expansion Template Attribute
1403 Language, or METAL. The macro commands are:
1405 **metal:define-macro="macro name"**
1406 Define that the tag and its contents are now a macro that may be
1407 inserted into other templates using the *use-macro* command. For
1408 example::
1410 <html metal:define-macro="page">
1411 ...
1412 </html>
1414 defines a macro called "page" using the ``<html>`` tag and its
1415 contents. Once defined, macros are stored on the template they're
1416 defined on in the ``macros`` attribute. You can access them later on
1417 through the ``templates`` variable, eg. the most common
1418 ``templates/page/macros/icing`` to access the "page" macro of the
1419 "page" template.
1421 **metal:use-macro="path expression"**
1422 Use a macro, which is identified by the path expression (see above).
1423 This will replace the current tag with the identified macro contents.
1424 For example::
1426 <tal:block metal:use-macro="templates/page/macros/icing">
1427 ...
1428 </tal:block>
1430 will replace the tag and its contents with the "page" macro of the
1431 "page" template.
1433 **metal:define-slot="slot name"** and **metal:fill-slot="slot name"**
1434 To define *dynamic* parts of the macro, you define "slots" which may
1435 be filled when the macro is used with a *use-macro* command. For
1436 example, the ``templates/page/macros/icing`` macro defines a slot like
1437 so::
1439 <title metal:define-slot="head_title">title goes here</title>
1441 In your *use-macro* command, you may now use a *fill-slot* command
1442 like this::
1444 <title metal:fill-slot="head_title">My Title</title>
1446 where the tag that fills the slot completely replaces the one defined
1447 as the slot in the macro.
1449 Note that you may not mix METAL and TAL commands on the same tag, but
1450 TAL commands may be used freely inside METAL-using tags (so your
1451 *fill-slots* tags may have all manner of TAL inside them).
1454 Information available to templates
1455 ----------------------------------
1457 Note: this is implemented by
1458 ``roundup.cgi.templating.RoundupPageTemplate``
1460 The following variables are available to templates.
1462 **context**
1463 The current context. This is either None, a `hyperdb class wrapper`_
1464 or a `hyperdb item wrapper`_
1465 **request**
1466 Includes information about the current request, including:
1467 - the current index information (``filterspec``, ``filter`` args,
1468 ``properties``, etc) parsed out of the form.
1469 - methods for easy filterspec link generation
1470 - *user*, the current user item as an HTMLItem instance
1471 - *form*
1472 The current CGI form information as a mapping of form argument name
1473 to value
1474 **config**
1475 This variable holds all the values defined in the tracker config.py
1476 file (eg. TRACKER_NAME, etc.)
1477 **db**
1478 The current database, used to access arbitrary database items.
1479 **templates**
1480 Access to all the tracker templates by name. Used mainly in
1481 *use-macro* commands.
1482 **utils**
1483 This variable makes available some utility functions like batching.
1484 **nothing**
1485 This is a special variable - if an expression evaluates to this, then
1486 the tag (in the case of a ``tal:replace``), its contents (in the case
1487 of ``tal:content``) or some attributes (in the case of
1488 ``tal:attributes``) will not appear in the the output. So, for
1489 example::
1491 <span tal:attributes="class nothing">Hello, World!</span>
1493 would result in::
1495 <span>Hello, World!</span>
1497 **default**
1498 Also a special variable - if an expression evaluates to this, then the
1499 existing HTML in the template will not be replaced or removed, it will
1500 remain. So::
1502 <span tal:replace="default">Hello, World!</span>
1504 would result in::
1506 <span>Hello, World!</span>
1509 The context variable
1510 ~~~~~~~~~~~~~~~~~~~~
1512 The *context* variable is one of three things based on the current
1513 context (see `determining web context`_ for how we figure this out):
1515 1. if we're looking at a "home" page, then it's None
1516 2. if we're looking at a specific hyperdb class, it's a
1517 `hyperdb class wrapper`_.
1518 3. if we're looking at a specific hyperdb item, it's a
1519 `hyperdb item wrapper`_.
1521 If the context is not None, we can access the properties of the class or
1522 item. The only real difference between cases 2 and 3 above are:
1524 1. the properties may have a real value behind them, and this will
1525 appear if the property is displayed through ``context/property`` or
1526 ``context/property/field``.
1527 2. the context's "id" property will be a false value in the second case,
1528 but a real, or true value in the third. Thus we can determine whether
1529 we're looking at a real item from the hyperdb by testing
1530 "context/id".
1532 Hyperdb class wrapper
1533 :::::::::::::::::::::
1535 Note: this is implemented by the ``roundup.cgi.templating.HTMLClass``
1536 class.
1538 This wrapper object provides access to a hyperb class. It is used
1539 primarily in both index view and new item views, but it's also usable
1540 anywhere else that you wish to access information about a class, or the
1541 items of a class, when you don't have a specific item of that class in
1542 mind.
1544 We allow access to properties. There will be no "id" property. The value
1545 accessed through the property will be the current value of the same name
1546 from the CGI form.
1548 There are several methods available on these wrapper objects:
1550 =========== =============================================================
1551 Method Description
1552 =========== =============================================================
1553 properties return a `hyperdb property wrapper`_ for all of this class's
1554 properties.
1555 list lists all of the active (not retired) items in the class.
1556 csv return the items of this class as a chunk of CSV text.
1557 propnames lists the names of the properties of this class.
1558 filter lists of items from this class, filtered and sorted by the
1559 current *request* filterspec/filter/sort/group args
1560 classhelp display a link to a javascript popup containing this class'
1561 "help" template.
1562 submit generate a submit button (and action hidden element)
1563 renderWith render this class with the given template.
1564 history returns 'New node - no history' :)
1565 is_edit_ok is the user allowed to Edit the current class?
1566 is_view_ok is the user allowed to View the current class?
1567 =========== =============================================================
1569 Note that if you have a property of the same name as one of the above
1570 methods, you'll need to access it using a python "item access"
1571 expression. For example::
1573 python:context['list']
1575 will access the "list" property, rather than the list method.
1578 Hyperdb item wrapper
1579 ::::::::::::::::::::
1581 Note: this is implemented by the ``roundup.cgi.templating.HTMLItem``
1582 class.
1584 This wrapper object provides access to a hyperb item.
1586 We allow access to properties. There will be no "id" property. The value
1587 accessed through the property will be the current value of the same name
1588 from the CGI form.
1590 There are several methods available on these wrapper objects:
1592 =============== ========================================================
1593 Method Description
1594 =============== ========================================================
1595 submit generate a submit button (and action hidden element)
1596 journal return the journal of the current item (**not
1597 implemented**)
1598 history render the journal of the current item as HTML
1599 renderQueryForm specific to the "query" class - render the search form
1600 for the query
1601 hasPermission specific to the "user" class - determine whether the
1602 user has a Permission
1603 is_edit_ok is the user allowed to Edit the current item?
1604 is_view_ok is the user allowed to View the current item?
1605 =============== ========================================================
1607 Note that if you have a property of the same name as one of the above
1608 methods, you'll need to access it using a python "item access"
1609 expression. For example::
1611 python:context['journal']
1613 will access the "journal" property, rather than the journal method.
1616 Hyperdb property wrapper
1617 ::::::::::::::::::::::::
1619 Note: this is implemented by subclasses of the
1620 ``roundup.cgi.templating.HTMLProperty`` class (``HTMLStringProperty``,
1621 ``HTMLNumberProperty``, and so on).
1623 This wrapper object provides access to a single property of a class. Its
1624 value may be either:
1626 1. if accessed through a `hyperdb item wrapper`_, then it's a value from
1627 the hyperdb
1628 2. if access through a `hyperdb class wrapper`_, then it's a value from
1629 the CGI form
1632 The property wrapper has some useful attributes:
1634 =============== ========================================================
1635 Attribute Description
1636 =============== ========================================================
1637 _name the name of the property
1638 _value the value of the property if any - this is the actual
1639 value retrieved from the hyperdb for this property
1640 =============== ========================================================
1642 There are several methods available on these wrapper objects:
1644 =========== ================================================================
1645 Method Description
1646 =========== ================================================================
1647 plain render a "plain" representation of the property. This method
1648 may take two arguments:
1650 escape
1651 If true, escape the text so it is HTML safe (default: no). The
1652 reason this defaults to off is that text is usually escaped
1653 at a later stage by the TAL commands, unless the "structure"
1654 option is used in the template. The following ``tal:content``
1655 expressions are all equivalent::
1657 "structure python:msg.content.plain(escape=1)"
1658 "python:msg.content.plain()"
1659 "msg/content/plain"
1660 "msg/content"
1662 Usually you'll only want to use the escape option in a
1663 complex expression.
1665 hyperlink
1666 If true, turn URLs, email addresses and hyperdb item
1667 designators in the text into hyperlinks (default: no). Note
1668 that you'll need to use the "structure" TAL option if you
1669 want to use this ``tal:content`` expression::
1671 "structure python:msg.content.plain(hyperlink=1)"
1673 Note also that the text is automatically HTML-escaped before
1674 the hyperlinking transformation.
1675 hyperlinked The same as msg.content.plain(hyperlink=1), but nicer::
1677 "structure msg/content/hyperlinked"
1679 field render an appropriate form edit field for the property - for
1680 most types this is a text entry box, but for Booleans it's a
1681 tri-state yes/no/neither selection.
1682 stext only on String properties - render the value of the property
1683 as StructuredText (requires the StructureText module to be
1684 installed separately)
1685 multiline only on String properties - render a multiline form edit
1686 field for the property
1687 email only on String properties - render the value of the property
1688 as an obscured email address
1689 confirm only on Password properties - render a second form edit field
1690 for the property, used for confirmation that the user typed
1691 the password correctly. Generates a field with name
1692 "name:confirm".
1693 now only on Date properties - return the current date as a new
1694 property
1695 reldate only on Date properties - render the interval between the date
1696 and now
1697 local only on Date properties - return this date as a new property
1698 with some timezone offset, for example::
1700 python:context.creation.local(10)
1702 will render the date with a +10 hour offset.
1703 pretty Date properties - render the date as "dd Mon YYYY" (eg. "19
1704 Mar 2004"). Takes an optional format argument, for example::
1706 python:context.activity.pretty('%Y-%m-%d')
1708 Will format as "2004-03-19" instead.
1710 Interval properties - render the interval in a pretty
1711 format (eg. "yesterday")
1712 menu only on Link and Multilink properties - render a form select
1713 list for this property
1714 reverse only on Multilink properties - produce a list of the linked
1715 items in reverse order
1716 =========== ================================================================
1718 All of the above functions perform checks for permissions required to
1719 display or edit the data they are manipulating. The simplest case is
1720 editing an issue title. Including the expression::
1722 context/title/field
1724 Will present the user with an edit field, if they have edit permission. If
1725 not, then they will be presented with a static display if they have view
1726 permission. If they don't even have view permission, then an error message
1727 is raised, preventing the display of the page, indicating that they don't
1728 have permission to view the information.
1731 The request variable
1732 ~~~~~~~~~~~~~~~~~~~~
1734 Note: this is implemented by the ``roundup.cgi.templating.HTMLRequest``
1735 class.
1737 The request variable is packed with information about the current
1738 request.
1740 .. taken from ``roundup.cgi.templating.HTMLRequest`` docstring
1742 =========== ============================================================
1743 Variable Holds
1744 =========== ============================================================
1745 form the CGI form as a cgi.FieldStorage
1746 env the CGI environment variables
1747 base the base URL for this tracker
1748 user a HTMLUser instance for this user
1749 classname the current classname (possibly None)
1750 template the current template (suffix, also possibly None)
1751 form the current CGI form variables in a FieldStorage
1752 =========== ============================================================
1754 **Index page specific variables (indexing arguments)**
1756 =========== ============================================================
1757 Variable Holds
1758 =========== ============================================================
1759 columns dictionary of the columns to display in an index page
1760 show a convenience access to columns - request/show/colname will
1761 be true if the columns should be displayed, false otherwise
1762 sort index sort column (direction, column name)
1763 group index grouping property (direction, column name)
1764 filter properties to filter the index on
1765 filterspec values to filter the index on
1766 search_text text to perform a full-text search on for an index
1767 =========== ============================================================
1769 There are several methods available on the request variable:
1771 =============== ========================================================
1772 Method Description
1773 =============== ========================================================
1774 description render a description of the request - handle for the
1775 page title
1776 indexargs_form render the current index args as form elements
1777 indexargs_url render the current index args as a URL
1778 base_javascript render some javascript that is used by other components
1779 of the templating
1780 batch run the current index args through a filter and return a
1781 list of items (see `hyperdb item wrapper`_, and
1782 `batching`_)
1783 =============== ========================================================
1785 The form variable
1786 :::::::::::::::::
1788 The form variable is a bit special because it's actually a python
1789 FieldStorage object. That means that you have two ways to access its
1790 contents. For example, to look up the CGI form value for the variable
1791 "name", use the path expression::
1793 request/form/name/value
1795 or the python expression::
1797 python:request.form['name'].value
1799 Note the "item" access used in the python case, and also note the
1800 explicit "value" attribute we have to access. That's because the form
1801 variables are stored as MiniFieldStorages. If there's more than one
1802 "name" value in the form, then the above will break since
1803 ``request/form/name`` is actually a *list* of MiniFieldStorages. So it's
1804 best to know beforehand what you're dealing with.
1807 The db variable
1808 ~~~~~~~~~~~~~~~
1810 Note: this is implemented by the ``roundup.cgi.templating.HTMLDatabase``
1811 class.
1813 Allows access to all hyperdb classes as attributes of this variable. If
1814 you want access to the "user" class, for example, you would use::
1816 db/user
1817 python:db.user
1819 Also, the current id of the current user is available as
1820 ``db.getuid()``. This isn't so useful in templates (where you have
1821 ``request/user``), but it can be useful in detectors or interfaces.
1823 The access results in a `hyperdb class wrapper`_.
1826 The templates variable
1827 ~~~~~~~~~~~~~~~~~~~~~~
1829 Note: this is implemented by the ``roundup.cgi.templating.Templates``
1830 class.
1832 This variable doesn't have any useful methods defined. It supports being
1833 used in expressions to access the templates, and consequently the
1834 template macros. You may access the templates using the following path
1835 expression::
1837 templates/name
1839 or the python expression::
1841 templates[name]
1843 where "name" is the name of the template you wish to access. The
1844 template has one useful attribute, namely "macros". To access a specific
1845 macro (called "macro_name"), use the path expression::
1847 templates/name/macros/macro_name
1849 or the python expression::
1851 templates[name].macros[macro_name]
1854 The utils variable
1855 ~~~~~~~~~~~~~~~~~~
1857 Note: this is implemented by the
1858 ``roundup.cgi.templating.TemplatingUtils`` class, but it may be extended
1859 as described below.
1861 =============== ========================================================
1862 Method Description
1863 =============== ========================================================
1864 Batch return a batch object using the supplied list
1865 =============== ========================================================
1867 You may add additional utility methods by writing them in your tracker
1868 ``interfaces.py`` module's ``TemplatingUtils`` class. See `adding a time
1869 log to your issues`_ for an example. The TemplatingUtils class itself
1870 will have a single attribute, ``client``, which may be used to access
1871 the ``client.db`` when you need to perform arbitrary database queries.
1873 Batching
1874 ::::::::
1876 Use Batch to turn a list of items, or item ids of a given class, into a
1877 series of batches. Its usage is::
1879 python:utils.Batch(sequence, size, start, end=0, orphan=0,
1880 overlap=0)
1882 or, to get the current index batch::
1884 request/batch
1886 The parameters are:
1888 ========= ==============================================================
1889 Parameter Usage
1890 ========= ==============================================================
1891 sequence a list of HTMLItems
1892 size how big to make the sequence.
1893 start where to start (0-indexed) in the sequence.
1894 end where to end (0-indexed) in the sequence.
1895 orphan if the next batch would contain less items than this value,
1896 then it is combined with this batch
1897 overlap the number of items shared between adjacent batches
1898 ========= ==============================================================
1900 All of the parameters are assigned as attributes on the batch object. In
1901 addition, it has several more attributes:
1903 =============== ========================================================
1904 Attribute Description
1905 =============== ========================================================
1906 start indicates the start index of the batch. *Note: unlike
1907 the argument, is a 1-based index (I know, lame)*
1908 first indicates the start index of the batch *as a 0-based
1909 index*
1910 length the actual number of elements in the batch
1911 sequence_length the length of the original, unbatched, sequence.
1912 =============== ========================================================
1914 And several methods:
1916 =============== ========================================================
1917 Method Description
1918 =============== ========================================================
1919 previous returns a new Batch with the previous batch settings
1920 next returns a new Batch with the next batch settings
1921 propchanged detect if the named property changed on the current item
1922 when compared to the last item
1923 =============== ========================================================
1925 An example of batching::
1927 <table class="otherinfo">
1928 <tr><th colspan="4" class="header">Existing Keywords</th></tr>
1929 <tr tal:define="keywords db/keyword/list"
1930 tal:repeat="start python:range(0, len(keywords), 4)">
1931 <td tal:define="batch python:utils.Batch(keywords, 4, start)"
1932 tal:repeat="keyword batch" tal:content="keyword/name">
1933 keyword here</td>
1934 </tr>
1935 </table>
1937 ... which will produce a table with four columns containing the items of
1938 the "keyword" class (well, their "name" anyway).
1940 Displaying Properties
1941 ---------------------
1943 Properties appear in the user interface in three contexts: in indices,
1944 in editors, and as search arguments. For each type of property, there
1945 are several display possibilities. For example, in an index view, a
1946 string property may just be printed as a plain string, but in an editor
1947 view, that property may be displayed in an editable field.
1950 Index Views
1951 -----------
1953 This is one of the class context views. It is also the default view for
1954 classes. The template used is "*classname*.index".
1957 Index View Specifiers
1958 ~~~~~~~~~~~~~~~~~~~~~
1960 An index view specifier (URL fragment) looks like this (whitespace has
1961 been added for clarity)::
1963 /issue?status=unread,in-progress,resolved&
1964 topic=security,ui&
1965 :group=+priority&
1966 :sort==activity&
1967 :filters=status,topic&
1968 :columns=title,status,fixer
1970 The index view is determined by two parts of the specifier: the layout
1971 part and the filter part. The layout part consists of the query
1972 parameters that begin with colons, and it determines the way that the
1973 properties of selected items are displayed. The filter part consists of
1974 all the other query parameters, and it determines the criteria by which
1975 items are selected for display. The filter part is interactively
1976 manipulated with the form widgets displayed in the filter section. The
1977 layout part is interactively manipulated by clicking on the column
1978 headings in the table.
1980 The filter part selects the union of the sets of items with values
1981 matching any specified Link properties and the intersection of the sets
1982 of items with values matching any specified Multilink properties.
1984 The example specifies an index of "issue" items. Only items with a
1985 "status" of either "unread" or "in-progress" or "resolved" are
1986 displayed, and only items with "topic" values including both "security"
1987 and "ui" are displayed. The items are grouped by priority, arranged in
1988 ascending order; and within groups, sorted by activity, arranged in
1989 descending order. The filter section shows filters for the "status" and
1990 "topic" properties, and the table includes columns for the "title",
1991 "status", and "fixer" properties.
1993 Searching Views
1994 ---------------
1996 Note: if you add a new column to the ``:columns`` form variable
1997 potentials then you will need to add the column to the appropriate
1998 `index views`_ template so that it is actually displayed.
2000 This is one of the class context views. The template used is typically
2001 "*classname*.search". The form on this page should have "search" as its
2002 ``@action`` variable. The "search" action:
2004 - sets up additional filtering, as well as performing indexed text
2005 searching
2006 - sets the ``:filter`` variable correctly
2007 - saves the query off if ``:query_name`` is set.
2009 The search page should lay out any fields that you wish to allow the
2010 user to search on. If your schema contains a large number of properties,
2011 you should be wary of making all of those properties available for
2012 searching, as this can cause confusion. If the additional properties are
2013 Strings, consider having their value indexed, and then they will be
2014 searchable using the full text indexed search. This is both faster, and
2015 more useful for the end user.
2017 The two special form values on search pages which are handled by the
2018 "search" action are:
2020 :search_text
2021 Text with which to perform a search of the text index. Results from
2022 that search will be used to limit the results of other filters (using
2023 an intersection operation)
2024 :query_name
2025 If supplied, the search parameters (including :search_text) will be
2026 saved off as a the query item and registered against the user's
2027 queries property. Note that the *classic* template schema has this
2028 ability, but the *minimal* template schema does not.
2031 Item Views
2032 ----------
2034 The basic view of a hyperdb item is provided by the "*classname*.item"
2035 template. It generally has three sections; an "editor", a "spool" and a
2036 "history" section.
2039 Editor Section
2040 ~~~~~~~~~~~~~~
2042 The editor section is used to manipulate the item - it may be a static
2043 display if the user doesn't have permission to edit the item.
2045 Here's an example of a basic editor template (this is the default
2046 "classic" template issue item edit form - from the "issue.item.html"
2047 template)::
2049 <table class="form">
2050 <tr>
2051 <th>Title</th>
2052 <td colspan="3" tal:content="structure python:context.title.field(size=60)">title</td>
2053 </tr>
2055 <tr>
2056 <th>Priority</th>
2057 <td tal:content="structure context/priority/menu">priority</td>
2058 <th>Status</th>
2059 <td tal:content="structure context/status/menu">status</td>
2060 </tr>
2062 <tr>
2063 <th>Superseder</th>
2064 <td>
2065 <span tal:replace="structure python:context.superseder.field(showid=1, size=20)" />
2066 <span tal:replace="structure python:db.issue.classhelp('id,title')" />
2067 <span tal:condition="context/superseder">
2068 <br>View: <span tal:replace="structure python:context.superseder.link(showid=1)" />
2069 </span>
2070 </td>
2071 <th>Nosy List</th>
2072 <td>
2073 <span tal:replace="structure context/nosy/field" />
2074 <span tal:replace="structure python:db.user.classhelp('username,realname,address,phone')" />
2075 </td>
2076 </tr>
2078 <tr>
2079 <th>Assigned To</th>
2080 <td tal:content="structure context/assignedto/menu">
2081 assignedto menu
2082 </td>
2083 <td> </td>
2084 <td> </td>
2085 </tr>
2087 <tr>
2088 <th>Change Note</th>
2089 <td colspan="3">
2090 <textarea name=":note" wrap="hard" rows="5" cols="60"></textarea>
2091 </td>
2092 </tr>
2094 <tr>
2095 <th>File</th>
2096 <td colspan="3"><input type="file" name=":file" size="40"></td>
2097 </tr>
2099 <tr>
2100 <td> </td>
2101 <td colspan="3" tal:content="structure context/submit">
2102 submit button will go here
2103 </td>
2104 </tr>
2105 </table>
2108 When a change is submitted, the system automatically generates a message
2109 describing the changed properties. As shown in the example, the editor
2110 template can use the ":note" and ":file" fields, which are added to the
2111 standard changenote message generated by Roundup.
2114 Form values
2115 :::::::::::
2117 We have a number of ways to pull properties out of the form in order to
2118 meet the various needs of:
2120 1. editing the current item (perhaps an issue item)
2121 2. editing information related to the current item (eg. messages or
2122 attached files)
2123 3. creating new information to be linked to the current item (eg. time
2124 spent on an issue)
2126 In the following, ``<bracketed>`` values are variable, ":" may be one of
2127 ":" or "@", and other text ("required") is fixed.
2129 Properties are specified as form variables:
2131 ``<propname>``
2132 property on the current context item
2134 ``<designator>:<propname>``
2135 property on the indicated item (for editing related information)
2137 ``<classname>-<N>:<propname>``
2138 property on the Nth new item of classname (generally for creating new
2139 items to attach to the current item)
2141 Once we have determined the "propname", we check to see if it is one of
2142 the special form values:
2144 ``@required``
2145 The named property values must be supplied or a ValueError will be
2146 raised.
2148 ``@remove@<propname>=id(s)``
2149 The ids will be removed from the multilink property.
2151 ``:add:<propname>=id(s)``
2152 The ids will be added to the multilink property.
2154 ``:link:<propname>=<designator>``
2155 Used to add a link to new items created during edit. These are
2156 collected and returned in ``all_links``. This will result in an
2157 additional linking operation (either Link set or Multilink append)
2158 after the edit/create is done using ``all_props`` in ``_editnodes``.
2159 The <propname> on the current item will be set/appended the id of the
2160 newly created item of class <designator> (where <designator> must be
2161 <classname>-<N>).
2163 Any of the form variables may be prefixed with a classname or
2164 designator.
2166 Two special form values are supported for backwards compatibility:
2168 ``:note``
2169 create a message (with content, author and date), linked to the
2170 context item. This is ALWAYS designated "msg-1".
2171 ``:file``
2172 create a file, attached to the current item and any message created by
2173 :note. This is ALWAYS designated "file-1".
2176 Spool Section
2177 ~~~~~~~~~~~~~
2179 The spool section lists related information like the messages and files
2180 of an issue.
2182 TODO
2185 History Section
2186 ~~~~~~~~~~~~~~~
2188 The final section displayed is the history of the item - its database
2189 journal. This is generally generated with the template::
2191 <tal:block tal:replace="structure context/history" />
2193 *To be done:*
2195 *The actual history entries of the item may be accessed for manual
2196 templating through the "journal" method of the item*::
2198 <tal:block tal:repeat="entry context/journal">
2199 a journal entry
2200 </tal:block>
2202 *where each journal entry is an HTMLJournalEntry.*
2204 Defining new web actions
2205 ------------------------
2207 You may define new actions to be triggered by the ``@action`` form variable.
2208 These are added to the tracker ``interfaces.py`` as ``Action`` classes that get
2209 called by the the ``Client`` class.
2211 Adding action classes takes three steps; first you `define the new
2212 action class`_, then you `register the action class`_ with the cgi
2213 interface so it may be triggered by the ``@action`` form variable.
2214 Finally you `use the new action`_ in your HTML form.
2216 See "`setting up a "wizard" (or "druid") for controlled adding of
2217 issues`_" for an example.
2220 Define the new action class
2221 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
2223 The action classes have the following interface::
2225 class MyAction(Action):
2226 def handle(self):
2227 ''' Perform some action. No return value is required.
2228 '''
2230 The *self.client* attribute is an instance of your tracker ``instance.Client``
2231 class - thus it's mostly implemented by ``roundup.cgi.client.Client``. See the
2232 docstring of that class for details of what it can do.
2234 The method will typically check the ``self.form`` variable's contents.
2235 It may then:
2237 - add information to ``self.client.ok_message`` or ``self.client.error_message``
2238 - change the ``self.client.template`` variable to alter what the user will see
2239 next
2240 - raise Unauthorised, SendStaticFile, SendFile, NotFound or Redirect
2241 exceptions (import them from roundup.cgi.exceptions)
2244 Register the action class
2245 ~~~~~~~~~~~~~~~~~~~~~~~~~~
2247 The class is now written, but isn't available to the user until you add it to
2248 the ``instance.Client`` class ``actions`` variable, like so::
2250 actions = client.Client.actions + (
2251 ('myaction', myActionClass),
2252 )
2254 This maps the action name "myaction" to the action class we defined.
2256 Use the new action
2257 ~~~~~~~~~~~~~~~~~~
2259 In your HTML form, add a hidden form element like so::
2261 <input type="hidden" name="@action" value="myaction">
2263 where "myaction" is the name you registered in the previous step.
2265 Actions may return content to the user
2266 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
2268 Actions generally perform some database manipulation and then pass control
2269 on to the rendering of a template in the current context (see `Determining
2270 web context`_ for how that works.) Some actions will want to generate the
2271 actual content returned to the user. Action methods may return their own
2272 content string to be displayed to the user, overriding the templating step.
2273 In this situation, we assume that the content is HTML by default. You may
2274 override the content type indicated to the user by calling ``setHeader``::
2276 self.client.setHeader('Content-Type', 'text/csv')
2278 This example indicates that the value sent back to the user is actually
2279 comma-separated value content (eg. something to be loaded into a
2280 spreadsheet or database).
2283 Examples
2284 ========
2286 .. contents::
2287 :local:
2288 :depth: 1
2291 Adding a new field to the classic schema
2292 ----------------------------------------
2294 This example shows how to add a new constrained property (i.e. a
2295 selection of distinct values) to your tracker.
2298 Introduction
2299 ~~~~~~~~~~~~
2301 To make the classic schema of roundup useful as a TODO tracking system
2302 for a group of systems administrators, it needed an extra data field per
2303 issue: a category.
2305 This would let sysadmins quickly list all TODOs in their particular area
2306 of interest without having to do complex queries, and without relying on
2307 the spelling capabilities of other sysadmins (a losing proposition at
2308 best).
2311 Adding a field to the database
2312 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
2314 This is the easiest part of the change. The category would just be a
2315 plain string, nothing fancy. To change what is in the database you need
2316 to add some lines to the ``open()`` function in ``dbinit.py``. Under the
2317 comment::
2319 # add any additional database schema configuration here
2321 add::
2323 category = Class(db, "category", name=String())
2324 category.setkey("name")
2326 Here we are setting up a chunk of the database which we are calling
2327 "category". It contains a string, which we are refering to as "name" for
2328 lack of a more imaginative title. (Since "name" is one of the properties
2329 that Roundup looks for on items if you do not set a key for them, it's
2330 probably a good idea to stick with it for new classes if at all
2331 appropriate.) Then we are setting the key of this chunk of the database
2332 to be that "name". This is equivalent to an index for database types.
2333 This also means that there can only be one category with a given name.
2335 Adding the above lines allows us to create categories, but they're not
2336 tied to the issues that we are going to be creating. It's just a list of
2337 categories off on its own, which isn't much use. We need to link it in
2338 with the issues. To do that, find the lines in the ``open()`` function
2339 in ``dbinit.py`` which set up the "issue" class, and then add a link to
2340 the category::
2342 issue = IssueClass(db, "issue", ... ,
2343 category=Multilink("category"), ... )
2345 The ``Multilink()`` means that each issue can have many categories. If
2346 you were adding something with a one-to-one relationship to issues (such
2347 as the "assignedto" property), use ``Link()`` instead.
2349 That is all you need to do to change the schema. The rest of the effort
2350 is fiddling around so you can actually use the new category.
2353 Populating the new category class
2354 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
2356 If you haven't initialised the database with the roundup-admin
2357 "initialise" command, then you can add the following to the tracker
2358 ``dbinit.py`` in the ``init()`` function under the comment::
2360 # add any additional database create steps here - but only if you
2361 # haven't initialised the database with the admin "initialise" command
2363 Add::
2365 category = db.getclass('category')
2366 category.create(name="scipy", order="1")
2367 category.create(name="chaco", order="2")
2368 category.create(name="weave", order="3")
2370 If the database has already been initalised, then you need to use the
2371 ``roundup-admin`` tool::
2373 % roundup-admin -i <tracker home>
2374 Roundup <version> ready for input.
2375 Type "help" for help.
2376 roundup> create category name=scipy order=1
2377 1
2378 roundup> create category name=chaco order=1
2379 2
2380 roundup> create category name=weave order=1
2381 3
2382 roundup> exit...
2383 There are unsaved changes. Commit them (y/N)? y
2385 TODO: explain why order=1 in each case. Also, does key get set to "name"
2386 automatically when added via roundup-admin?
2389 Setting up security on the new objects
2390 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
2392 By default only the admin user can look at and change objects. This
2393 doesn't suit us, as we want any user to be able to create new categories
2394 as required, and obviously everyone needs to be able to view the
2395 categories of issues for it to be useful.
2397 We therefore need to change the security of the category objects. This
2398 is also done in the ``open()`` function of ``dbinit.py``.
2400 There are currently two loops which set up permissions and then assign
2401 them to various roles. Simply add the new "category" to both lists::
2403 # new permissions for this schema
2404 for cl in 'issue', 'file', 'msg', 'user', 'category':
2405 db.security.addPermission(name="Edit", klass=cl,
2406 description="User is allowed to edit "+cl)
2407 db.security.addPermission(name="View", klass=cl,
2408 description="User is allowed to access "+cl)
2410 # Assign the access and edit permissions for issue, file and message
2411 # to regular users now
2412 for cl in 'issue', 'file', 'msg', 'category':
2413 p = db.security.getPermission('View', cl)
2414 db.security.addPermissionToRole('User', p)
2415 p = db.security.getPermission('Edit', cl)
2416 db.security.addPermissionToRole('User', p)
2418 So you are in effect doing the following (with 'cl' substituted by its
2419 value)::
2421 db.security.addPermission(name="Edit", klass='category',
2422 description="User is allowed to edit "+'category')
2423 db.security.addPermission(name="View", klass='category',
2424 description="User is allowed to access "+'category')
2426 which is creating two permission types; that of editing and viewing
2427 "category" objects respectively. Then the following lines assign those
2428 new permissions to the "User" role, so that normal users can view and
2429 edit "category" objects::
2431 p = db.security.getPermission('View', 'category')
2432 db.security.addPermissionToRole('User', p)
2434 p = db.security.getPermission('Edit', 'category')
2435 db.security.addPermissionToRole('User', p)
2437 This is all the work that needs to be done for the database. It will
2438 store categories, and let users view and edit them. Now on to the
2439 interface stuff.
2442 Changing the web left hand frame
2443 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
2445 We need to give the users the ability to create new categories, and the
2446 place to put the link to this functionality is in the left hand function
2447 bar, under the "Issues" area. The file that defines how this area looks
2448 is ``html/page``, which is what we are going to be editing next.
2450 If you look at this file you can see that it contains a lot of
2451 "classblock" sections which are chunks of HTML that will be included or
2452 excluded in the output depending on whether the condition in the
2453 classblock is met. Under the end of the classblock for issue is where we
2454 are going to add the category code::
2456 <p class="classblock"
2457 tal:condition="python:request.user.hasPermission('View', 'category')">
2458 <b>Categories</b><br>
2459 <a tal:condition="python:request.user.hasPermission('Edit', 'category')"
2460 href="category?@template=item">New Category<br></a>
2461 </p>
2463 The first two lines is the classblock definition, which sets up a
2464 condition that only users who have "View" permission for the "category"
2465 object will have this section included in their output. Next comes a
2466 plain "Categories" header in bold. Everyone who can view categories will
2467 get that.
2469 Next comes the link to the editing area of categories. This link will
2470 only appear if the condition - that the user has "Edit" permissions for
2471 the "category" objects - is matched. If they do have permission then
2472 they will get a link to another page which will let the user add new
2473 categories.
2475 Note that if you have permission to *view* but not to *edit* categories,
2476 then all you will see is a "Categories" header with nothing underneath
2477 it. This is obviously not very good interface design, but will do for
2478 now. I just claim that it is so I can add more links in this section
2479 later on. However to fix the problem you could change the condition in
2480 the classblock statement, so that only users with "Edit" permission
2481 would see the "Categories" stuff.
2484 Setting up a page to edit categories
2485 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
2487 We defined code in the previous section which let users with the
2488 appropriate permissions see a link to a page which would let them edit
2489 conditions. Now we have to write that page.
2491 The link was for the *item* template of the *category* object. This
2492 translates into Roundup looking for a file called ``category.item.html``
2493 in the ``html`` tracker directory. This is the file that we are going to
2494 write now.
2496 First we add an info tag in a comment which doesn't affect the outcome
2497 of the code at all, but is useful for debugging. If you load a page in a
2498 browser and look at the page source, you can see which sections come
2499 from which files by looking for these comments::
2501 <!-- category.item -->
2503 Next we need to add in the METAL macro stuff so we get the normal page
2504 trappings::
2506 <tal:block metal:use-macro="templates/page/macros/icing">
2507 <title metal:fill-slot="head_title">Category editing</title>
2508 <td class="page-header-top" metal:fill-slot="body_title">
2509 <h2>Category editing</h2>
2510 </td>
2511 <td class="content" metal:fill-slot="content">
2513 Next we need to setup up a standard HTML form, which is the whole
2514 purpose of this file. We link to some handy javascript which sends the
2515 form through only once. This is to stop users hitting the send button
2516 multiple times when they are impatient and thus having the form sent
2517 multiple times::
2519 <form method="POST" onSubmit="return submit_once()"
2520 enctype="multipart/form-data">
2522 Next we define some code which sets up the minimum list of fields that
2523 we require the user to enter. There will be only one field - "name" - so
2524 they better put something in it, otherwise the whole form is pointless::
2526 <input type="hidden" name="@required" value="name">
2528 To get everything to line up properly we will put everything in a table,
2529 and put a nice big header on it so the user has an idea what is
2530 happening::
2532 <table class="form">
2533 <tr><th class="header" colspan="2">Category</th></tr>
2535 Next, we need the field into which the user is going to enter the new
2536 category. The "context.name.field(size=60)" bit tells Roundup to
2537 generate a normal HTML field of size 60, and the contents of that field
2538 will be the "name" variable of the current context (which is
2539 "category"). The upshot of this is that when the user types something in
2540 to the form, a new category will be created with that name::
2542 <tr>
2543 <th>Name</th>
2544 <td tal:content="structure python:context.name.field(size=60)">
2545 name</td>
2546 </tr>
2548 Then a submit button so that the user can submit the new category::
2550 <tr>
2551 <td> </td>
2552 <td colspan="3" tal:content="structure context/submit">
2553 submit button will go here
2554 </td>
2555 </tr>
2557 Finally we finish off the tags we used at the start to do the METAL
2558 stuff::
2560 </td>
2561 </tal:block>
2563 So putting it all together, and closing the table and form we get::
2565 <!-- category.item -->
2566 <tal:block metal:use-macro="templates/page/macros/icing">
2567 <title metal:fill-slot="head_title">Category editing</title>
2568 <td class="page-header-top" metal:fill-slot="body_title">
2569 <h2>Category editing</h2>
2570 </td>
2571 <td class="content" metal:fill-slot="content">
2572 <form method="POST" onSubmit="return submit_once()"
2573 enctype="multipart/form-data">
2575 <table class="form">
2576 <tr><th class="header" colspan="2">Category</th></tr>
2578 <tr>
2579 <th>Name</th>
2580 <td tal:content="structure python:context.name.field(size=60)">
2581 name</td>
2582 </tr>
2584 <tr>
2585 <td>
2586
2587 <input type="hidden" name="@required" value="name">
2588 </td>
2589 <td colspan="3" tal:content="structure context/submit">
2590 submit button will go here
2591 </td>
2592 </tr>
2593 </table>
2594 </form>
2595 </td>
2596 </tal:block>
2598 This is quite a lot to just ask the user one simple question, but there
2599 is a lot of setup for basically one line (the form line) to do its work.
2600 To add another field to "category" would involve one more line (well,
2601 maybe a few extra to get the formatting correct).
2604 Adding the category to the issue
2605 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
2607 We now have the ability to create issues to our heart's content, but
2608 that is pointless unless we can assign categories to issues. Just like
2609 the ``html/category.item.html`` file was used to define how to add a new
2610 category, the ``html/issue.item.html`` is used to define how a new issue
2611 is created.
2613 Just like ``category.issue.html`` this file defines a form which has a
2614 table to lay things out. It doesn't matter where in the table we add new
2615 stuff, it is entirely up to your sense of aesthetics::
2617 <th>Category</th>
2618 <td><span tal:replace="structure context/category/field" />
2619 <span tal:replace="structure db/category/classhelp" />
2620 </td>
2622 First, we define a nice header so that the user knows what the next
2623 section is, then the middle line does what we are most interested in.
2624 This ``context/category/field`` gets replaced by a field which contains
2625 the category in the current context (the current context being the new
2626 issue).
2628 The classhelp lines generate a link (labelled "list") to a popup window
2629 which contains the list of currently known categories.
2632 Searching on categories
2633 ~~~~~~~~~~~~~~~~~~~~~~~
2635 We can add categories, and create issues with categories. The next
2636 obvious thing that we would like to be able to do, would be to search
2637 for issues based on their category, so that, for example, anyone working
2638 on the web server could look at all issues in the category "Web".
2640 If you look for "Search Issues" in the 'html/page.html' file, you will
2641 find that it looks something like
2642 ``<a href="issue?@template=search">Search Issues</a>``. This shows us
2643 that when you click on "Search Issues" it will be looking for a
2644 ``issue.search.html`` file to display. So that is the file that we will
2645 change.
2647 If you look at this file it should be starting to seem familiar, although it
2648 does use some new macros. You can add the new category search code anywhere you
2649 like within that form::
2651 <tr tal:define="name string:category;
2652 db_klass string:category;
2653 db_content string:name;">
2654 <th>Priority:</th>
2655 <td metal:use-macro="search_select"></td>
2656 <td metal:use-macro="column_input"></td>
2657 <td metal:use-macro="sort_input"></td>
2658 <td metal:use-macro="group_input"></td>
2659 </tr>
2661 The definitions in the <tr> opening tag are used by the macros:
2663 - search_select expands to a drop-down box with all categories using db_klass
2664 and db_content.
2665 - column_input expands to a checkbox for selecting what columns should be
2666 displayed.
2667 - sort_input expands to a radio button for selecting what property should be
2668 sorted on.
2669 - group_input expands to a radio button for selecting what property should be
2670 group on.
2672 The category search code above would expand to the following::
2674 <tr>
2675 <th>Category:</th>
2676 <td>
2677 <select name="category">
2678 <option value="">don't care</option>
2679 <option value="">------------</option>
2680 <option value="1">scipy</option>
2681 <option value="2">chaco</option>
2682 <option value="3">weave</option>
2683 </select>
2684 </td>
2685 <td><input type="checkbox" name=":columns" value="category"></td>
2686 <td><input type="radio" name=":sort" value="category"></td>
2687 <td><input type="radio" name=":group" value="category"></td>
2688 </tr>
2690 Adding category to the default view
2691 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
2693 We can now add categories, add issues with categories, and search for
2694 issues based on categories. This is everything that we need to do;
2695 however, there is some more icing that we would like. I think the
2696 category of an issue is important enough that it should be displayed by
2697 default when listing all the issues.
2699 Unfortunately, this is a bit less obvious than the previous steps. The
2700 code defining how the issues look is in ``html/issue.index.html``. This
2701 is a large table with a form down at the bottom for redisplaying and so
2702 forth.
2704 Firstly we need to add an appropriate header to the start of the table::
2706 <th tal:condition="request/show/category">Category</th>
2708 The *condition* part of this statement is to avoid displaying the
2709 Category column if the user has selected not to see it.
2711 The rest of the table is a loop which will go through every issue that
2712 matches the display criteria. The loop variable is "i" - which means
2713 that every issue gets assigned to "i" in turn.
2715 The new part of code to display the category will look like this::
2717 <td tal:condition="request/show/category"
2718 tal:content="i/category"></td>
2720 The condition is the same as above: only display the condition when the
2721 user hasn't asked for it to be hidden. The next part is to set the
2722 content of the cell to be the category part of "i" - the current issue.
2724 Finally we have to edit ``html/page.html`` again. This time, we need to
2725 tell it that when the user clicks on "Unasigned Issues" or "All Issues",
2726 the category column should be included in the resulting list. If you
2727 scroll down the page file, you can see the links with lots of options.
2728 The option that we are interested in is the ``:columns=`` one which
2729 tells roundup which fields of the issue to display. Simply add
2730 "category" to that list and it all should work.
2733 Adding in state transition control
2734 ----------------------------------
2736 Sometimes tracker admins want to control the states that users may move
2737 issues to. You can do this by following these steps:
2739 1. make "status" a required variable. This is achieved by adding the
2740 following to the top of the form in the ``issue.item.html``
2741 template::
2743 <input type="hidden" name="@required" value="status">
2745 this will force users to select a status.
2747 2. add a Multilink property to the status class::
2749 stat = Class(db, "status", ... , transitions=Multilink('status'),
2750 ...)
2752 and then edit the statuses already created, either:
2754 a. through the web using the class list -> status class editor, or
2755 b. using the roundup-admin "set" command.
2757 3. add an auditor module ``checktransition.py`` in your tracker's
2758 ``detectors`` directory, for example::
2760 def checktransition(db, cl, nodeid, newvalues):
2761 ''' Check that the desired transition is valid for the "status"
2762 property.
2763 '''
2764 if not newvalues.has_key('status'):
2765 return
2766 current = cl.get(nodeid, 'status')
2767 new = newvalues['status']
2768 if new == current:
2769 return
2770 ok = db.status.get(current, 'transitions')
2771 if new not in ok:
2772 raise ValueError, 'Status not allowed to move from "%s" to "%s"'%(
2773 db.status.get(current, 'name'), db.status.get(new, 'name'))
2775 def init(db):
2776 db.issue.audit('set', checktransition)
2778 4. in the ``issue.item.html`` template, change the status editing bit
2779 from::
2781 <th>Status</th>
2782 <td tal:content="structure context/status/menu">status</td>
2784 to::
2786 <th>Status</th>
2787 <td>
2788 <select tal:condition="context/id" name="status">
2789 <tal:block tal:define="ok context/status/transitions"
2790 tal:repeat="state db/status/list">
2791 <option tal:condition="python:state.id in ok"
2792 tal:attributes="
2793 value state/id;
2794 selected python:state.id == context.status.id"
2795 tal:content="state/name"></option>
2796 </tal:block>
2797 </select>
2798 <tal:block tal:condition="not:context/id"
2799 tal:replace="structure context/status/menu" />
2800 </td>
2802 which displays only the allowed status to transition to.
2805 Displaying only message summaries in the issue display
2806 ------------------------------------------------------
2808 Alter the issue.item template section for messages to::
2810 <table class="messages" tal:condition="context/messages">
2811 <tr><th colspan="5" class="header">Messages</th></tr>
2812 <tr tal:repeat="msg context/messages">
2813 <td><a tal:attributes="href string:msg${msg/id}"
2814 tal:content="string:msg${msg/id}"></a></td>
2815 <td tal:content="msg/author">author</td>
2816 <td class="date" tal:content="msg/date/pretty">date</td>
2817 <td tal:content="msg/summary">summary</td>
2818 <td>
2819 <a tal:attributes="href string:?@remove@messages=${msg/id}&@action=edit">
2820 remove</a>
2821 </td>
2822 </tr>
2823 </table>
2825 Restricting the list of users that are assignable to a task
2826 -----------------------------------------------------------
2828 1. In your tracker's "dbinit.py", create a new Role, say "Developer"::
2830 db.security.addRole(name='Developer', description='A developer')
2832 2. Just after that, create a new Permission, say "Fixer", specific to
2833 "issue"::
2835 p = db.security.addPermission(name='Fixer', klass='issue',
2836 description='User is allowed to be assigned to fix issues')
2838 3. Then assign the new Permission to your "Developer" Role::
2840 db.security.addPermissionToRole('Developer', p)
2842 4. In the issue item edit page ("html/issue.item.html" in your tracker
2843 directory), use the new Permission in restricting the "assignedto"
2844 list::
2846 <select name="assignedto">
2847 <option value="-1">- no selection -</option>
2848 <tal:block tal:repeat="user db/user/list">
2849 <option tal:condition="python:user.hasPermission(
2850 'Fixer', context._classname)"
2851 tal:attributes="
2852 value user/id;
2853 selected python:user.id == context.assignedto"
2854 tal:content="user/realname"></option>
2855 </tal:block>
2856 </select>
2858 For extra security, you may wish to setup an auditor to enforce the
2859 Permission requirement (install this as "assignedtoFixer.py" in your
2860 tracker "detectors" directory)::
2862 def assignedtoMustBeFixer(db, cl, nodeid, newvalues):
2863 ''' Ensure the assignedto value in newvalues is a used with the
2864 Fixer Permission
2865 '''
2866 if not newvalues.has_key('assignedto'):
2867 # don't care
2868 return
2870 # get the userid
2871 userid = newvalues['assignedto']
2872 if not db.security.hasPermission('Fixer', userid, cl.classname):
2873 raise ValueError, 'You do not have permission to edit %s'%cl.classname
2875 def init(db):
2876 db.issue.audit('set', assignedtoMustBeFixer)
2877 db.issue.audit('create', assignedtoMustBeFixer)
2879 So now, if an edit action attempts to set "assignedto" to a user that
2880 doesn't have the "Fixer" Permission, the error will be raised.
2883 Setting up a "wizard" (or "druid") for controlled adding of issues
2884 ------------------------------------------------------------------
2886 1. Set up the page templates you wish to use for data input. My wizard
2887 is going to be a two-step process: first figuring out what category
2888 of issue the user is submitting, and then getting details specific to
2889 that category. The first page includes a table of help, explaining
2890 what the category names mean, and then the core of the form::
2892 <form method="POST" onSubmit="return submit_once()"
2893 enctype="multipart/form-data">
2894 <input type="hidden" name="@template" value="add_page1">
2895 <input type="hidden" name="@action" value="page1_submit">
2897 <strong>Category:</strong>
2898 <tal:block tal:replace="structure context/category/menu" />
2899 <input type="submit" value="Continue">
2900 </form>
2902 The next page has the usual issue entry information, with the
2903 addition of the following form fragments::
2905 <form method="POST" onSubmit="return submit_once()"
2906 enctype="multipart/form-data"
2907 tal:condition="context/is_edit_ok"
2908 tal:define="cat request/form/category/value">
2910 <input type="hidden" name="@template" value="add_page2">
2911 <input type="hidden" name="@required" value="title">
2912 <input type="hidden" name="category" tal:attributes="value cat">
2913 .
2914 .
2915 .
2916 </form>
2918 Note that later in the form, I test the value of "cat" include form
2919 elements that are appropriate. For example::
2921 <tal:block tal:condition="python:cat in '6 10 13 14 15 16 17'.split()">
2922 <tr>
2923 <th>Operating System</th>
2924 <td tal:content="structure context/os/field"></td>
2925 </tr>
2926 <tr>
2927 <th>Web Browser</th>
2928 <td tal:content="structure context/browser/field"></td>
2929 </tr>
2930 </tal:block>
2932 ... the above section will only be displayed if the category is one
2933 of 6, 10, 13, 14, 15, 16 or 17.
2935 3. Determine what actions need to be taken between the pages - these are
2936 usually to validate user choices and determine what page is next. Now encode
2937 those actions in a new ``Action`` class and insert hooks to those actions in
2938 the "actions" attribute on on the ``interfaces.Client`` class, like so (see
2939 `defining new web actions`_)::
2941 class Page1SubmitAction(Action):
2942 def handle(self):
2943 ''' Verify that the user has selected a category, and then move
2944 on to page 2.
2945 '''
2946 category = self.form['category'].value
2947 if category == '-1':
2948 self.error_message.append('You must select a category of report')
2949 return
2950 # everything's ok, move on to the next page
2951 self.template = 'add_page2'
2953 actions = client.Client.actions + (
2954 ('page1_submit', Page1SubmitAction),
2955 )
2957 4. Use the usual "new" action as the ``@action`` on the final page, and
2958 you're done (the standard context/submit method can do this for you).
2961 Using an external password validation source
2962 --------------------------------------------
2964 We have a centrally-managed password changing system for our users. This
2965 results in a UN*X passwd-style file that we use for verification of
2966 users. Entries in the file consist of ``name:password`` where the
2967 password is encrypted using the standard UN*X ``crypt()`` function (see
2968 the ``crypt`` module in your Python distribution). An example entry
2969 would be::
2971 admin:aamrgyQfDFSHw
2973 Each user of Roundup must still have their information stored in the Roundup
2974 database - we just use the passwd file to check their password. To do this, we
2975 need to override the standard ``verifyPassword`` method defined in
2976 ``roundup.cgi.actions.LoginAction`` and register the new class with our
2977 ``Client`` class in the tracker home ``interfaces.py`` module::
2979 from roundup.cgi.actions import LoginAction
2981 class ExternalPasswordLoginAction(LoginAction):
2982 def verifyPassword(self, userid, password):
2983 # get the user's username
2984 username = self.db.user.get(userid, 'username')
2986 # the passwords are stored in the "passwd.txt" file in the
2987 # tracker home
2988 file = os.path.join(self.db.config.TRACKER_HOME, 'passwd.txt')
2990 # see if we can find a match
2991 for ent in [line.strip().split(':') for line in
2992 open(file).readlines()]:
2993 if ent[0] == username:
2994 return crypt.crypt(password, ent[1][:2]) == ent[1]
2996 # user doesn't exist in the file
2997 return 0
2999 class Client(client.Client):
3000 actions = client.Client.actions + (
3001 ('login', ExternalPasswordLoginAction)
3002 )
3004 What this does is look through the file, line by line, looking for a
3005 name that matches.
3007 We also remove the redundant password fields from the ``user.item``
3008 template.
3011 Adding a "vacation" flag to users for stopping nosy messages
3012 ------------------------------------------------------------
3014 When users go on vacation and set up vacation email bouncing, you'll
3015 start to see a lot of messages come back through Roundup "Fred is on
3016 vacation". Not very useful, and relatively easy to stop.
3018 1. add a "vacation" flag to your users::
3020 user = Class(db, "user",
3021 username=String(), password=Password(),
3022 address=String(), realname=String(),
3023 phone=String(), organisation=String(),
3024 alternate_addresses=String(),
3025 roles=String(), queries=Multilink("query"),
3026 vacation=Boolean())
3028 2. So that users may edit the vacation flags, add something like the
3029 following to your ``user.item`` template::
3031 <tr>
3032 <th>On Vacation</th>
3033 <td tal:content="structure context/vacation/field">vacation</td>
3034 </tr>
3036 3. edit your detector ``nosyreactor.py`` so that the ``nosyreaction()``
3037 consists of::
3039 def nosyreaction(db, cl, nodeid, oldvalues):
3040 users = db.user
3041 messages = db.msg
3042 # send a copy of all new messages to the nosy list
3043 for msgid in determineNewMessages(cl, nodeid, oldvalues):
3044 try:
3045 # figure the recipient ids
3046 sendto = []
3047 seen_message = {}
3048 recipients = messages.get(msgid, 'recipients')
3049 for recipid in messages.get(msgid, 'recipients'):
3050 seen_message[recipid] = 1
3052 # figure the author's id, and indicate they've received
3053 # the message
3054 authid = messages.get(msgid, 'author')
3056 # possibly send the message to the author, as long as
3057 # they aren't anonymous
3058 if (db.config.MESSAGES_TO_AUTHOR == 'yes' and
3059 users.get(authid, 'username') != 'anonymous'):
3060 sendto.append(authid)
3061 seen_message[authid] = 1
3063 # now figure the nosy people who weren't recipients
3064 nosy = cl.get(nodeid, 'nosy')
3065 for nosyid in nosy:
3066 # Don't send nosy mail to the anonymous user (that
3067 # user shouldn't appear in the nosy list, but just
3068 # in case they do...)
3069 if users.get(nosyid, 'username') == 'anonymous':
3070 continue
3071 # make sure they haven't seen the message already
3072 if not seen_message.has_key(nosyid):
3073 # send it to them
3074 sendto.append(nosyid)
3075 recipients.append(nosyid)
3077 # generate a change note
3078 if oldvalues:
3079 note = cl.generateChangeNote(nodeid, oldvalues)
3080 else:
3081 note = cl.generateCreateNote(nodeid)
3083 # we have new recipients
3084 if sendto:
3085 # filter out the people on vacation
3086 sendto = [i for i in sendto
3087 if not users.get(i, 'vacation', 0)]
3089 # map userids to addresses
3090 sendto = [users.get(i, 'address') for i in sendto]
3092 # update the message's recipients list
3093 messages.set(msgid, recipients=recipients)
3095 # send the message
3096 cl.send_message(nodeid, msgid, note, sendto)
3097 except roundupdb.MessageSendError, message:
3098 raise roundupdb.DetectorError, message
3100 Note that this is the standard nosy reaction code, with the small
3101 addition of::
3103 # filter out the people on vacation
3104 sendto = [i for i in sendto if not users.get(i, 'vacation', 0)]
3106 which filters out the users that have the vacation flag set to true.
3109 Adding a time log to your issues
3110 --------------------------------
3112 We want to log the dates and amount of time spent working on issues, and
3113 be able to give a summary of the total time spent on a particular issue.
3115 1. Add a new class to your tracker ``dbinit.py``::
3117 # storage for time logging
3118 timelog = Class(db, "timelog", period=Interval())
3120 Note that we automatically get the date of the time log entry
3121 creation through the standard property "creation".
3123 2. Link to the new class from your issue class (again, in
3124 ``dbinit.py``)::
3126 issue = IssueClass(db, "issue",
3127 assignedto=Link("user"), topic=Multilink("keyword"),
3128 priority=Link("priority"), status=Link("status"),
3129 times=Multilink("timelog"))
3131 the "times" property is the new link to the "timelog" class.
3133 3. We'll need to let people add in times to the issue, so in the web
3134 interface we'll have a new entry field. This is a special field
3135 because unlike the other fields in the issue.item template, it
3136 affects a different item (a timelog item) and not the template's
3137 item, an issue. We have a special syntax for form fields that affect
3138 items other than the template default item (see the cgi
3139 documentation on `special form variables`_). In particular, we add a
3140 field to capture a new timelog item's perdiod::
3142 <tr>
3143 <th>Time Log</th>
3144 <td colspan=3><input type="text" name="timelog-1@period" />
3145 <br />(enter as '3y 1m 4d 2:40:02' or parts thereof)
3146 </td>
3147 </tr>
3149 and another hidden field that links that new timelog item (new
3150 because it's marked as having id "-1") to the issue item. It looks
3151 like this::
3153 <input type="hidden" name="@link@times" value="timelog-1" />
3155 On submission, the "-1" timelog item will be created and assigned a
3156 real item id. The "times" property of the issue will have the new id
3157 added to it.
3159 4. We want to display a total of the time log times that have been
3160 accumulated for an issue. To do this, we'll need to actually write
3161 some Python code, since it's beyond the scope of PageTemplates to
3162 perform such calculations. We do this by adding a method to the
3163 TemplatingUtils class in our tracker ``interfaces.py`` module::
3165 class TemplatingUtils:
3166 ''' Methods implemented on this class will be available to HTML
3167 templates through the 'utils' variable.
3168 '''
3169 def totalTimeSpent(self, times):
3170 ''' Call me with a list of timelog items (which have an
3171 Interval "period" property)
3172 '''
3173 total = Interval('0d')
3174 for time in times:
3175 total += time.period._value
3176 return total
3178 Replace the ``pass`` line if one appears in your TemplatingUtils
3179 class. As indicated in the docstrings, we will be able to access the
3180 ``totalTimeSpent`` method via the ``utils`` variable in our templates.
3182 5. Display the time log for an issue::
3184 <table class="otherinfo" tal:condition="context/times">
3185 <tr><th colspan="3" class="header">Time Log
3186 <tal:block
3187 tal:replace="python:utils.totalTimeSpent(context.times)" />
3188 </th></tr>
3189 <tr><th>Date</th><th>Period</th><th>Logged By</th></tr>
3190 <tr tal:repeat="time context/times">
3191 <td tal:content="time/creation"></td>
3192 <td tal:content="time/period"></td>
3193 <td tal:content="time/creator"></td>
3194 </tr>
3195 </table>
3197 I put this just above the Messages log in my issue display. Note our
3198 use of the ``totalTimeSpent`` method which will total up the times
3199 for the issue and return a new Interval. That will be automatically
3200 displayed in the template as text like "+ 1y 2:40" (1 year, 2 hours
3201 and 40 minutes).
3203 8. If you're using a persistent web server - roundup-server or
3204 mod_python for example - then you'll need to restart that to pick up
3205 the code changes. When that's done, you'll be able to use the new
3206 time logging interface.
3208 Using a UN*X passwd file as the user database
3209 ---------------------------------------------
3211 On some systems the primary store of users is the UN*X passwd file. It
3212 holds information on users such as their username, real name, password
3213 and primary user group.
3215 Roundup can use this store as its primary source of user information,
3216 but it needs additional information too - email address(es), roundup
3217 Roles, vacation flags, roundup hyperdb item ids, etc. Also, "retired"
3218 users must still exist in the user database, unlike some passwd files in
3219 which the users are removed when they no longer have access to a system.
3221 To make use of the passwd file, we therefore synchronise between the two
3222 user stores. We also use the passwd file to validate the user logins, as
3223 described in the previous example, `using an external password
3224 validation source`_. We keep the users lists in sync using a fairly
3225 simple script that runs once a day, or several times an hour if more
3226 immediate access is needed. In short, it:
3228 1. parses the passwd file, finding usernames, passwords and real names,
3229 2. compares that list to the current roundup user list:
3231 a. entries no longer in the passwd file are *retired*
3232 b. entries with mismatching real names are *updated*
3233 c. entries only exist in the passwd file are *created*
3235 3. send an email to administrators to let them know what's been done.
3237 The retiring and updating are simple operations, requiring only a call
3238 to ``retire()`` or ``set()``. The creation operation requires more
3239 information though - the user's email address and their roundup Roles.
3240 We're going to assume that the user's email address is the same as their
3241 login name, so we just append the domain name to that. The Roles are
3242 determined using the passwd group identifier - mapping their UN*X group
3243 to an appropriate set of Roles.
3245 The script to perform all this, broken up into its main components, is
3246 as follows. Firstly, we import the necessary modules and open the
3247 tracker we're to work on::
3249 import sys, os, smtplib
3250 from roundup import instance, date
3252 # open the tracker
3253 tracker_home = sys.argv[1]
3254 tracker = instance.open(tracker_home)
3256 Next we read in the *passwd* file from the tracker home::
3258 # read in the users
3259 file = os.path.join(tracker_home, 'users.passwd')
3260 users = [x.strip().split(':') for x in open(file).readlines()]
3262 Handle special users (those to ignore in the file, and those who don't
3263 appear in the file)::
3265 # users to not keep ever, pre-load with the users I know aren't
3266 # "real" users
3267 ignore = ['ekmmon', 'bfast', 'csrmail']
3269 # users to keep - pre-load with the roundup-specific users
3270 keep = ['comment_pool', 'network_pool', 'admin', 'dev-team',
3271 'cs_pool', 'anonymous', 'system_pool', 'automated']
3273 Now we map the UN*X group numbers to the Roles that users should have::
3275 roles = {
3276 '501': 'User,Tech', # tech
3277 '502': 'User', # finance
3278 '503': 'User,CSR', # customer service reps
3279 '504': 'User', # sales
3280 '505': 'User', # marketing
3281 }
3283 Now we do all the work. Note that the body of the script (where we have
3284 the tracker database open) is wrapped in a ``try`` / ``finally`` clause,
3285 so that we always close the database cleanly when we're finished. So, we
3286 now do all the work::
3288 # open the database
3289 db = tracker.open('admin')
3290 try:
3291 # store away messages to send to the tracker admins
3292 msg = []
3294 # loop over the users list read in from the passwd file
3295 for user,passw,uid,gid,real,home,shell in users:
3296 if user in ignore:
3297 # this user shouldn't appear in our tracker
3298 continue
3299 keep.append(user)
3300 try:
3301 # see if the user exists in the tracker
3302 uid = db.user.lookup(user)
3304 # yes, they do - now check the real name for correctness
3305 if real != db.user.get(uid, 'realname'):
3306 db.user.set(uid, realname=real)
3307 msg.append('FIX %s - %s'%(user, real))
3308 except KeyError:
3309 # nope, the user doesn't exist
3310 db.user.create(username=user, realname=real,
3311 address='%s@ekit-inc.com'%user, roles=roles[gid])
3312 msg.append('ADD %s - %s (%s)'%(user, real, roles[gid]))
3314 # now check that all the users in the tracker are also in our
3315 # "keep" list - retire those who aren't
3316 for uid in db.user.list():
3317 user = db.user.get(uid, 'username')
3318 if user not in keep:
3319 db.user.retire(uid)
3320 msg.append('RET %s'%user)
3322 # if we did work, then send email to the tracker admins
3323 if msg:
3324 # create the email
3325 msg = '''Subject: %s user database maintenance
3327 %s
3328 '''%(db.config.TRACKER_NAME, '\n'.join(msg))
3330 # send the email
3331 smtp = smtplib.SMTP(db.config.MAILHOST)
3332 addr = db.config.ADMIN_EMAIL
3333 smtp.sendmail(addr, addr, msg)
3335 # now we're done - commit the changes
3336 db.commit()
3337 finally:
3338 # always close the database cleanly
3339 db.close()
3341 And that's it!
3344 Using an LDAP database for user information
3345 -------------------------------------------
3347 A script that reads users from an LDAP store using
3348 http://python-ldap.sf.net/ and then compares the list to the users in the
3349 roundup user database would be pretty easy to write. You'd then have it run
3350 once an hour / day (or on demand if you can work that into your LDAP store
3351 workflow). See the example `Using a UN*X passwd file as the user database`_
3352 for more information about doing this.
3354 To authenticate off the LDAP store (rather than using the passwords in the
3355 roundup user database) you'd use the same python-ldap module inside an
3356 extension to the cgi interface. You'd do this by overriding the method called
3357 "verifyPassword" on the LoginAction class in your tracker's interfaces.py
3358 module (see `using an external password validation source`_). The method is
3359 implemented by default as::
3361 def verifyPassword(self, userid, password):
3362 ''' Verify the password that the user has supplied
3363 '''
3364 stored = self.db.user.get(self.userid, 'password')
3365 if password == stored:
3366 return 1
3367 if not password and not stored:
3368 return 1
3369 return 0
3371 So you could reimplement this as something like::
3373 def verifyPassword(self, userid, password):
3374 ''' Verify the password that the user has supplied
3375 '''
3376 # look up some unique LDAP information about the user
3377 username = self.db.user.get(self.userid, 'username')
3378 # now verify the password supplied against the LDAP store
3381 Enabling display of either message summaries or the entire messages
3382 -------------------------------------------------------------------
3384 This is pretty simple - all we need to do is copy the code from the
3385 example `displaying only message summaries in the issue display`_ into
3386 our template alongside the summary display, and then introduce a switch
3387 that shows either one or the other. We'll use a new form variable,
3388 ``@whole_messages`` to achieve this::
3390 <table class="messages" tal:condition="context/messages">
3391 <tal:block tal:condition="not:request/form/@whole_messages/value | python:0">
3392 <tr><th colspan="3" class="header">Messages</th>
3393 <th colspan="2" class="header">
3394 <a href="?@whole_messages=yes">show entire messages</a>
3395 </th>
3396 </tr>
3397 <tr tal:repeat="msg context/messages">
3398 <td><a tal:attributes="href string:msg${msg/id}"
3399 tal:content="string:msg${msg/id}"></a></td>
3400 <td tal:content="msg/author">author</td>
3401 <td class="date" tal:content="msg/date/pretty">date</td>
3402 <td tal:content="msg/summary">summary</td>
3403 <td>
3404 <a tal:attributes="href string:?@remove@messages=${msg/id}&@action=edit">remove</a>
3405 </td>
3406 </tr>
3407 </tal:block>
3409 <tal:block tal:condition="request/form/@whole_messages/value | python:0">
3410 <tr><th colspan="2" class="header">Messages</th>
3411 <th class="header">
3412 <a href="?@whole_messages=">show only summaries</a>
3413 </th>
3414 </tr>
3415 <tal:block tal:repeat="msg context/messages">
3416 <tr>
3417 <th tal:content="msg/author">author</th>
3418 <th class="date" tal:content="msg/date/pretty">date</th>
3419 <th style="text-align: right">
3420 (<a tal:attributes="href string:?@remove@messages=${msg/id}&@action=edit">remove</a>)
3421 </th>
3422 </tr>
3423 <tr><td colspan="3" tal:content="msg/content"></td></tr>
3424 </tal:block>
3425 </tal:block>
3426 </table>
3429 Blocking issues that depend on other issues
3430 -------------------------------------------
3432 We needed the ability to mark certain issues as "blockers" - that is,
3433 they can't be resolved until another issue (the blocker) they rely on is
3434 resolved. To achieve this:
3436 1. Create a new property on the issue Class,
3437 ``blockers=Multilink("issue")``. Edit your tracker's dbinit.py file.
3438 Where the "issue" class is defined, something like::
3440 issue = IssueClass(db, "issue",
3441 assignedto=Link("user"), topic=Multilink("keyword"),
3442 priority=Link("priority"), status=Link("status"))
3444 add the blockers entry like so::
3446 issue = IssueClass(db, "issue",
3447 blockers=Multilink("issue"),
3448 assignedto=Link("user"), topic=Multilink("keyword"),
3449 priority=Link("priority"), status=Link("status"))
3451 2. Add the new "blockers" property to the issue.item edit page, using
3452 something like::
3454 <th>Waiting On</th>
3455 <td>
3456 <span tal:replace="structure python:context.blockers.field(showid=1,
3457 size=20)" />
3458 <span tal:replace="structure python:db.issue.classhelp('id,title')" />
3459 <span tal:condition="context/blockers"
3460 tal:repeat="blk context/blockers">
3461 <br>View: <a tal:attributes="href string:issue${blk/id}"
3462 tal:content="blk/id"></a>
3463 </span>
3465 You'll need to fiddle with your item page layout to find an
3466 appropriate place to put it - I'll leave that fun part up to you.
3467 Just make sure it appears in the first table, possibly somewhere near
3468 the "superseders" field.
3470 3. Create a new detector module (attached) which enforces the rules:
3472 - issues may not be resolved if they have blockers
3473 - when a blocker is resolved, it's removed from issues it blocks
3475 The contents of the detector should be something like this::
3477 def blockresolution(db, cl, nodeid, newvalues):
3478 ''' If the issue has blockers, don't allow it to be resolved.
3479 '''
3480 if nodeid is None:
3481 blockers = []
3482 else:
3483 blockers = cl.get(nodeid, 'blockers')
3484 blockers = newvalues.get('blockers', blockers)
3486 # don't do anything if there's no blockers or the status hasn't
3487 # changed
3488 if not blockers or not newvalues.has_key('status'):
3489 return
3491 # get the resolved state ID
3492 resolved_id = db.status.lookup('resolved')
3494 # format the info
3495 u = db.config.TRACKER_WEB
3496 s = ', '.join(['<a href="%sissue%s">%s</a>'%(
3497 u,id,id) for id in blockers])
3498 if len(blockers) == 1:
3499 s = 'issue %s is'%s
3500 else:
3501 s = 'issues %s are'%s
3503 # ok, see if we're trying to resolve
3504 if newvalues['status'] == resolved_id:
3505 raise ValueError, "This issue can't be resolved until %s resolved."%s
3507 def resolveblockers(db, cl, nodeid, newvalues):
3508 ''' When we resolve an issue that's a blocker, remove it from the
3509 blockers list of the issue(s) it blocks.
3510 '''
3511 if not newvalues.has_key('status'):
3512 return
3514 # get the resolved state ID
3515 resolved_id = db.status.lookup('resolved')
3517 # interesting?
3518 if newvalues['status'] != resolved_id:
3519 return
3521 # yes - find all the blocked issues, if any, and remove me from
3522 # their blockers list
3523 issues = cl.find(blockers=nodeid)
3524 for issueid in issues:
3525 blockers = cl.get(issueid, 'blockers')
3526 if nodeid in blockers:
3527 blockers.remove(nodeid)
3528 cl.set(issueid, blockers=blockers)
3531 def init(db):
3532 # might, in an obscure situation, happen in a create
3533 db.issue.audit('create', blockresolution)
3534 db.issue.audit('set', blockresolution)
3536 # can only happen on a set
3537 db.issue.react('set', resolveblockers)
3539 Put the above code in a file called "blockers.py" in your tracker's
3540 "detectors" directory.
3542 4. Finally, and this is an optional step, modify the tracker web page
3543 URLs so they filter out issues with any blockers. You do this by
3544 adding an additional filter on "blockers" for the value "-1". For
3545 example, the existing "Show All" link in the "page" template (in the
3546 tracker's "html" directory) looks like this::
3548 <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>
3550 modify it to add the "blockers" info to the URL (note, both the
3551 ":filter" *and* "blockers" values must be specified)::
3553 <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>
3555 That's it. You should now be able to set blockers on your issues. Note
3556 that if you want to know whether an issue has any other issues dependent
3557 on it (i.e. it's in their blockers list) you can look at the journal
3558 history at the bottom of the issue page - look for a "link" event to
3559 another issue's "blockers" property.
3561 Add users to the nosy list based on the topic
3562 ---------------------------------------------
3564 We need the ability to automatically add users to the nosy list based
3565 on the occurence of a topic. Every user should be allowed to edit his
3566 own list of topics for which he wants to be added to the nosy list.
3568 Below will be showed that such a change can be performed with only
3569 minimal understanding of the roundup system, but with clever use
3570 of Copy and Paste.
3572 This requires three changes to the tracker: a change in the database to
3573 allow per-user recording of the lists of topics for which he wants to
3574 be put on the nosy list, a change in the user view allowing to edit
3575 this list of topics, and addition of an auditor which updates the nosy
3576 list when a topic is set.
3578 Adding the nosy topic list
3579 ~~~~~~~~~~~~~~~~~~~~~~~~~~
3581 The change in the database to make is that for any user there should be
3582 a list of topics for which he wants to be put on the nosy list. Adding
3583 a ``Multilink`` of ``keyword`` seem to fullfill this (note that within
3584 the code topics are called ``keywords``.) As such, all what has to be
3585 done is to add a new field to the definition of ``user`` within the
3586 file ``dbinit.py``. We will call this new field ``nosy_keywords``, and
3587 the updated definition of user will be::
3589 user = Class(db, "user",
3590 username=String(), password=Password(),
3591 address=String(), realname=String(),
3592 phone=String(), organisation=String(),
3593 alternate_addresses=String(),
3594 queries=Multilink('query'), roles=String(),
3595 timezone=String(),
3596 nosy_keywords=Multilink('keyword'))
3598 Changing the user view to allow changing the nosy topic list
3599 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
3601 We want any user to be able to change the list of topics for which
3602 he will by default be added to the nosy list. We choose to add this
3603 to the user view, as is generated by the file ``html/user.item.html``.
3604 We easily can
3605 see that the topic field in the issue view has very similar editting
3606 requirements as our nosy topics, both being a list of topics. As
3607 such, we search for Topics in ``issue.item.html``, and extract the
3608 associated parts from there. We add this to ``user.item.html`` at the
3609 bottom of the list of viewed items (i.e. just below the 'Alternate
3610 E-mail addresses' in the classic template)::
3612 <tr>
3613 <th>Nosy Topics</th>
3614 <td>
3615 <span tal:replace="structure context/nosy_keywords/field" />
3616 <span tal:replace="structure python:db.keyword.classhelp(property='nosy_keywords')" />
3617 </td>
3618 </tr>
3621 Addition of an auditor to update the nosy list
3622 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
3624 The more difficult part is the addition of the logic to actually
3625 at the users to the nosy list when it is required.
3626 The choice is made to perform this action when the topics on an
3627 item are set, including when an item is created.
3628 Here we choose to start out with a copy of the
3629 ``detectors/nosyreaction.py`` detector, which we copy to the file
3630 ``detectors/nosy_keyword_reaction.py``.
3631 This looks like a good start as it also adds users
3632 to the nosy list. A look through the code reveals that the
3633 ``nosyreaction`` function actually is sending the e-mail, which
3634 we do not need. As such, we can change the init function to::
3636 def init(db):
3637 db.issue.audit('create', update_kw_nosy)
3638 db.issue.audit('set', update_kw_nosy)
3640 After that we rename the ``updatenosy`` function to ``update_kw_nosy``.
3641 The first two blocks of code in that function relate to settings
3642 ``current`` to a combination of the old and new nosy lists. This
3643 functionality is left in the new auditor. The following block of
3644 code, which in ``updatenosy`` handled adding the assignedto user(s)
3645 to the nosy list, should be replaced by a block of code to add the
3646 interested users to the nosy list. We choose here to loop over all
3647 new topics, than loop over all users,
3648 and assign the user to the nosy list when the topic in the user's
3649 nosy_keywords. The next part in ``updatenosy``, adding the author
3650 and/or recipients of a message to the nosy list, obviously is not
3651 relevant here and thus is deleted from the new auditor. The last
3652 part, copying the new nosy list to newvalues, does not have to be changed.
3653 This brings the following function::
3655 def update_kw_nosy(db, cl, nodeid, newvalues):
3656 '''Update the nosy list for changes to the topics
3657 '''
3658 # nodeid will be None if this is a new node
3659 current = {}
3660 if nodeid is None:
3661 ok = ('new', 'yes')
3662 else:
3663 ok = ('yes',)
3664 # old node, get the current values from the node if they haven't
3665 # changed
3666 if not newvalues.has_key('nosy'):
3667 nosy = cl.get(nodeid, 'nosy')
3668 for value in nosy:
3669 if not current.has_key(value):
3670 current[value] = 1
3672 # if the nosy list changed in this transaction, init from the new value
3673 if newvalues.has_key('nosy'):
3674 nosy = newvalues.get('nosy', [])
3675 for value in nosy:
3676 if not db.hasnode('user', value):
3677 continue
3678 if not current.has_key(value):
3679 current[value] = 1
3681 # add users with topic in nosy_keywords to the nosy list
3682 if newvalues.has_key('topic') and newvalues['topic'] is not None:
3683 topic_ids = newvalues['topic']
3684 for topic in topic_ids:
3685 # loop over all users,
3686 # and assign user to nosy when topic in nosy_keywords
3687 for user_id in db.user.list():
3688 nosy_kw = db.user.get(user_id, "nosy_keywords")
3689 found = 0
3690 for kw in nosy_kw:
3691 if kw == topic:
3692 found = 1
3693 if found:
3694 current[user_id] = 1
3696 # that's it, save off the new nosy list
3697 newvalues['nosy'] = current.keys()
3699 and these two function are the only ones needed in the file.
3701 TODO: update this example to use the find() Class method.
3703 Caveats
3704 ~~~~~~~
3706 A few problems with the design here can be noted:
3708 Multiple additions
3709 When a user, after automatic selection, is manually removed
3710 from the nosy list, he again is added to the nosy list when the
3711 topic list of the issue is updated. A better design might be
3712 to only check which topics are new compared to the old list
3713 of topics, and only add users when they have indicated
3714 interest on a new topic.
3716 The code could also be changed to only trigger on the create() event,
3717 rather than also on the set() event, thus only setting the nosy list
3718 when the issue is created.
3720 Scalability
3721 In the auditor there is a loop over all users. For a site with
3722 only few users this will pose no serious problem, however, with
3723 many users this will be a serious performance bottleneck.
3724 A way out will be to link from the topics to the users which
3725 selected these topics a nosy topics. This will eliminate the
3726 loop over all users.
3729 Adding action links to the index page
3730 -------------------------------------
3732 Add a column to the item.index.html template.
3734 Resolving the issue::
3736 <a tal:attributes="href
3737 string:issue${i/id}?:status=resolved&:action=edit">resolve</a>
3739 "Take" the issue::
3741 <a tal:attributes="href
3742 string:issue${i/id}?:assignedto=${request/user/id}&:action=edit">take</a>
3744 ... and so on
3746 Users may only edit their issues
3747 --------------------------------
3749 Users registering themselves are granted Provisional access - meaning they
3750 have access to edit the issues they submit, but not others. We create a new
3751 Role called "Provisional User" which is granted to newly-registered users,
3752 and has limited access. One of the Permissions they have is the new "Edit
3753 Own" on issues (regular users have "Edit".) We back up the permissions with
3754 an auditor.
3756 First up, we create the new Role and Permission structure in
3757 ``dbinit.py``::
3759 # New users not approved by the admin
3760 db.security.addRole(name='Provisional User',
3761 description='New user registered via web or email')
3762 p = db.security.addPermission(name='Edit Own', klass='issue',
3763 description='Can only edit own issues')
3764 db.security.addPermissionToRole('Provisional User', p)
3766 # Assign the access and edit Permissions for issue to new users now
3767 p = db.security.getPermission('View', 'issue')
3768 db.security.addPermissionToRole('Provisional User', p)
3769 p = db.security.getPermission('Edit', 'issue')
3770 db.security.addPermissionToRole('Provisional User', p)
3772 # and give the new users access to the web and email interface
3773 p = db.security.getPermission('Web Access')
3774 db.security.addPermissionToRole('Provisional User', p)
3775 p = db.security.getPermission('Email Access')
3776 db.security.addPermissionToRole('Provisional User', p)
3779 Then in the ``config.py`` we change the Role assigned to newly-registered
3780 users, replacing the existing ``'User'`` values::
3782 NEW_WEB_USER_ROLES = 'Provisional User'
3783 NEW_EMAIL_USER_ROLES = 'Provisional User'
3785 Finally we add a new *auditor* to the ``detectors`` directory called
3786 ``provisional_user_auditor.py``::
3788 def audit_provisionaluser(db, cl, nodeid, newvalues):
3789 ''' New users are only allowed to modify their own issues.
3790 '''
3791 if (db.getuid() != cl.get(nodeid, 'creator')
3792 and db.security.hasPermission('Edit Own', db.getuid(), cl.classname)):
3793 raise ValueError, ('You are only allowed to edit your own %s'
3794 % cl.classname)
3796 def init(db):
3797 # fire before changes are made
3798 db.issue.audit('set', audit_provisionaluser)
3799 db.issue.audit('retire', audit_provisionaluser)
3800 db.issue.audit('restore', audit_provisionaluser)
3802 Note that some older trackers might also want to change the ``page.html``
3803 template as follows::
3805 <p class="classblock"
3806 - tal:condition="python:request.user.username != 'anonymous'">
3807 + tal:condition="python:request.user.hasPermission('View', 'user')">
3808 <b>Administration</b><br>
3809 <tal:block tal:condition="python:request.user.hasPermission('Edit', None)">
3810 <a href="home?:template=classlist">Class List</a><br>
3812 (note that the "-" indicates a removed line, and the "+" indicates an added
3813 line).
3816 Colouring the rows in the issue index according to priority
3817 -----------------------------------------------------------
3819 A simple ``tal:attributes`` statement will do the bulk of the work here. In
3820 the ``issue.index.html`` template, add to the ``<tr>`` that displays the
3821 actual rows of data::
3823 <tr tal:attributes="class string:priority-${i/priority/plain}">
3825 and then in your stylesheet (``style.css``) specify the colouring for the
3826 different priorities, like::
3828 tr.priority-critical td {
3829 background-color: red;
3830 }
3832 tr.priority-urgent td {
3833 background-color: orange;
3834 }
3836 and so on, with far less offensive colours :)
3838 Editing multiple items in an index view
3839 ---------------------------------------
3841 To edit the status of all items in the item index view, edit the
3842 ``issue.item.html``:
3844 1. add a form around the listing table, so at the top it reads::
3846 <form method="POST" tal:attributes="action request/classname">
3847 <table class="list">
3849 and at the bottom of that table::
3851 </table>
3852 </form
3854 making sure you match the ``</table>`` from the list table, not the
3855 navigation table or the subsequent form table.
3857 2. in the display for the issue property, change::
3859 <td tal:condition="request/show/status"
3860 tal:content="python:i.status.plain() or default"> </td>
3862 to::
3864 <td tal:condition="request/show/status"
3865 tal:content="structure i/status/field"> </td>
3867 this will result in an edit field for the status property.
3869 3. after the ``tal:block`` which lists the actual index items (marked by
3870 ``tal:repeat="i batch"``) add a new table row::
3872 <tr>
3873 <td tal:attributes="colspan python:len(request.columns)">
3874 <input type="submit" value=" Save Changes ">
3875 <input type="hidden" name="@action" value="edit">
3876 <tal:block replace="structure request/indexargs_form" />
3877 </td>
3878 </tr>
3880 which gives us a submit button, indicates that we are performing an edit
3881 on any changed statuses and the final block will make sure that the
3882 current index view parameters (filtering, columns, etc) will be used in
3883 rendering the next page (the results of the editing).
3885 -------------------
3887 Back to `Table of Contents`_
3889 .. _`Table of Contents`: index.html
3890 .. _`design documentation`: design.html