diff --git a/modules/webmessage/lib/webmessage.py b/modules/webmessage/lib/webmessage.py
index f23b54cb1..9052c6f09 100644
--- a/modules/webmessage/lib/webmessage.py
+++ b/modules/webmessage/lib/webmessage.py
@@ -1,445 +1,446 @@
 # -*- coding: utf-8 -*-
 ##
 ## $Id$
 ##
 ## This file is part of CDS Invenio.
 ## Copyright (C) 2002, 2003, 2004, 2005, 2006 CERN.
 ##
 ## CDS Invenio is free software; you can redistribute it and/or
 ## modify it under the terms of the GNU General Public License as
 ## published by the Free Software Foundation; either version 2 of the
 ## License, or (at your option) any later version.
 ##
 ## CDS Invenio is distributed in the hope that it will be useful, but
 ## WITHOUT ANY WARRANTY; without even the implied warranty of
 ## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 ## General Public License for more details.
 ##
 ## You should have received a copy of the GNU General Public License
 ## along with CDS Invenio; if not, write to the Free Software Foundation, Inc.,
 ## 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA.
 
 """ WebMessage module, messaging system"""
 
 __revision__ = "$Id$"
 
-import cgi
-
-from invenio.webmessage_dblayer import *
-from invenio.webmessage_config import *
+import invenio.webmessage_dblayer as db
+from invenio.webmessage_config import CFG_WEBMESSAGE_STATUS_CODE, \
+                                      CFG_WEBMESSAGE_RESULTS_FIELD, \
+                                      CFG_WEBMESSAGE_SEPARATOR, \
+                                      CFG_WEBMESSAGE_MAX_SIZE_OF_MESSAGE, \
+                                      CFG_WEBMESSAGE_ROLES_WITHOUT_QUOTA
 from invenio.config import cdslang
 from invenio.messages import gettext_set_language
 from invenio.dateutils import datetext_default, get_datetext
+from invenio.htmlutils import escape_html
 from invenio.webuser import list_users_in_roles
-
-import invenio.template
-
 try:
+    import invenio.template
     webmessage_templates = invenio.template.load('webmessage')
 except:
     pass
-
-def perform_request_display_msg(uid, msgid, ln = cdslang):
+    
+def perform_request_display_msg(uid, msgid, ln=cdslang):
     """
     Displays a specific message
     @param uid:   user id
     @param msgid: message id
     
     @return a (body, errors[], warnings[]) formed tuple
     """    
     errors = []
     warnings = []
     body = ""
 
-    if (check_user_owns_message(uid, msgid) == 0):
+    if (db.check_user_owns_message(uid, msgid) == 0):
         # The user doesn't own this message
         errors.append(('ERR_WEBMESSAGE_NOTOWNER',))
     else:
         (msg_id,
-         msg_from_id,
-         msg_from_nickname,
-         msg_sent_to,
-         msg_sent_to_group,
-         msg_subject,
-         msg_body,
-         msg_sent_date,
-         msg_received_date,
-         msg_status) = get_message(uid, msgid)
+         msg_from_id, msg_from_nickname,
+         msg_sent_to, msg_sent_to_group,
+         msg_subject, msg_body,
+         msg_sent_date, msg_received_date,
+         msg_status) = db.get_message(uid, msgid)
         
         if (msg_id == ""):
 	    # The message exists in table user_msgMESSAGE
 	    # but not in table msgMESSAGE => table inconsistency
             errors.append(('ERR_WEBMESSAGE_NOMESSAGE',))
         else:
             if (msg_status == CFG_WEBMESSAGE_STATUS_CODE['NEW']):
-                set_message_status(uid, msgid, CFG_WEBMESSAGE_STATUS_CODE['READ'])
-            body = webmessage_templates.tmpl_display_msg(msg_id, 
-                                                         msg_from_id,
-                                                         msg_from_nickname,
-							 msg_sent_to,
-							 msg_sent_to_group,
-							 msg_subject, 
-							 msg_body,
-							 msg_sent_date,
-                                                         msg_received_date,
-                                                         ln)
+                db.set_message_status(uid, msgid, 
+                                      CFG_WEBMESSAGE_STATUS_CODE['READ'])
+            body = webmessage_templates.tmpl_display_msg(
+                                                msg_id, 
+                                                msg_from_id,
+                                                msg_from_nickname,
+							                    msg_sent_to,
+							                    msg_sent_to_group,
+							                    msg_subject,
+							                    msg_body,
+							                    msg_sent_date,
+							                    msg_received_date,
+							                    ln)
     return (body, errors, warnings)
             
 def perform_request_display(uid, errors=[], warnings=[], infos=[], ln=cdslang):
     """
     Displays the user's Inbox
     @param uid:   user id
 
     @return a (body, [errors], [warnings]) formed tuple
     """
     body = ""    
     rows = []
-    rows = get_all_messages_for_user(uid)
-    nb_messages = 0
-    nb_messages = count_nb_messages(uid)
+    rows = db.get_all_messages_for_user(uid)
+    nb_messages = db.count_nb_messages(uid)
     no_quota_users = list_users_in_roles(CFG_WEBMESSAGE_ROLES_WITHOUT_QUOTA)
-    no_quota = 0
+    no_quota = False
     if uid in no_quota_users:
-       no_quota = 1
-        
+        no_quota = True
     body = webmessage_templates.tmpl_display_inbox(messages=rows,
                                                    infos=infos,
                                                    warnings=warnings,
                                                    nb_messages=nb_messages,
                                                    no_quota=no_quota,
                                                    ln=ln)
     return (body, errors, warnings)
 
 def perform_request_delete_msg(uid, msgid, ln=cdslang):
     """
     Delete a given message from user inbox
     @param uid: user id (int)
     @param msgid: message id (int)
     @param ln: language
     @return a (body, errors, warning tuple)
     """
     _ = gettext_set_language(ln)
     
     errors = []
     warnings = []
     infos = []
 
-    if (check_user_owns_message(uid, msgid) == 0):
+    if (db.check_user_owns_message(uid, msgid) == 0):
         # The user doesn't own this message
         errors.append(('ERR_WEBMESSAGE_NOTOWNER',))
     else:
-        if (delete_message_from_user_inbox(uid, msgid)==0):
+        if (db.delete_message_from_user_inbox(uid, msgid) == 0):
             warnings.append(_("The message could not be deleted."))
         else:
             infos.append(_("The message was successfully deleted."))
     return perform_request_display(uid, errors, warnings, infos, ln) 
 
-def perform_request_delete_all(uid, confirmed=0, ln=cdslang):
+def perform_request_delete_all(uid, confirmed=False, ln=cdslang):
     """
     Delete every message for a given user
     @param uid: user id (int)
     @param confirmed: 0 will produce a confirmation message
     @param ln: language
     @return a (body, errors, warnings) tuple
     """    
     infos = []
     warnings = []
     errors = []
     _ = gettext_set_language(ln)
     if confirmed:
-        delete_all_messages(uid)
+        db.delete_all_messages(uid)
         infos = [_("Your mailbox has been emptied.")]
         return perform_request_display(uid, warnings, errors, infos, ln)
     else:
         body = webmessage_templates.tmpl_confirm_delete(ln)
         return (body, errors, warnings)
 
 def perform_request_write(uid,
                           msg_reply_id="",
                           msg_to="",
                           msg_to_group="",
                           ln=cdslang):
     """
     Display a write a message page.
     @param uid: user id (int)
     @param msg_reply_id: if this message is a reply to another, other's ID (int)
     @param msg_to: comma separated usernames (string)
     @param msg_to_group: comma separated groupnames (string)
     @param ln: language
     @return a (body, errors, warnings) tuple
     """
     errors = []
     warnings = []
     body = ""
 
-    msg_from_nickname = ""
-    msg_subject = ""
-    msg_body = ""
+    msg_from_nickname = msg_subject = msg_body = ""
     msg_id = 0
     if (msg_reply_id):
-        if (check_user_owns_message(uid, msg_reply_id) == 0):
+        if (db.check_user_owns_message(uid, msg_reply_id) == 0):
             # The user doesn't own this message
             errors.append(('ERR_WEBMESSAGE_NOTOWNER',))
         else:
             # dummy == variable name to make pylint and pychecker happy!
             (msg_id,
-             msg_from_id,
-             msg_from_nickname,
-             dummy,
-             dummy,
-             msg_subject,
-             msg_body,
-             dummy,
-             dummy,
-             dummy) = get_message(uid, msg_reply_id)    
+             msg_from_id, msg_from_nickname,
+             dummy, dummy,
+             msg_subject, msg_body,
+             dummy, dummy, dummy) = db.get_message(uid, msg_reply_id)    
             if (msg_id == ""):
                 # The message exists in table user_msgMESSAGE
                 # but not in table msgMESSAGE => table inconsistency
                 errors.append(('ERR_WEBMESSAGE_NOMESSAGE',))
             else:
                 msg_to = msg_from_nickname or str(msg_from_id)
     
     body = webmessage_templates.tmpl_write(msg_to=msg_to,
                                            msg_to_group=msg_to_group,
                                            msg_id=msg_id,
                                            msg_subject=msg_subject,
                                            msg_body=msg_body,
                                            warnings=[],
                                            ln=ln)
     return (body, errors, warnings)
 
-def perform_request_write_with_search(uid,
-                                      msg_to_user="",
-                                      msg_to_group="",
-                                      msg_subject="",
-                                      msg_body="",
-                                      msg_send_year=0,
-                                      msg_send_month=0, 
-                                      msg_send_day=0,
-                                      names_selected=[],
-                                      search_pattern="",
-                                      results_field=CFG_WEBMESSAGE_RESULTS_FIELD['NONE'],
-                                      add_values=0,
-                                      ln=cdslang):
+def perform_request_write_with_search(
+                        uid,
+                        msg_to_user="",
+                        msg_to_group="",
+                        msg_subject="",
+                        msg_body="",
+                        msg_send_year=0,
+                        msg_send_month=0, 
+                        msg_send_day=0,
+                        names_selected=[],
+                        search_pattern="",
+                        results_field=CFG_WEBMESSAGE_RESULTS_FIELD['NONE'],
+                        add_values=0,
+                        ln=cdslang):
     """
     Display a write message page, with prefilled values
     @param msg_to_user: comma separated usernames (str)
     @param msg_to_group: comma separated groupnames (str)
     @param msg_subject: message subject (str)
     @param msg_bidy: message body (string)
     @param msg_send_year: year to send this message on (int)
     @param_msg_send_month: month to send this message on (int)
     @param_msg_send_day: day to send this message on (int)
     @param users_to_add: list of usernames ['str'] to add to msg_to_user
     @param groups_to_add: list of groupnames ['str'] to add to msg_to_group
     @param user_search_pattern: will search users with this pattern (str)
     @param group_search_pattern: will search groups with this pattern (str)
     @param mode_user: if 1 display user search box, else group search box
     @param add_values: if 1 users_to_add will be added to msg_to_user field..
     @param ln: language
     @return a (body, errors, warnings) formed tuple.
     """    
     warnings = []
     errors = []
     search_results_list = []
     def cat_names(name1, name2):
         """ name1, name2 => 'name1, name2' """
         return name1 + CFG_WEBMESSAGE_SEPARATOR + " " + name2
     
     if results_field == CFG_WEBMESSAGE_RESULTS_FIELD['USER']:
         if add_values and len(names_selected):
             usernames_to_add = reduce(cat_names, names_selected)
             if msg_to_user:
                 msg_to_user = cat_names(msg_to_user, usernames_to_add)
             else:
                 msg_to_user = usernames_to_add
                 
-        users_found = get_nicknames_like(search_pattern)
+        users_found = db.get_nicknames_like(search_pattern)
         if users_found:
             for user_name in users_found:
-                search_results_list.append((user_name[0], user_name[0] in names_selected))
+                search_results_list.append((user_name[0], 
+                                            user_name[0] in names_selected))
         
     elif results_field == CFG_WEBMESSAGE_RESULTS_FIELD['GROUP']:
         if add_values and len(names_selected):
             groupnames_to_add = reduce(cat_names, names_selected)
             if msg_to_group:
                 msg_to_group = cat_names(msg_to_group, groupnames_to_add)
             else:
                 msg_to_group = groupnames_to_add
-        groups_dict = get_groupnames_like(uid, search_pattern)
+        groups_dict = db.get_groupnames_like(uid, search_pattern)
         groups_found = groups_dict.values()
         if groups_found:
             for group_name in groups_found:
-                search_results_list.append((group_name, group_name in names_selected))
+                search_results_list.append((group_name, 
+                                            group_name in names_selected))
        
-    body = webmessage_templates.tmpl_write(msg_to=msg_to_user,
-                                           msg_to_group=msg_to_group,
-                                           msg_subject=msg_subject,
-                                           msg_body=msg_body, 
-                                           msg_send_year=msg_send_year,
-                                           msg_send_month=msg_send_month,
-                                           msg_send_day=msg_send_day,
-                                           warnings=warnings,
-                                           search_results_list=search_results_list,
-                                           search_pattern=search_pattern,
-                                           results_field=results_field, 
-                                           ln=ln)
+    body = webmessage_templates.tmpl_write(
+                            msg_to=msg_to_user,
+                            msg_to_group=msg_to_group,
+                            msg_subject=msg_subject,
+                            msg_body=msg_body, 
+                            msg_send_year=msg_send_year,
+                            msg_send_month=msg_send_month,
+                            msg_send_day=msg_send_day,
+                            warnings=warnings,
+                            search_results_list=search_results_list,
+                            search_pattern=search_pattern,
+                            results_field=results_field, 
+                            ln=ln)
     return (body, errors, warnings)
   
 def perform_request_send(uid,
                          msg_to_user="",
                          msg_to_group="",
                          msg_subject="",
                          msg_body="",
                          msg_send_year=0,
                          msg_send_month=0,
                          msg_send_day=0,
                          ln=cdslang):
     """
     send a message. if unable return warnings to write page
     @param uid: id of user from (int)
     @param msg_to_user: comma separated usernames (recipients) (str)
     @param msg_to_group: comma separated groupnames (recipeints) (str)
     @param msg_subject: subject of message (str)
     @param msg_body: body of message (str)
     @param msg_send_year: send this message on year x (int)
     @param msg_send_month: send this message on month y (int)
     @param msg_send_day: send this message on day z (int)
     @param ln: language
     @return a (body, errors, warnings) tuple
     """
     _ = gettext_set_language(ln)
 
-    def strip_spaces(str):
+    def strip_spaces(text):
         """suppress spaces before and after x (str)"""
-        return str.strip()
+        return text.strip()
     # wash user input
     users_to = map(strip_spaces, msg_to_user.split(CFG_WEBMESSAGE_SEPARATOR))
     groups_to = map(strip_spaces, msg_to_group.split(CFG_WEBMESSAGE_SEPARATOR))
 
     if users_to == ['']:
         users_to = []
     if groups_to == ['']:
         groups_to = []
 
 
     warnings = []
     errors = []
     infos = []
     problem = None
 
     users_to_str = CFG_WEBMESSAGE_SEPARATOR.join(users_to)
     groups_to_str = CFG_WEBMESSAGE_SEPARATOR.join(groups_to)
     
     send_on_date = get_datetext(msg_send_year, msg_send_month, msg_send_day)
     if (msg_send_year == msg_send_month == msg_send_day == 0):
         status = CFG_WEBMESSAGE_STATUS_CODE['NEW']
     else:
         status = CFG_WEBMESSAGE_STATUS_CODE['REMINDER']
         if send_on_date == datetext_default:
-            warning = _("The chosen date (%(x_year)i/%(x_month)i/%(x_day)i) is invalid.")
+            warning = \
+            _("The chosen date (%(x_year)i/%(x_month)i/%(x_day)i) is invalid.")
             warning = warning % {'x_year': msg_send_year,
                                  'x_month': msg_send_month,
                                  'x_day': msg_send_day}
             warnings.append(warning)
-            problem = 1
+            problem = True
             
     if not(users_to_str or groups_to_str):
         # <=> not(users_to_str) AND not(groups_to_str)
         warnings.append(_("Please enter a user name or a group name."))
-        problem = 1
+        problem = True
         
     if len(msg_body) > CFG_WEBMESSAGE_MAX_SIZE_OF_MESSAGE:
-        warnings.append(_("Your message is too long, please edit it. Maximum size allowed is %i characters.")%(CFG_WEBMESSAGE_MAX_SIZE_OF_MESSAGE,))
-        problem = 1
+        warnings.append(_("Your message is too long, please edit it. Maximum size allowed is %i characters.") % \
+                            (CFG_WEBMESSAGE_MAX_SIZE_OF_MESSAGE,))
+        problem = True
 
-    users_dict = get_uids_from_nicks(users_to)
+    users_dict = db.get_uids_from_nicks(users_to)
     users_to = users_dict.items() # users_to=[(nick, uid),(nick2, uid2)]
-    groups_dict = get_gids_from_groupnames(groups_to)
+    groups_dict = db.get_gids_from_groupnames(groups_to)
     groups_to = groups_dict.items()
     gids_to = []
     for (group_name, group_id) in groups_to:
         if not(group_id):
-            warnings.append(_("Group %s does not exist.")% (cgi.escape(group_name)))
+            warnings.append(_("Group %s does not exist.") % \
+                            (escape_html(group_name)))
             problem = 1
         else:
             gids_to.append(group_id)
         
     # Get uids from gids
-    uids_from_group = get_uids_members_of_groups(gids_to)
+    uids_from_group = db.get_uids_members_of_groups(gids_to)
     # Add the original uids, and make sure  there is no double values.
     tmp_dict = {}
     for uid_receiver in uids_from_group:
         tmp_dict[uid_receiver] = None
     for (user_nick, user_id) in users_to:
         if user_id:
             if user_id not in tmp_dict:
                 uids_from_group.append(user_id)
                 tmp_dict[user_id] = None
         else:
-            if type(user_nick) == int or type(user_nick) == str and user_nick.isdigit():
+            if type(user_nick) == int or \
+               type(user_nick) == str and user_nick.isdigit():
                 user_nick = int(user_nick)
-                if user_exists(user_nick) and user_nick not in tmp_dict:
+                if db.user_exists(user_nick) and user_nick not in tmp_dict:
                     uids_from_group.append(user_nick)
                     tmp_dict[user_nick] = None
             else:                    
-                warnings.append(_("User %s does not exist.")% (cgi.escape(user_nick)))
-                problem = 1
+                warnings.append(_("User %s does not exist.")% \
+                                (escape_html(user_nick)))
+                problem = True
     if problem:
         body = webmessage_templates.tmpl_write(msg_to=users_to_str,
                                                msg_to_group=groups_to_str,
                                                msg_subject=msg_subject,
                                                msg_body=msg_body,
                                                msg_send_year=msg_send_year,
                                                msg_send_month=msg_send_month,
                                                msg_send_day=msg_send_day,
                                                warnings=warnings,
                                                ln=ln)
         title =  _("Write a message")
         navtrail = get_navtrail(ln, title)
         return (body, errors, warnings, title, navtrail)
     else:
-        msg_id = create_message(uid,
-                                users_to_str,
-                                groups_to_str,
-                                msg_subject,
-                                msg_body,
-                                send_on_date)
-        uid_problem = send_message(uids_from_group, msg_id, status)
+        msg_id = db.create_message(uid,
+                                   users_to_str, groups_to_str,
+                                   msg_subject, msg_body,
+                                   send_on_date)
+        uid_problem = db.send_message(uids_from_group, msg_id, status)
         if len(uid_problem) > 0:
-            usernames_problem_dict = get_nicks_from_uids(uid_problem)
+            usernames_problem_dict = db.get_nicks_from_uids(uid_problem)
             usernames_problem = usernames_problem_dict.values()
             def listing(name1, name2):
                 """ name1, name2 => 'name1, name2' """
                 return str(name1) + ", " + str(name2)
             warning = _("Your message could not be sent to the following recipients due to their quota:") + " "
             warnings.append(warning + reduce(listing, usernames_problem)) 
 
         if len(uids_from_group) != len(uid_problem):
             infos.append(_("Your message has been sent."))
         else:
-            check_if_need_to_delete_message_permanently([msg_id])
-        (body, errors, warnings) = perform_request_display(uid, errors, warnings, infos, ln)
+            db.check_if_need_to_delete_message_permanently([msg_id])
+        (body, errors, warnings) = perform_request_display(uid, 
+                                                           errors, 
+                                                           warnings, 
+                                                           infos, ln)
         title = _("Your Messages")
         return (body, errors, warnings, title, get_navtrail(ln))
 
 def account_new_mail(uid, ln=cdslang):
     """
     display new mail info for myaccount.py page.
     @param uid: user id (int)
     @param ln: language
     @return html body
     """
-    nb_new_mail = get_nb_new_messages_for_user(uid)
-    total_mail = get_nb_readable_messages_for_user(uid)
-    return webmessage_templates.tmpl_account_new_mail(nb_new_mail, total_mail, ln)
+    nb_new_mail = db.get_nb_new_messages_for_user(uid)
+    total_mail = db.get_nb_readable_messages_for_user(uid)
+    return webmessage_templates.tmpl_account_new_mail(nb_new_mail, 
+                                                      total_mail, ln)
 
 def get_navtrail(ln=cdslang, title=""):
     """
     gets the navtrail for title...
     @param title: title of the page
     @param ln: language
     @return HTML output
     """
     navtrail = webmessage_templates.tmpl_navtrail(ln, title)
     return navtrail
diff --git a/modules/webmessage/lib/webmessage_mailutils.py b/modules/webmessage/lib/webmessage_mailutils.py
index 80c3eb5ff..071aa8cd3 100644
--- a/modules/webmessage/lib/webmessage_mailutils.py
+++ b/modules/webmessage/lib/webmessage_mailutils.py
@@ -1,119 +1,166 @@
 # -*- coding: utf-8 -*-
 ## $Id$
 
 ## This file is part of CDS Invenio.
 ## Copyright (C) 2002, 2003, 2004, 2005, 2006 CERN.
 ##
 ## CDS Invenio is free software; you can redistribute it and/or
 ## modify it under the terms of the GNU General Public License as
 ## published by the Free Software Foundation; either version 2 of the
 ## License, or (at your option) any later version.
 ##
 ## CDS Invenio is distributed in the hope that it will be useful, but
 ## WITHOUT ANY WARRANTY; without even the implied warranty of
 ## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 ## General Public License for more details.
 ##
 ## You should have received a copy of the GNU General Public License
 ## along with CDS Invenio; if not, write to the Free Software Foundation, Inc.,
 ## 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA.
 
 """ Library for quoting text, email style """
 
 __revision__ = "$Id$"
 
+from invenio.htmlutils import HTMLWasher
+
 def email_quoted_txt2html(text,
                           tabs_before=0,
                           indent_txt='>>',
                           linebreak_txt="\n",
                           indent_html=('<div class="commentbox">', "</div>"),
                           linebreak_html='<br/>'):
     """
     Takes a typical mail quoted text, e.g.:
         hello,
         you told me:
         >> Your mother was a hamster and your father smelt of elderberries
         I must tell you that I'm not convinced. Then in this discussion:
         >>>> Is there someone else up there we could talk to?
         >> No. Now, go away, or I shall taunt you a second time-a!
         I think we're not going to be friends!
     and return an html formatted output, e.g.:
         hello,<br/>
         you told me:<br/>
         <div>
           Your mother was a hamster and your father smelt of elderberries
         </div>
         I must tell you that I'm not convinced. Then in this discussion:
         <div>
           <div>
             Is there someone else up there we could talk to?
           </div>
           No. Now, go away, or I shall taunt you a second time-a!
         </div>
         I think we're not going to be friends!
         
     @param text: the text in quoted format
     @param tabs_before: number of tabulations before each line
-    @param indent_str: quote separator in email (default:'>>')
-    @param linebreak_str: line separator in email (default: '\n')
+    @param indent_txt: quote separator in email (default:'>>')
+    @param linebreak_txt: line separator in email (default: '\n')
     @param indent_html: tuple of (opening, closing) html tags.
                         default: ('<div class="commentbox">', "</div>")
     @param linebreak_html: line separator in html (default: '<br/>')
     @return string containing html formatted output
     """
     final_body = ""
     nb_indent = 0
     lines = text.split(linebreak_txt)
     for line in lines:
-        new_nb_indent = line.count(indent_txt)
+        new_nb_indent = 0
+        while True:
+            if line.startswith(indent_txt):
+                new_nb_indent += 1
+                line = line[len(indent_txt):]
+            else:
+                break        
         if (new_nb_indent > nb_indent):
-            for _ in range(nb_indent, new_nb_indent):
+            for dummy in range(nb_indent, new_nb_indent):
                 final_body += tabs_before*"\t" + indent_html[0] + "\n"
                 tabs_before += 1
         elif (new_nb_indent < nb_indent):
-            for _ in range(new_nb_indent, nb_indent):
+            for dummy in range(new_nb_indent, nb_indent):
                 tabs_before -= 1 
                 final_body += (tabs_before)*"\t" + indent_html[1] + "\n"
-        final_body += tabs_before*"\t" + line.replace(indent_txt, '')
+        else:
+            final_body += (tabs_before)*"\t" + linebreak_html
+        final_body += tabs_before*"\t" + line
         final_body += linebreak_html + "\n"
         nb_indent = new_nb_indent
-    for _ in range(0, nb_indent):
+    for dummy in range(0, nb_indent):
         tabs_before -= 1
         final_body += (tabs_before)*"\t" + "</div>\n"
     return final_body
 
 
 def email_quote_txt(text,
                     indent_txt='>>',
                     linebreak_input="\n",
                     linebreak_output="\n"):
     """
     Takes a text and returns it in a typical mail quoted format, e.g.:
         C'est un lapin, lapin de bois.
         >>Quoi?
         Un cadeau.
         >>What?
         A present.
         >>Oh, un cadeau.
     will return:
         >>C'est un lapin, lapin de bois.
         >>>>Quoi?
         >>Un cadeau.
         >>>>What?
         >>A present.
         >>>>Oh, un cadeau.   
     @param text: the string to quote
     @param indent_txt: the string used for quoting (default: '>>')
     @param linebreak_input: in the text param, string used for linebreaks
                             default: '\n'
     @param linebreak_output: linebreak used for output
                              default: '\n'
     @return the text as a quoted string
     """
     if (text == ""):
         return ""
     lines = text.split(linebreak_input)
     text = ""
     for line in lines:
         text += indent_txt + line + linebreak_output
     return text
+    
+def escape_email_quoted_text(text, indent_txt='>>', linebreak_txt='\n'):
+    """Escape text using an email-like indenting rule.
+    As an example, this text:
+    
+    >>Brave Sir Robin ran away... 
+    <img src="malicious_script />*No!* 
+    >>bravely ran away away... 
+    I didn't!*<script>malicious code</script> 
+    >>When danger reared its ugly head, he bravely turned his tail and fled. 
+    <form onload="malicious"></form>*I never did!* 
+    
+    will be escaped like this:
+    >>Brave Sir Robin ran away... 
+    &lt;img src="malicious_script /&gt;*No!* 
+    >>bravely ran away away... 
+    I didn't!*&lt;script&gt;malicious code&lt;/script&gt; 
+    >>When danger reared its ugly head, he bravely turned his tail and fled. 
+    &lt;form onload="malicious"&gt;&lt;/form&gt;*I never did!* 
+    """
+    washer = HTMLWasher()
+    lines = text.split(linebreak_txt)
+    print len(lines)
+    output = ''
+    for line in lines:
+        line = line.strip()
+        nb_indent = 0
+        while True:
+            if line.startswith(indent_txt):
+                print 'ici!!'
+                nb_indent += 1
+                line = line[len(indent_txt):]
+            else:
+                break
+        output += (nb_indent * indent_txt) + washer.wash(line) + linebreak_txt
+        nb_indent = 0
+    return output[:-1]
\ No newline at end of file
diff --git a/modules/webmessage/lib/webmessage_templates.py b/modules/webmessage/lib/webmessage_templates.py
index e1c5772bb..e45194e4b 100644
--- a/modules/webmessage/lib/webmessage_templates.py
+++ b/modules/webmessage/lib/webmessage_templates.py
@@ -1,651 +1,688 @@
 # -*- coding: utf-8 -*-
 ## $Id$
 ## 
 ## handles rendering of webmessage module
 ##
 ## This file is part of CDS Invenio.
 ## Copyright (C) 2002, 2003, 2004, 2005, 2006 CERN.
 ##
 ## CDS Invenio is free software; you can redistribute it and/or
 ## modify it under the terms of the GNU General Public License as
 ## published by the Free Software Foundation; either version 2 of the
 ## License, or (at your option) any later version.
 ##
 ## CDS Invenio is distributed in the hope that it will be useful, but
 ## WITHOUT ANY WARRANTY; without even the implied warranty of
 ## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 ## General Public License for more details.
 ##
 ## You should have received a copy of the GNU General Public License
 ## along with CDS Invenio; if not, write to the Free Software Foundation, Inc.,
 ## 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA.
 
 """ templates for webmessage module """
 
 __revision__ = "$Id$"
 
-import cgi
-
 from invenio.webmessage_mailutils import email_quoted_txt2html, email_quote_txt
 from invenio.webmessage_config import CFG_WEBMESSAGE_STATUS_CODE, \
                                       CFG_WEBMESSAGE_SEPARATOR, \
                                       CFG_WEBMESSAGE_MAX_NB_OF_MESSAGES, \
                                       CFG_WEBMESSAGE_RESULTS_FIELD
 from invenio.textutils import indent_text
 from invenio.dateutils import convert_datetext_to_dategui, \
                               datetext_default, \
                               create_day_selectbox, \
                               create_month_selectbox, \
                               create_year_selectbox
+from invenio.urlutils import create_html_link, create_url
+from invenio.htmlutils import escape_html
 from invenio.config import weburl, cdslang
 from invenio.messages import gettext_set_language
 from invenio.webuser import get_user_info
 
 class Template:
+    """Templates for WebMessage module"""
+    
     def tmpl_display_inbox(self, messages, infos=[], warnings=[], nb_messages=0, no_quota=0, ln=cdslang):
         """
         Displays a list of messages, with the appropriate links and buttons
         @param messages: a list of tuples:
                          [(message_id,
                            user_from_id,
                            user_from_nickname,
                            subject,
                            sent_date,
                            status=]
         @param infos: a list of informations to print on top of page
         @param warnings: a list of warnings to display
         @param nb_messages: number of messages user has
         @param no_quota: 1 if user has no quota (admin) or 0 else.
         @param ln: language of the page.
         @return the list in HTML format                                            
         """
         _ = gettext_set_language(ln)
         dummy = 0
         inbox = self.tmpl_warning(warnings, ln)
         inbox += self.tmpl_infobox(infos, ln)
         if not(no_quota):
             inbox += self.tmpl_quota(nb_messages, ln)
         inbox += """
 <table class="mailbox">
   <thead class="mailboxheader">
     <tr class="inboxheader"> 
       <td>%s</td>
       <td>%s</td>
       <td>%s</td>
       <td>%s</td>
     </tr>
   </thead>
   <tfoot>
     <tr style="height:0px;">
       <td></td>
       <td></td>
       <td></td>
       <td></td>
     </tr>
   </tfoot>
-  <tbody class="mailboxbody">""" %(_("Subject"), _("Sender"), _("Date"), _("Action"))
+  <tbody class="mailboxbody">""" % (_("Subject"), 
+                                    _("Sender"), 
+                                    _("Date"), 
+                                    _("Action"))
         if len(messages) == 0:
             inbox += """
     <tr class="mailboxrecord" style="height: 100px;">
       <td colspan="4" style="text-align: center;">
         <b>%s</b>
       </td>
     </tr>""" %(_("No messages"),)
-        for (msgid, id_user_from, user_from_nick, subject, sent_date, status) in messages:
+        for (msgid, id_user_from, user_from_nick, 
+             subject, sent_date, status) in messages:
             if not(subject):
                 subject = _("No subject")
-            subject_link = '<a href="display_msg?msgid=%i&amp;ln=%s">%s</a>'% (msgid,
-                                                                               ln,
-                                                                               cgi.escape(subject))
+            subject_link = create_html_link(
+                                weburl + '/yourmessages/display_msg',
+                                {'msgid': msgid, 'ln': ln},
+                                escape_html(subject))
             if user_from_nick:
                 from_link = '%s'% (user_from_nick)
             else:
                 from_link = get_user_info(id_user_from, ln)[2]
-            action_link = '<a href="write?msg_reply_id=%i&amp;ln=%s">%s</a> / '% (msgid,
-                                                                                 ln,
-                                                                                 _("Reply"))
-            action_link += '<a href="delete?msgid=%i&amp;ln=%s">%s</a>'% (msgid,
-                                                                            ln,
-                                                                            _("Delete"))
+            action_link = create_html_link(weburl + '/yourmessages/write',
+                                           {'msg_reply_id': msgid, 'ln': ln},
+                                           _("Reply"))
+            action_link += ' '
+            action_link += create_html_link(weburl + '/yourmessages/delete',
+                                            {'msgid': msgid, 'ln': ln},
+                                            _("Delete"))
             s_date = convert_datetext_to_dategui(sent_date, ln)
             stat_style = ''
             if (status == CFG_WEBMESSAGE_STATUS_CODE['NEW']):
                 stat_style = ' style="font-weight:bold"' 
             inbox += """
     <tr class="mailboxrecord">
       <td%s>%s</td>
       <td>%s</td>
       <td>%s</td>
       <td>%s</td>
     </tr>""" %(stat_style, subject_link, from_link, s_date, action_link)
         inbox += """
     <tr class="mailboxfooter">
       <td colspan="2">
-        <form name="newMessage" action="write?ln=%(ln)s" method="post">
+        <form name="newMessage" action="%(url_new)s" method="post">
           <input type="submit" name="del_all" value="%(write_label)s" class="formbutton" />
         </form>
       </td>
       <td>&nbsp;</td>
       <td>
-        <form name="deleteAll" action="delete_all?ln=%(ln)s" method="post">
+        <form name="deleteAll" action="url_delete_all" method="post">
           <input type="submit" name="del_all" value="%(delete_all_label)s" class="formbutton" />
         </form>
       </td>
     </tr> 
   </tbody>
-</table>""" % {'ln': ln,
+</table>""" % {'url_new': create_url(weburl + '/yourmessages/write', 
+                                     {'ln': ln}),
+               'url_delete_all': create_url(weburl + '/yourmessages/delete_all', 
+                                            {'ln': ln}),                           
                'write_label': _("Write new message"),
                'delete_all_label': _("Delete All")}
         return indent_text(inbox, 2)
 
     def tmpl_write(self,
-                   msg_to="",
-                   msg_to_group="",
+                   msg_to="", msg_to_group="",
                    msg_id=0,
-                   msg_subject="",
-                   msg_body="",
-                   msg_send_year=0,
-                   msg_send_month=0,
-                   msg_send_day=0,
+                   msg_subject="", msg_body="",
+                   msg_send_year=0, msg_send_month=0, msg_send_day=0,
                    warnings=[],
                    search_results_list=[],
                    search_pattern="",
                    results_field=CFG_WEBMESSAGE_RESULTS_FIELD['NONE'],
                    ln=cdslang):
         """
         Displays a writing message form with optional prefilled fields
         @param msg_to: nick of the user (prefills the To: field)
         @param msg_subject: subject of the message (prefills the Subject: field)
         @param msg_body: body of the message (prefills the Message: field)
         @param msg_send_year: prefills to year field
         @param msg_send_month: prefills the month field
         @param msg_send_day: prefills the day field
         @param warnings: display warnings on top of page
         @param search_results_list: list of tuples. (user/groupname, is_selected)
         @param search_pattern: pattern used for searching
         @param results_field: 'none', 'user' or 'group', see CFG_WEBMESSAGE_RESULTS_FIELD
         @param ln: language of the form
         @return the form in HTML format
         """
         _ = gettext_set_language(ln)
         write_box = self.tmpl_warning(warnings)
 
         # escape forbidden character
-        msg_to = msg_to.replace('"', '&quot;')
-        msg_to_group = msg_to_group.replace('"', '&quot;')
-        msg_subject = msg_subject.replace('"', '&quot;')
-        search_pattern = search_pattern.replace('"','&quot;')
+        msg_to = escape_html(msg_to)
+        msg_to_group = escape_html(msg_to_group)
+        msg_subject = escape_html(msg_subject)
+        search_pattern = escape_html(search_pattern)
 
         to_select = self.tmpl_user_or_group_search(search_results_list,
                                                    search_pattern,
                                                    results_field,
                                                    ln)
-        if (msg_id != 0):
+        if msg_id:
             msg_subject = _("Re:") + " " + msg_subject
             msg_body = email_quote_txt(msg_body)
-            msg_body = msg_body.replace('>', '&gt;')
         write_box += """
-<form name="write_message" action="send" method="post">
-  <input type="hidden" name="ln" value="%(ln)s"/>
+<form name="write_message" action="%(url_form)s" method="post">
   <div style="float: left; vertical-align:text-top; margin-right: 10px;">
     <table class="mailbox">
       <thead class="mailboxheader">
         <tr>
           <td class="inboxheader" colspan="2">
             <table class="messageheader">
               <tr>
                 <td class="mailboxlabel">%(to_label)s</td>
                 <td class="mailboxlabel">%(users_label)s</td>
                 <td style="width:100%%;">
                   <input class="mailboxinput" type="text" name="msg_to_user" value="%(to_users)s" />
                 </td>
               </tr>
               <tr>
                 <td class="mailboxlabel">&nbsp;</td>
                 <td class="mailboxlabel">%(groups_label)s</td>
                 <td style="width:100%%;">
                   <input class="mailboxinput" type="text" name="msg_to_group" value="%(to_groups)s" />
                 </td>
               </tr>
               <tr>
                 <td class="mailboxlabel">&nbsp;</td>
                 <td>&nbsp;</td>
                 <td>&nbsp;</td>
               </tr>
               <tr>
                 <td class="mailboxlabel">%(subject_label)s</td>
                 <td colspan="2">
                   <input class="mailboxinput" type="text" name="msg_subject" value="%(subject)s" />
                 </td>
               </tr>
             </table>
           </td>
         </tr>
       </thead>
       <tfoot>
         <tr>
           <td style="height:0px" colspan="2"></td>
         </tr>
       </tfoot>
       <tbody class="mailboxbody">
         <tr>
           <td class="mailboxlabel">%(message_label)s</td>
           <td>
             <textarea name="msg_body" rows="10" cols="50">"""
         write_box = indent_text(write_box, 2)
         write_box_part2 = """
           </td>
         </tr>
         <tr>
           <td class="mailboxlabel">%(send_later_label)s</td>
           <td>
             %(day_field)s
             %(month_field)s
             %(year_field)s
           </td>
         </tr>
         <tr class="mailboxfooter">
           <td colspan="2" class="mailboxfoot">
             <input type="submit" name="send_button" value="%(send_label)s" class="formbutton"/>
           </td>
         </tr>
       </tbody>
     </table>
   </div>
   <div style="vertical-align:top; margin-left: 5px; float: left;">
     %(to_select)s
   </div>
 </form>
 """
         write_box_part2 = indent_text(write_box_part2, 2)
         write_box += "%(body)s" "</textarea>"+ write_box_part2
-        day_field = create_day_selectbox('msg_send_day', msg_send_day, ln)
-        month_field = create_month_selectbox('msg_send_month', msg_send_month, ln)
-        year_field = create_year_selectbox('msg_send_year', -1, 10, msg_send_year, ln)
-        write_box = write_box % {'to_users' : msg_to,
+        day_field = create_day_selectbox('msg_send_day', 
+                                          msg_send_day, ln)
+        month_field = create_month_selectbox('msg_send_month', 
+                                              msg_send_month, ln)
+        year_field = create_year_selectbox('msg_send_year', -1, 10, 
+                                            msg_send_year, ln)
+        write_box = write_box % {'url_form': create_url(
+                                                weburl + '/yourmessages/send',
+                                                {'ln': ln}),
+                                 'to_users' : msg_to,
                                  'to_groups': msg_to_group,
                                  'subject' : msg_subject,
                                  'body' : msg_body,
                                  'ln': ln,
                                  'day_field': day_field,
                                  'month_field': month_field,
                                  'year_field': year_field,
                                  'to_select': to_select,
                                  'send_later_label': _("Send later?"),
                                  'to_label': _("To:"),
                                  'users_label': _("Users"),
                                  'groups_label': _("Groups"),
                                  'subject_label': _("Subject:"),
                                  'message_label': _("Message:"),
                                  'send_label': _("SEND")}
         return write_box 
     
     def tmpl_display_msg(self, 
                          msg_id="",
                          msg_from_id="",
                          msg_from_nickname="",
                          msg_sent_to="", 
                          msg_sent_to_group="",
                          msg_subject="",
                          msg_body="",
                          msg_sent_date="",
                          msg_received_date=datetext_default,
                          ln=cdslang):
         """
         Displays a given message
         @param msg_id: id of the message
         @param msg_from_id: id of user who sent the message
         @param msg_from_nickname: nickname of the user who sent the message
         @param msg_sent_to: list of users who received the message
                             (comma separated string)
         @param msg_sent_to_group: list of groups who received the message
                                   (comma separated string)
         @param msg_subject: subject of the message
         @param msg_body: body of the message
         @param msg_sent_date: date at which the message was sent
         @param msg_received_date: date at which the message had to be received
                                   (if this argument != 0000-00-00 => reminder
         @param ln: language of the page
         @return the message in HTML format
         """
 
         # load the right message language
         _ = gettext_set_language(ln)
         
         sent_to_link = ''
         tos = msg_sent_to.split(CFG_WEBMESSAGE_SEPARATOR)
         if (tos):
             for to in tos[0:-1]:
                 to_display = to
                 if to.isdigit():
                     (dummy, to, to_display) = get_user_info(int(to), ln)
-                sent_to_link += '<a href="write?msg_to=%s&amp;ln=%s">'% (to, ln)
-                sent_to_link += '%s</a>%s '% (cgi.escape(to_display), CFG_WEBMESSAGE_SEPARATOR)
+                sent_to_link += create_html_link(weburl + '/yourmessages/write',
+                                                 {'msg_to': to, 'ln': ln},
+                                                 escape_html(to_display))
+                sent_to_link += CFG_WEBMESSAGE_SEPARATOR
             to_display = tos[-1]
             to = tos[-1]
             if to.isdigit():
                 (dummy, to, to_display) = get_user_info(int(to), ln)
-            sent_to_link += '<a href="write?msg_to=%s&amp;ln=%s">%s</a>'% (to, ln, cgi.escape(to_display))
+            sent_to_link += create_html_link(weburl + '/yourmessages/write',
+                                             {'msg_to': to, 'ln': ln},
+                                             escape_html(to_display))
         group_to_link = ""
         groups = msg_sent_to_group.split(CFG_WEBMESSAGE_SEPARATOR)
         if (groups):
             for group in groups[0:-1]:
-                group_to_link += '<a href="write?msg_to_group=%s&amp;ln=%s">'% (group, ln)
-                group_to_link += '%s</a>%s '% (cgi.escape(group), CFG_WEBMESSAGE_SEPARATOR)
-            group_to_link += '<a href="write?msg_to_group=%s&amp;ln=%s">%s</a>'% (groups[-1], ln, groups[-1])
+                group_to_link += create_html_link(
+                                    weburl + '/yourmessages/write',
+                                    {'msg_to_group': group, 'ln': ln},
+                                    escape_html(group))
+                group_to_link += CFG_WEBMESSAGE_SEPARATOR
+            group_to_link += create_html_link(
+                                weburl + '/yourmessages/write',
+                                {'msg_to_group': groups[-1], 'ln': ln},
+                                escape_html(groups[-1]))
         # format the msg so that the '>>' chars give vertical lines
         final_body = email_quoted_txt2html(msg_body)
 
         out = """
 <table class="mailbox" style="width: 70%%;">
   <thead class="mailboxheader">
     <tr>
       <td class="inboxheader" colspan="2">
         <table class="messageheader">
           <tr>
             <td class="mailboxlabel">%(from_label)s</td>
-            <td><a href="write?msg_to=%(from)s&amp;ln=%(ln)s">%(from_display)s</a></td>
+            <td>%(from_link)s</td>
           </tr>
           <tr>
             <td class="mailboxlabel">%(subject_label)s</td>
             <td style="width: 100%%;">%(subject)s</td>
           </tr>
           <tr>
             <td class="mailboxlabel">%(sent_label)s</td>
             <td>%(sent_date)s</td>
           </tr>"""
         if (msg_received_date != datetext_default):
             out += """
           <tr>
             <td class="mailboxlabel">%(received_label)s</td>
             <td>%(received_date)s</td>
           </tr>"""
         out += """
           <tr>
             <td class="mailboxlabel">%(sent_to_label)s</td>
             <td>%(sent_to)s</td>
           </tr>"""
         if (msg_sent_to_group != ""):
             out += """
           <tr>
             <td class="mailboxlabel">%(groups_label)s</td>
             <td>%(sent_to_group)s</td>
           </tr>"""
         out += """
         </table>
       </td>
     </tr>
   </thead>
   <tfoot>
     <tr>
       <td></td>
       <td></td>
     </tr>
   </tfoot>
   <tbody class="mailboxbody">
     <tr class="mailboxrecord">
       <td colspan="2">%(body)s</td>
     </tr>
     <tr class="mailboxfooter">
       <td>
-        <form name="reply" action="write?msg_reply_id=%(msg_id)s" method="post">
+        <form name="reply" action="%(reply_url)s" method="post">
           <input class="formbutton" name="reply" value="%(reply_but_label)s" type="submit" />
         </form>
       </td>
       <td>
-        <form name="deletemsg" action="delete?msgid=%(msg_id)s&amp;ln=%(ln)s" method="post">
+        <form name="deletemsg" action="%(delete_url)s" method="post">
           <input class="formbutton" name="delete" value="%(delete_but_label)s" type="submit" />
         </form>
       </td>
     </tr>
   </tbody>
 </table>
         """
         if msg_from_nickname:
             msg_from_display = msg_from_nickname
         else:
             msg_from_display = get_user_info(msg_from_id, ln)[2]
             msg_from_nickname = msg_from_id
 
-        out = out % {'from' : msg_from_nickname,
-                     'from_display': msg_from_display,
+        out = out % {'from_link': create_html_link(
+                                        weburl + '/yourmessages/write',
+                                        {'msg_to': msg_from_nickname,
+                                         'ln': ln},
+                                        msg_from_display),
+                     'reply_url': create_url(weburl + '/yourmessages/write',
+                                             {'msg_reply_id': msg_id,
+                                             'ln':  ln}),
+                     'delete_url': create_url(weburl + '/yourmessages/delete',
+                                             {'msgid': msg_id,
+                                             'ln':  ln}),
                      'sent_date' : convert_datetext_to_dategui(msg_sent_date, ln),
                      'received_date': convert_datetext_to_dategui(msg_received_date, ln),
                      'sent_to': sent_to_link,
                      'sent_to_group': group_to_link,
-                     'subject' : cgi.escape(msg_subject),
-                     'body' : cgi.escape(final_body),
+                     'subject' : msg_subject,
+                     'body' : final_body,
                      'reply_to': msg_from_id,
-                     'msg_id': msg_id,
                      'ln': ln,
                      'from_label':_("From:"),
                      'subject_label':_("Subject:"),
                      'sent_label': _("Sent on:"),
                      'received_label':_("Received on:"),
                      'sent_to_label': _("Sent to:"),
                      'groups_label': _("Sent to groups:"),
                      'reply_but_label':_("REPLY"),
                      'delete_but_label': _("DELETE")}
         return indent_text(out, 2)
 
     def tmpl_navtrail(self, ln=cdslang, title=""):
         """
         display the navtrail, e.g.:
         Your account > Your messages > title
         @param title: the last part of the navtrail. Is not a link
         @param ln: language
         return html formatted navtrail
         """
         _ = gettext_set_language(ln)
-        nav_h1 = '<a class="navtrail" href="%s/youraccount/display?ln=%s">%s</a>'
+        nav_h1 = create_html_link(weburl + '/youraccount/display',
+                                  {'ln': ln},
+                                  _("Your Account"),
+                                  {'class': 'navtrail'})        
         nav_h2 = ""
         if (title != ""):
-            nav_h2 = ' &gt; <a class="navtrail" href="%s/yourmessages/display?ln=%s">%s</a>'
-            nav_h2 = nav_h2 % (weburl, ln, _("Your Messages"))
-
-        return nav_h1 % (weburl, ln, _("Your Account")) + nav_h2
+            nav_h2 += create_html_link(weburl + '/yourmessages/display',
+                                       {'ln': ln},
+                                       _("Your Messages"),
+                                       {'class': 'navtrail'})
+            return nav_h1 + ' &gt; ' + nav_h2
+        return nav_h1
     
     def tmpl_confirm_delete(self, ln=cdslang):
         """
         display a confirm message
         @param ln: language
         @return html output
         """
         _ = gettext_set_language(ln)
         out = """
 <table class="confirmoperation">
   <tr>
     <td colspan="2" class="confirmmessage">
       %(message)s
     </td>
   </tr>
   <tr>
     <td>
       <form name="validate" action="delete_all" method="post">
         <input type="hidden" name="confirmed" value="1" />
         <input type="hidden" name="ln" value="%(ln)s" />
         <input type="submit" value="%(yes_label)s" class="formbutton" />
       </form>
     </td>
     <td>
       <form name="cancel" action="display" method="post">
         <input type="hidden" name="ln" value="%(ln)s" />
         <input type="submit" value="%(no_label)s" class="formbutton" />
       </form>
     </td>
   </tr>
 </table>"""% {'message': _("Are you sure you want to empty your whole mailbox?"),
               'ln':ln,
               'yes_label': _("Yes"),
               'no_label': _("No")}
         return indent_text(out, 2)
 
     def tmpl_infobox(self, infos, ln=cdslang):
         """Display len(infos) information fields
         @param infos: list of strings
         @param ln=language
         @return html output
         """
         _ = gettext_set_language(ln)
         if not((type(infos) is list) or (type(infos) is tuple)):
             infos = [infos]       
         infobox = ""
         for info in infos:
             infobox += "<div class=\"infobox\">"
             lines = info.split("\n")
             for line in lines[0:-1]:
                 infobox += line + "<br/>\n"
             infobox += lines[-1] + "</div><br/>\n"
         return infobox
 
 
     def tmpl_warning(self, warnings, ln=cdslang):
         """
         Display len(warnings) warning fields
         @param infos: list of strings
         @param ln=language
         @return html output
         """
         _ = gettext_set_language(ln)
         if not((type(warnings) is list) or (type(warnings) is tuple)):
             warnings = [warnings]
         warningbox = ""
         if warnings != []:
             warningbox = "<div class=\"warningbox\">\n  <b>Warning:</b>\n"
             for warning in warnings:
                 lines = warning.split("\n")
                 warningbox += "  <p>"
                 for line in lines[0:-1]:
                     warningbox += line + "    <br/>\n"
                 warningbox += lines[-1] + "  </p>"
             warningbox += "</div><br/>\n"
         return warningbox
 
 
     def tmpl_quota(self, nb_messages=0, ln=cdslang):
         """
         Display a quota bar.
         @nb_messages: number of messages in inbox.
         @ln=language
         @return html output
         """
         _ = gettext_set_language(ln)
         quota = float(CFG_WEBMESSAGE_MAX_NB_OF_MESSAGES)
         ratio = float(nb_messages) / quota
         out = """
 %(quota_label)s<br/>
 <div class="quotabox">
   <div class="quotabar" style="width:%(width)ipx"></div>
 </div>""" %{'quota_label' : _("Quota used: %i messages out of max. %i")%(nb_messages, CFG_WEBMESSAGE_MAX_NB_OF_MESSAGES),
             'width' : int(ratio * 200)
             }
 
         return out
 
     
     def tmpl_multiple_select(self, select_name, tuples_list, ln=cdslang):
         """displays a multiple select environment
         @param tuples_list: a list of (value, isSelected) tuples
         @return HTML output
         """
         _ = gettext_set_language(ln)
         if not((type(tuples_list) is list) or (type(tuples_list) is tuple)):
             tuples_list = [tuples_list]
         out = """
         %s
 <select name="%s" multiple="multiple" style="width:100%%">"""% (_("Please select one or more:"), select_name)
         for (value, is_selected) in tuples_list:
             out += '  <option value="%s"'% value
             if is_selected:
                 out += " selected=\"selected\""
             out += ">%s</option>\n"% value
         out += "</select>\n"
         return out    
 
 
     def tmpl_user_or_group_search(self,
                                   tuples_list=[],
                                   search_pattern="",
                                   results_field=CFG_WEBMESSAGE_RESULTS_FIELD['NONE'],
                                   ln=cdslang):
         """
         Display a box for user searching
         @param tuples_list: list of (value, is_selected) tuples
         @param search_pattern: text to display in this field
         @param results_field: either 'none', 'user', 'group', look at CFG_WEBMESSAGE_RESULTS_FIELD
         @param ln: language
         @return html output
         """
         _ = gettext_set_language(ln)
         multiple_select = ''
         add_button = ''
         if results_field != CFG_WEBMESSAGE_RESULTS_FIELD['NONE'] and results_field in CFG_WEBMESSAGE_RESULTS_FIELD.values():
             if len(tuples_list):
                 multiple_select = self.tmpl_multiple_select('names_selected', tuples_list)
                 add_button = '<input type="submit" name="%s" value="%s" class="nonsubmitbutton" />'
                 if results_field == CFG_WEBMESSAGE_RESULTS_FIELD['USER']:
                     add_button = add_button % ('add_user', _("Add to users"))
                 else:
                     add_button = add_button % ('add_group', _("Add to groups"))
             else:
                 if results_field == CFG_WEBMESSAGE_RESULTS_FIELD['USER']:
                     multiple_select = _("No matching user")
                 else:
                     multiple_select = _("No matching group")
         out = """
 <table class="mailbox">
   <thead class="mailboxheader">
     <tr class ="inboxheader">
       <td colspan="3">
         %(title_label)s
         <input type="hidden" name="results_field" value="%(results_field)s" />
       </td>
     </tr>
   </thead>
   <tbody class="mailboxbody">
   <tr class="mailboxsearch">
       <td>
         <input type="text" name="search_pattern" value="%(search_pattern)s" />
       </td>
       <td>
         <input type="submit" name="search_user" value="%(search_user_label)s" class="nonsubmitbutton" />
       </td>
       <td>
         <input type="submit" name="search_group" value="%(search_group_label)s" class="nonsubmitbutton" />
       </td>
     </tr>
     <tr class="mailboxresults">
       <td colspan="2">
         %(multiple_select)s
       </td>
       <td>
         %(add_button)s
       </td>
     </tr>
   </tbody>
 </table>
 """
-        out = out% {'title_label'        : _("Find users or groups:"),
-                    'search_user_label'  : _("Find a user"),
-                    'search_group_label' : _("Find a group"),
-                    'results_field'      : results_field,
-                    'search_pattern'     : search_pattern,
-                    'multiple_select'    : multiple_select,
-                    'add_button'         : add_button}
+        out = out % {'title_label'        : _("Find users or groups:"),
+                     'search_user_label'  : _("Find a user"),
+                     'search_group_label' : _("Find a group"),
+                     'results_field'      : results_field,
+                     'search_pattern'     : search_pattern,
+                     'multiple_select'    : multiple_select,
+                     'add_button'         : add_button}
         return out
 
     def tmpl_account_new_mail(self, nb_new_mail=0, total_mail=0, ln=cdslang):
         """
         display infos about inbox (used by myaccount.py)
         @param nb_new_mail: number of new mails
         @param ln: language
         return: html output.
         """
         _ = gettext_set_language(ln)
         out = _("You have %s new messages out of %s messages")
         out %= ('<b>' + str(nb_new_mail) + '</b>', 
-                '<a href="' + weburl + '/yourmessages/?ln=' + ln + '">' + str(total_mail))
-        out += '</a>.'
-        return out
+                create_html_link(weburl + '/yourmessages/', 
+                                 {'ln': ln}, 
+                                 str(total_mail), 
+                                 {}, 
+                                 False, False))
+        return out + '.'
 
     
diff --git a/modules/webmessage/lib/webmessage_webinterface.py b/modules/webmessage/lib/webmessage_webinterface.py
index d84774f20..786fde499 100644
--- a/modules/webmessage/lib/webmessage_webinterface.py
+++ b/modules/webmessage/lib/webmessage_webinterface.py
@@ -1,285 +1,312 @@
 # -*- coding: utf-8 -*-
 ## $Id$
 ## Messaging system (internal)
 
 ## This file is part of CDS Invenio.
 ## Copyright (C) 2002, 2003, 2004, 2005, 2006 CERN.
 ##
 ## CDS Invenio is free software; you can redistribute it and/or
 ## modify it under the terms of the GNU General Public License as
 ## published by the Free Software Foundation; either version 2 of the
 ## License, or (at your option) any later version.
 ##
 ## CDS Invenio is distributed in the hope that it will be useful, but
 ## WITHOUT ANY WARRANTY; without even the implied warranty of
 ## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 ## General Public License for more details.
 ##
 ## You should have received a copy of the GNU General Public License
 ## along with CDS Invenio; if not, write to the Free Software Foundation, Inc.,
 ## 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA.
 
 """WebMessage web interface"""
 
 __revision__ = "$Id$"
 
 __lastupdated__ = """$Date$"""
 
-from invenio.config import weburl, cdslang, CFG_ACCESS_CONTROL_LEVEL_SITE
+from invenio.config import weburl, CFG_ACCESS_CONTROL_LEVEL_SITE
 from invenio.webuser import getUid, isGuestUser, page_not_authorized
-from invenio.webmessage import *
+from invenio.webmessage import perform_request_display, \
+                               perform_request_display_msg, \
+                               perform_request_write, \
+                               perform_request_send, \
+                               perform_request_write_with_search, \
+                               perform_request_delete_msg, \
+                               perform_request_delete_all, \
+                               get_navtrail
 from invenio.webmessage_config import CFG_WEBMESSAGE_RESULTS_FIELD
+from invenio.webmessage_mailutils import escape_email_quoted_text
 from invenio.webpage import page
 from invenio.messages import gettext_set_language
 from invenio.urlutils import redirect_to_url
+from invenio.htmlutils import escape_html
 from invenio.webinterface_handler import wash_urlargd, WebInterfaceDirectory
 
 class WebInterfaceYourMessagesPages(WebInterfaceDirectory):
     """Defines the set of /yourmessages pages."""
 
     _exports = ['', 'display', 'write', 'send', 'delete', 'delete_all',
                 'display_msg']
 
     def index(self, req, form):
         """ The function called by default
         """
         redirect_to_url(req, "%s/yourmessages/display?%s" % (weburl, req.args))
 
     def display(self, req, form):
         """
         Displays the Inbox of a given user
         @param ln:  language
         @return the page for inbox
         """
         argd = wash_urlargd(form, {})
 
         # Check if user is logged
         uid = getUid(req)
         if uid == -1 or isGuestUser(uid) or CFG_ACCESS_CONTROL_LEVEL_SITE >= 1: 
-            return page_not_authorized(req, "%s/yourmessages/display" % (weburl,))    
+            return page_not_authorized(req, "%s/yourmessages/display" % \
+                                            (weburl,))    
 
         _ = gettext_set_language(argd['ln'])
 
         (body, errors, warnings) = perform_request_display(uid=uid,
                                                            ln=argd['ln'])
 
         return page(title       = _("Your Messages"),
                     body        = body,
                     navtrail    = get_navtrail(argd['ln']),
                     uid         = uid,
                     lastupdated = __lastupdated__,
                     req         = req,
                     language    = argd['ln'],
                     errors      = errors,
                     warnings    = warnings)
     
     def write(self, req, form):
         """ write(): interface for message composing
-        @param msg_reply_id: if this message is a reply to another, id of the other
-        @param msg_to: if this message is not a reply, nickname of the user it must be
-                       delivered to.
+        @param msg_reply_id: if this message is a reply to another, id of the
+                             other
+        @param msg_to: if this message is not a reply, nickname of the user it
+                       must be delivered to.
         @param msg_to_group: name of group to send message to
         @param ln: language
         @return the compose page
         """
         argd = wash_urlargd(form, {'msg_reply_id': (int, 0),
                                    'msg_to': (str, ""),
                                    'msg_to_group': (str, "")})
 
         # Check if user is logged
         uid = getUid(req)
 
         if uid == -1 or CFG_ACCESS_CONTROL_LEVEL_SITE >= 1 or isGuestUser(uid): 
             return page_not_authorized(req, "%s/yourmessages/write" % (weburl,))
 
         _ = gettext_set_language(argd['ln'])
 
         # Request the composing page
-        (body, errors, warnings) = perform_request_write(uid=uid,
-                                                         msg_reply_id=argd['msg_reply_id'],
-                                                         msg_to=argd['msg_to'],
-                                                         msg_to_group=argd['msg_to_group'],
-                                                         ln=argd['ln'])
+        (body, errors, warnings) = perform_request_write(
+                                        uid=uid,
+                                        msg_reply_id=argd['msg_reply_id'],
+                                        msg_to=argd['msg_to'],
+                                        msg_to_group=argd['msg_to_group'],
+                                        ln=argd['ln'])
         title = _("Write a message")
 
         return page(title       = title,
                     body        = body,
                     navtrail    = get_navtrail(argd['ln'], title),
                     uid         = uid,
                     lastupdated = __lastupdated__,
                     req         = req,
                     language    = argd['ln'],
                     errors      = errors,
                     warnings    = warnings)
 
     def send(self, req, form):
         """
         Sends the message
         @param msg_to_user: comma separated usernames (str)
         @param msg_to_group: comma separated groupnames (str)
         @param msg_subject: message subject (str)
         @param msg_body: message body (string)
         @param msg_send_year: year to send this message on (int)
         @param_msg_send_month: month to send this message on (int)
         @param_msg_send_day: day to send this message on (int)
         @param results_field: value determining which results field to display. 
-                              See CFG_WEBMESSAGE_RESULTS_FIELD in webmessage_config.py
-        @param names_to_add: list of usernames ['str'] to add to msg_to_user / group
-        @param search_pattern: will search for users/groups with this pattern (str)
-        @param add_values: if 1 users_to_add will be added to msg_to_user field..
+                              See CFG_WEBMESSAGE_RESULTS_FIELD in
+                              webmessage_config.py
+        @param names_to_add: list of usernames ['str'] to add to 
+                             msg_to_user / group
+        @param search_pattern: will search for users/groups with this pattern
+        @param add_values: if 1 users_to_add will be added to msg_to_user 
+                           field..
         @param *button: which button was pressed
         @param ln: language
         @return a (body, errors, warnings) formed tuple.
         """
         argd = wash_urlargd(form, {'msg_to_user': (str, ""),
                                    'msg_to_group': (str, ""),
                                    'msg_subject': (str, ""),
                                    'msg_body': (str, ""),
                                    'msg_send_year': (int, 0),
                                    'msg_send_month': (int, 0),
                                    'msg_send_day': (int, 0),
-                                   'results_field': (str, CFG_WEBMESSAGE_RESULTS_FIELD['NONE']),
+                                   'results_field': (str,
+                                        CFG_WEBMESSAGE_RESULTS_FIELD['NONE']),
                                    'names_selected': (list, []), 
                                    'search_pattern': (str, ""), 
                                    'send_button': (str, ""), 
                                    'search_user': (str, ""), 
                                    'search_group': (str, ""), 
                                    'add_user': (str, ""), 
                                    'add_group': (str, ""), 
                                    })
         # Check if user is logged
         uid = getUid(req)
         if uid == -1 or isGuestUser(uid) or CFG_ACCESS_CONTROL_LEVEL_SITE >= 1: 
             return page_not_authorized(req, "%s/yourmessages/send" % (weburl,))
         _ = gettext_set_language(argd['ln'])
         if argd['send_button']:
-            (body, errors, warnings, title, navtrail) = perform_request_send(uid=uid,
-                                                                             msg_to_user=argd['msg_to_user'],
-                                                                             msg_to_group=argd['msg_to_group'],
-                                                                             msg_subject=argd['msg_subject'],
-                                                                             msg_body=argd['msg_body'],
-                                                                             msg_send_year=argd['msg_send_year'],
-                                                                             msg_send_month=argd['msg_send_month'],
-                                                                             msg_send_day=argd['msg_send_day'],
-                                                                             ln=argd['ln'])
+            (body, errors, warnings, title, navtrail) = perform_request_send(
+                            uid=uid,
+                            msg_to_user=argd['msg_to_user'],
+                            msg_to_group=argd['msg_to_group'],
+                            msg_subject=escape_html(argd['msg_subject']),
+                            msg_body=escape_email_quoted_text(argd['msg_body']),
+                            msg_send_year=argd['msg_send_year'],
+                            msg_send_month=argd['msg_send_month'],
+                            msg_send_day=argd['msg_send_day'],
+                            ln=argd['ln'])
         else:
             title = _('Write a message')
             navtrail = get_navtrail(argd['ln'], title)
             if argd['search_user']:
                 argd['results_field'] = CFG_WEBMESSAGE_RESULTS_FIELD['USER']
             elif argd['search_group']:
                 argd['results_field'] = CFG_WEBMESSAGE_RESULTS_FIELD['GROUP']
             add_values = 0
             if argd['add_group'] or argd['add_user']:
                 add_values = 1
-            
-            (body, errors, warnings) = perform_request_write_with_search(uid=uid,
-                                                                         msg_to_user=argd['msg_to_user'],
-                                                                         msg_to_group=argd['msg_to_group'],
-                                                                         msg_subject=argd['msg_subject'],
-                                                                         msg_body=argd['msg_body'],
-                                                                         msg_send_year=argd['msg_send_year'],
-                                                                         msg_send_month=argd['msg_send_month'],
-                                                                         msg_send_day=argd['msg_send_day'],
-                                                                         names_selected=argd['names_selected'],
-                                                                         search_pattern=argd['search_pattern'],
-                                                                         results_field=argd['results_field'],
-                                                                         add_values=add_values,
-                                                                         ln=argd['ln'])
+            (body, errors, warnings) = perform_request_write_with_search(
+                            uid=uid,
+                            msg_to_user=argd['msg_to_user'],
+                            msg_to_group=argd['msg_to_group'],
+                            msg_subject=escape_html(argd['msg_subject']),
+                            msg_body=escape_email_quoted_text(argd['msg_body']),
+                            msg_send_year=argd['msg_send_year'],
+                            msg_send_month=argd['msg_send_month'],
+                            msg_send_day=argd['msg_send_day'],
+                            names_selected=argd['names_selected'],
+                            search_pattern=argd['search_pattern'],
+                            results_field=argd['results_field'],
+                            add_values=add_values,
+                            ln=argd['ln'])
         return page(title       = title,
                     body        = body,
                     navtrail    = navtrail,
                     uid         = uid,
                     lastupdated = __lastupdated__,
                     req         = req,
                     language    = argd['ln'],
                     errors      = errors,
                     warnings    = warnings)
 
     def delete(self, req, form):
         """
         Suppress a message
         @param msgid: id of message
         @param ln: language
         @return page
         """
         argd = wash_urlargd(form, {'msgid': (int, -1),
                                    })
 
         # Check if user is logged
         uid = getUid(req)
         if uid == -1 or CFG_ACCESS_CONTROL_LEVEL_SITE >= 1 or isGuestUser(uid): 
-            return page_not_authorized(req, "%s/yourmessages/delete_msg" % (weburl,))
+            return page_not_authorized(req, 
+                                       "%s/yourmessages/delete_msg" % \
+                                       (weburl,))
 
         _ = gettext_set_language(argd['ln'])
 
         # Generate content
-        (body, errors, warnings) = perform_request_delete_msg(uid, argd['msgid'], argd['ln'])
+        (body, errors, warnings) = perform_request_delete_msg(uid, 
+                                                              argd['msgid'],
+                                                              argd['ln'])
         return page(title       = _("Your Messages"),
                     body        = body,
                     navtrail    = get_navtrail(argd['ln']),
                     uid         = uid,
                     lastupdated = __lastupdated__,
                     req         = req,
                     language    = argd['ln'],
                     errors      = errors,
                     warnings    = warnings)
 
     def delete_all(self, req, form):        
         """
         Empty user's inbox
         @param confimed: 1 if message is confirmed
         @param ln: language
         \return page
         """        
         argd = wash_urlargd(form, {'confirmed': (int, 0),
                                    })
 
         # Check if user is logged
         uid = getUid(req)
         if uid == -1 or CFG_ACCESS_CONTROL_LEVEL_SITE >= 1 or isGuestUser(uid): 
-            return page_not_authorized(req, "%s/yourmessages/delete_all" % (weburl,))
+            return page_not_authorized(req, "%s/yourmessages/delete_all" % \
+                                            (weburl,))
 
         _ = gettext_set_language(argd['ln'])
 
         # Generate content
-        (body, errors, warnings) = perform_request_delete_all(uid, argd['confirmed'], argd['ln'])
+        (body, errors, warnings) = perform_request_delete_all(uid, 
+                                                              argd['confirmed'],
+                                                              argd['ln'])
         return page(title       = _("Your Messages"),
                     body        = body,
                     navtrail    = get_navtrail(argd['ln']),
                     uid         = uid,
                     lastupdated = __lastupdated__,
                     req         = req,
                     language    = argd['ln'],
                     errors      = errors,
                     warnings    = warnings)
 
     def display_msg(self, req, form):
         """
         Display a message
         @param msgid: id of message
         @param ln: languae
         @return page
         """
         argd = wash_urlargd(form, {'msgid': (int, -1),
                                    })
 
         # Check if user is logged
         uid = getUid(req)
         if uid == -1 or CFG_ACCESS_CONTROL_LEVEL_SITE >= 1 or isGuestUser(uid): 
-            return page_not_authorized(req, "%s/yourmessages/display_msg" % (weburl,))
+            return page_not_authorized(req, "%s/yourmessages/display_msg" % \
+                                             (weburl,))
 
         _ = gettext_set_language(argd['ln'])
         # Generate content
-        (body, errors, warnings) = perform_request_display_msg(uid, argd['msgid'], argd['ln'])
+        (body, errors, warnings) = perform_request_display_msg(uid, 
+                                                               argd['msgid'],
+                                                               argd['ln'])
         title = _("Read a message")
         return page(title       = title,
                     body        = body,
                     navtrail    = get_navtrail(argd['ln'], title),
                     uid         = uid,
                     lastupdated = __lastupdated__,
                     req         = req,
                     language    = argd['ln'],
                     errors      = errors,
                     warnings    = warnings)