diff --git a/modules/bibformat/lib/bibformat_templates.py b/modules/bibformat/lib/bibformat_templates.py
index baa8f1f1c..7aa1b124a 100644
--- a/modules/bibformat/lib/bibformat_templates.py
+++ b/modules/bibformat/lib/bibformat_templates.py
@@ -1,2406 +1,2459 @@
 # -*- coding: utf-8 -*-
 ##
 ## $Id$
 ##
 ## This file is part of CDS Invenio.
 ## Copyright (C) 2002, 2003, 2004, 2005, 2006, 2007, 2008 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.
 
 """HTML Templates for BibFormat administration"""
 
 __revision__ = "$Id$"
 
 # non Invenio imports
 import cgi
 
 # Invenio imports
 from invenio.messages import gettext_set_language
 from invenio.config import CFG_SITE_URL, CFG_SITE_SECURE_URL
 from invenio.messages import language_list_long
 from invenio.config import CFG_PATH_PHP
 
 MAX_MAPPINGS = 100 #show max this number of mappings on one page
 
 
 class Template:
     """Templating class, refer to bibformat.py for examples of call"""
 
     def tmpl_admin_index(self, ln, warnings, is_admin):
         """
         Returns the main BibFormat admin page.
 
         @param ln language
         @param warnings a list of warnings to display at top of page. None if no warning
         @param is_admin indicate if user is authorized to use BibFormat
         @return main BibFormat admin page
         """
 
         _ = gettext_set_language(ln)    # load the right message language
 
         out = ''
 
         if warnings:
             out += '''
             <table width="66%%" class="errorbox" style="margin-left: auto; margin-right: auto;">
             <tr>
             <th class="errorboxheader">
             %(warnings)s
             </th>
             </tr>
             </table>
             ''' % {'warnings': '<br/>'.join(warnings)}
 
         out += '''
         <p>
          This is where you can edit the formatting styles available for the records. '''
 
         if not is_admin:
             out += '''You need to
             <a href="%(siteurl)s/youraccount/login?referer=%(siteurl)s/admin/bibformat/bibformatadmin.py">login</a> to enter.
          ''' % {'siteurl':CFG_SITE_URL}
 
         out += '''
         </p>
         <dl>
         <dt><a href="%(siteurl)s/admin/bibformat/bibformatadmin.py/format_templates_manage?ln=%(ln)s">Manage Format Templates</a></dt>
         <dd>Define how to format a record.</dd>
         </dl>
         <dl>
         <dt><a href="%(siteurl)s/admin/bibformat/bibformatadmin.py/output_formats_manage?ln=%(ln)s">Manage Output Formats</a></dt>
         <dd>Define which template is applied to which record for a given output.</dd>
         </dl>
         <dl>
         <dt><a href="%(siteurl)s/admin/bibformat/bibformatadmin.py/kb_manage?ln=%(ln)s">Manage Knowledge Bases</a></dt>
         <dd>Define mappings of values, for standardizing records or declaring often used values.</dd>
         </dl>
         <br/>
         <dl>
         <dt><a href="%(siteurl)s/admin/bibformat/bibformatadmin.py/format_elements_doc?ln=%(ln)s">Format Elements Documentation</a></dt>
         <dd>Documentation of the format elements to be used inside format templates.</dd>
         </dl>
         <dl>
         <dt><a href="%(siteurl)s/help/admin/bibformat-admin-guide">BibFormat Admin Guide</a></dt>
         <dd>Documentation about BibFormat administration</dd>
         </dl>
         '''% {'siteurl':CFG_SITE_URL, 'ln':ln}
 
         if CFG_PATH_PHP:
             #Show PHP admin only if PHP is enabled
             out += '''
             <br/><br/><br/><br/>
             <div style="background-color:rgb(204, 204, 204);">
 
             <h2><span style="color:rgb(204, 0, 0);">Old</span>
             BibFormat admin interface (in gray box)</h2>
             <em>
             <p>The BibFormat admin interface enables you to specify how the
             bibliographic data is presented to the end user in the search
             interface and search results pages.  For example, you may specify that
             titles should be printed in bold font, the abstract in small italic,
             etc.  Moreover, the BibFormat is not only a simple bibliographic data
             <em>output formatter</em>, but also an automated <em>link
             constructor</em>.  For example, from the information on journal name
             and pages, it may automatically create links to publisher's site based
             on some configuration rules.
 
             <h2>Configuring BibFormat</h2>
 
             <p>By default, a simple HTML format based on the most common fields
             (title, author, abstract, keywords, fulltext link, etc) is defined.
             You certainly want to define your own ouput formats in case you have a
             specific metadata structure.
 
             <p>Here is a short guide of what you can configure:
 
             <blockquote>
             <dl>
 
             <dt><a href="BEH_display.php">Behaviours</a>
 
             <dd>Define one or more output BibFormat behaviours.  These are then
             passed as parameters to the BibFormat modules while executing
             formatting.
 
             <br /><em>Example:</em> You can tell BibFormat that is has to enrich the
             incoming metadata file by the created format, or that it only has to
             print the format out.
 
             <dt><a href="OAIER_display.php">Extraction Rules</a>
 
             <dd>Define how the metadata tags from input are mapped into internal
             BibFormat variable names.  The variable names can afterwards be used
             in formatting and linking rules.
 
             <br /><em>Example:</em> You can tell that <code>100 $a</code> field
             should be mapped into <code>$100.a</code> internal variable that you
             could use later.
 
             <dt><a href="LINK_display.php">Link Rules</a>
 
             <dd>Define rules for automated creation of URI links from mapped
             internal variables.
 
             <br /><em>Example:</em> You can tell a rule how to create a link to
             People database out of the <code>$100.a</code> internal variable
             repesenting author's name.  (The <code>$100.a</code> variable was mapped
             in the previous step, see the Extraction Rules.)
 
             <dt><a href="LINK_FORMAT_display.php">File Formats</a>
 
             <dd>Define file format types based on file extensions.  This will be
             used when proposing various fulltext services.
 
             <br /><em>Example:</em> You can tell that <code>*.pdf</code> files will
             be treated as PDF files.
 
             <dt><a href="UDF_display.php">User Defined Functions (UDFs)</a>
 
             <dd>Define your own functions that you can reuse when creating your
             own output formats.  This enables you to do complex formatting without
             ever touching the BibFormat core code.
 
             <br /><em>Example:</em> You can define a function how to match and
             extract email addresses out of a text file.
 
             <dt><a href="FORMAT_display.php">Formats</a>
 
             <dd>Define the output formats, i.e. how to create the output out of
             internal BibFormat variables that were extracted in a previous step.
             This is the functionality you would want to configure most of the
             time.  It may reuse formats, user defined functions, knowledge bases,
             etc.
 
             <br /><em>Example:</em> You can tell that authors should be printed in
             italic, that if there are more than 10 authors only the first three
             should be printed, etc.
 
             <dt><a href="KB_display.php">Knowledge Bases (KBs)</a>
 
             <dd>Define one or more knowledge bases that enables you to transform
             various forms of input data values into the unique standard form on
             the output.
 
             <br /><em>Example:</em> You can tell that <em>Phys Rev D</em> and
             <em>Physical Review D</em> are both the same journal and that these
             names should be standardized to <em>Phys Rev : D</em>.
 
             <dt><a href="test.php">Execution Test</a>
 
             <dd>Enables you to test your formats on your sample data file.  Useful
             when debugging newly created formats.
 
             </dl>
             </blockquote>
 
             <p>To learn more on BibFormat configuration, you can consult the <a
             href="guide.html">BibFormat Admin Guide</a>.</small>
 
             <h2>Running BibFormat</h2>
 
             <h3>From the Web interface</h3>
             <p>
             Run <a href="BIBREFORMAT_display.php">Reformat Records</a> tool.
             This tool permits you to update stored formats for bibliographic records.
             <br />
             It should normally be used after configuring BibFormat's
             <a href="BEH_display.php">Behaviours</a> and
             <a href="FORMAT_display.php">Formats</a>.
             When these are ready, you can choose to rebuild formats for selected
             collections or you can manually enter a search query and the web interface
             will accomplish all necessary formatting steps.
             <br />
             <i>Example:</i> You can request Photo collections to have their HTML
             brief formats rebuilt, or you can reformat all the records written by Ellis.
 
             <h3>From the command-line interface</h3>
 
             <p>Consider having an XML MARC data file that is to be uploaded into
             the CDS Invenio.  (For example, it might have been harvested from other
             sources and processed via <a href="../bibconvert/">BibConvert</a>.)
             Having configured BibFormat and its default output type behaviour, you
             would then run this file throught BibFormat as follows:
 
             <blockquote>
             <pre>
             $ bibformat < /tmp/sample.xml > /tmp/sample_with_fmt.xml
             <pre>
             </blockquote>
 
             that would create default HTML formats and would "enrich" the input
             XML data file by this format.  (You would then continue the upload
             procedure by calling successively <a
             href="../bibupload/">BibUpload</a> and <a
             href="../bibindex/">BibIndex</a>.)
 
             <p>Now consider a different situation.  You would like to add a new
             possible format, say "HTML portfolio" and "HTML captions" in order to
             nicely format multiple photographs in one page.  Let us suppose that
             these two formats are called <code>hp</code> and <code>hc</code> and
             are already loaded in the <code>collection_format</code> table.
             (TODO: describe how this is done via WebAdmin.)  You would then
             proceed as follows: firstly, you would prepare the corresponding <a
             href="BEH_display.php">output behaviours</a> called <code>HP</code>
             and <code>HC</code> (TODO: note the uppercase!) that would not enrich
             the input file but that would produce an XML file with only
             <code>001</code> and <code>FMT</code> tags.  (This is in order not to
             update the bibliographic information but the formats only.)  You would
             also prepare corresponding <a href="FORMAT_display.php">formats</a>
             at the same time.  Secondly, you would launch the formatting as
             follows:
 
             <blockquote>
             <pre>
             $ bibformat otype=HP,HC < /tmp/sample.xml > /tmp/sample_fmts_only.xml
             <pre>
             </blockquote>
 
             that should give you an XML file containing only 001 and FMT tags.
             Finally, you would upload the formats:
 
             <blockquote>
             <pre>
             $ bibupload < /tmp/sample_fmts_only.xml
             <pre>
             </blockquote>
 
             and that's it. The new formats should now appear in <a
             href="%(siteurl)s">WebSearch</a>.
             </em>
             </div>
 
             ''' % {'siteurl':CFG_SITE_URL, 'ln':ln}
 
         return out
 
     def tmpl_admin_format_template_show_attributes(self, ln, name, description, filename, editable,
 						   all_templates=[], new=False):
         """
         Returns a page to change format template name and description
 
 	If template is new, offer a way to create a duplicate from an
 	existing template
 
         @param ln language
         @param name the name of the format
         @param description the description of the format
         @param filename the filename of the template
         @param editable True if we let user edit, else False
 	@param all_templates a list of tuples (filename, name) of all other templates
 	@param new if True, the format template has just been added (is new)
         @return editor for 'format'
         """
         _ = gettext_set_language(ln)    # load the right message language
 
 
         out = ""
 
         out += '''
         <table class="admin_wvar" cellspacing="0">
         <tr><th colspan="4" class="adminheaderleft">%(menu)s</th></tr>
         <tr>
         <td>0.&nbsp;<small><a href="format_templates_manage?ln=%(ln)s">%(close_editor)s</a></small>&nbsp;</td>
         <td>1.&nbsp;<small><a href="format_template_show?ln=%(ln)s&amp;bft=%(filename)s">%(template_editor)s</a></small>&nbsp;</td>
         <td>2.&nbsp;<small>%(modify_template_attributes)s</small>&nbsp;</td>
         <td>3.&nbsp;<small><a href="format_template_show_dependencies?ln=%(ln)s&amp;bft=%(filename)s">%(check_dependencies)s</a></small>&nbsp;</td>
         </tr>
         </table><br/>
         ''' % {'ln':ln,
                'menu':_("Menu"),
                'filename':filename,
                'close_editor': _("Close Editor"),
                'modify_template_attributes': _("Modify Template Attributes"),
                'template_editor': _("Template Editor"),
                'check_dependencies': _("Check Dependencies")
                }
 
         disabled = ""
         readonly = ""
         if not editable:
             disabled = 'disabled="disabled"'
             readonly = 'readonly="readonly"'
 
         out += '''
         <form action="format_template_update_attributes?ln=%(ln)s&amp;bft=%(filename)s" method="POST">
 	''' % {'ln':ln,
 	       'filename':filename}
 
         if new:
             #Offer the possibility to make a duplicate of existing format template code
             out += '''
              <table><tr>
              <th class="adminheaderleft">Make a copy of format template:&nbsp;[<a href="%(siteurl)s/help/admin/bibformat-admin-guide#addFormatTemplate">?</a>]</th>
              </tr>
             <tr>
             <td><select tabindex="1" name="duplicate" id="duplicate" %(readonly)s>
             <option value="">None (Blank Page)</option>
             <option value="" disabled="disabled">-------------</option>
             ''' %  {'siteurl': CFG_SITE_URL,
                     'readonly':readonly}
             for (o_filename, o_name) in all_templates:
                 out += '''<option value="%(template_filename)s">%(template_name)s</option>''' % {'template_name':o_name,
                                                                                                  'template_filename': o_filename}
             out += ''' </select>
             </td></tr></table>'''
 
         out += '''
         <table><tr>
         <th colspan="2" class="adminheaderleft">%(name)s attributes&nbsp;[<a href="%(siteurl)s/help/admin/bibformat-admin-guide#attrsFormatTemplate">?</a>]</th>
         </tr>
         <tr>
         <td class="admintdright">
 
         <input type="hidden" name="key" value="%(name)s"/>
         <label for="name">%(name_label)s</label>:&nbsp;</td>
         <td><input tabindex="2" name="name" type="text" id="name" size="25" value="%(name)s" %(readonly)s/>
         <input type="hidden" value="%(filename)s"/>
         </td>
         </tr>
         ''' % {"name": name,
                'ln':ln,
                'filename':filename,
                'disabled':disabled,
                'readonly':readonly,
                'name_label': _("Name"),
                'siteurl':CFG_SITE_URL
                }
 
         out += '''
         <tr>
         <td class="admintdright" valign="top"><label for="description">%(description_label)s</label>:&nbsp;</td>
         <td><textarea tabindex="3" name="description" id="description" rows="4" cols="25" %(readonly)s>%(description)s</textarea> </td>
         </tr>
         <tr>
         <td>&nbsp;</td>
         <td align="right"><input tabindex="6" class="adminbutton" type="submit" value="%(update_format_attributes)s" %(disabled)s/></td>
         </tr>
         </table></form>
         ''' % {"description": description,
                'ln':ln,
                'filename':filename,
                'disabled':disabled,
                'readonly':readonly,
                'description_label': _("Description"),
                'update_format_attributes': _("Update Format Attributes"),
                'siteurl':CFG_SITE_URL
                }
 
         return out
 
     def tmpl_admin_format_template_show_dependencies(self, ln, name, filename, output_formats, format_elements, tags):
         """
         Shows the dependencies (on elements) of the given format.
 
         @param name the name of the template
         @param filename the filename of the template
         @param format_elements the elements (and list of tags in each element) this template depends on
         @param output_formats the output format that depend on this template
         @param tags the tags that are called by format elements this template depends on.
         """
         _ = gettext_set_language(ln)    # load the right message language
 
         out = '''
         <table class="admin_wvar" cellspacing="0">
         <tr><th colspan="4" class="adminheaderleft">%(menu)s</th></tr>
         <tr>
         <td>0.&nbsp;<small><a href="format_templates_manage?ln=%(ln)s">%(close_editor)s</a>&nbsp;</small></td>
         <td>1.&nbsp;<small><a href="format_template_show?ln=%(ln)s&amp;bft=%(filename)s">%(template_editor)s</a></small>&nbsp;</td>
         <td>2.&nbsp;<small><a href="format_template_show_attributes?ln=%(ln)s&amp;bft=%(filename)s">%(modify_template_attributes)s</a></small>&nbsp;</td>
         <td>3.&nbsp;<small>%(check_dependencies)s</small>&nbsp;</td>
         </tr>
         </table>
         <table width="90%%" class="admin_wvar" cellspacing="0"><tr>
         <th class="adminheaderleft">Output Formats that use %(name)s</th>
         <th class="adminheaderleft">Format Elements used by %(name)s*</th>
         <th class="adminheaderleft">All Tags Called*</th>
         </tr>
         <tr>
         <td valign="top">&nbsp;<br/>
         ''' % {'ln':ln,
                'filename':filename,
                'menu': _("Menu"),
                'close_editor': _("Close Editor"),
                'modify_template_attributes': _("Modify Template Attributes"),
                'template_editor': _("Template Editor"),
                'check_dependencies': _("Check Dependencies"),
                'name': name }
 
         #Print output formats
         if len(output_formats) == 0:
             out += '<p align="center"><i>No output format uses this format template.</i></p>'
 
         for output_format in output_formats:
             name = output_format['names']['generic']
             filename = output_format['filename']
             out += ''' <a href="output_format_show?ln=%(ln)s&amp;bfo=%(filename)s">%(name)s</a>''' % {'filename':filename,
                                                                                                   'name':name,
                                                                                                   'ln':ln}
             if len(output_format['tags']) > 0:
                 out += "("+", ".join(output_format['tags'])+")"
             out += "<br/>"
 
         #Print format elements (and tags)
         out += '</td><td valign="top">&nbsp;<br/>'
         if len(format_elements) == 0:
             out += '<p align="center"><i>This format template uses no format element.</i></p>'
         for format_element in format_elements:
             name = format_element['name']
             out += ''' <a href="format_elements_doc?ln=%(ln)s#%(anchor)s">%(name)s</a>''' % {'name':"bfe_"+name.lower(),
                                                                                            'anchor':name.upper(),
                                                                                            'ln':ln}
             if len(format_element['tags']) > 0:
                 out += "("+", ".join(format_element['tags'])+")"
             out += "<br/>"
         #Print tags
         out += '</td><td valign="top">&nbsp;<br/>'
         if len(tags) == 0:
             out += '<p align="center"><i>This format template uses no tag.</i></p>'
         for tag in tags:
             out += '''%(tag)s<br/>''' % { 'tag':tag}
         out += '''
         </td>
         </tr>
         </table>
         <b>*Note</b>: Some tags linked with this format template might not be shown. Check manually.
         '''
         return out
 
     def tmpl_admin_format_template_show(self, ln, name, description, code, filename, ln_for_preview, pattern_for_preview, editable, content_type_for_preview, content_types):
         """
         Returns the editor for format templates. Edit 'format'
 
         @param ln language
         @param format the format to edit
         @param filename the filename of the template
         @param ln_for_preview the language for the preview (for bfo)
         @param pattern_for_preview the search pattern to be used for the preview (for bfo)
         @param editable True if we let user edit, else False
         @param code the code of the template of the editor
         @return editor for 'format'
         """
         _ = gettext_set_language(ln)    # load the right message language
 
         out = ""
 
         # If xsl, hide some options in the menu
         nb_menu_options = 4
         if filename.endswith('.xsl'):
             nb_menu_options = 2
 
         out += '''
         <style type="text/css">
             <!--
                 .ed_button {
                 font-size: x-small;
                 }
             -->
         </style>
         <script src="%(siteurl)s/admin/bibformat/js_quicktags.js" type="text/javascript"></script>
         <script type="text/javascript">
 
         function getByID( id ) {
             if (document.getElementById)
                 var returnVar = document.getElementById(id);
             else if (document.all)
                 var returnVar = document.all[id];
             else if (document.layers)
                 var returnVar = document.layers[id];
 
             return returnVar;
         }
 
         window.onresize= resizeViews;
         window.onload= prepareLayout;
 
         function prepareLayout(){
             resizeViews();
         }
 
         function resizeViews(){
             var myWidth = 0, myHeight = 0;
             if( typeof( window.innerWidth ) == 'number' ) {
                 //Non-IE
                 myWidth = window.innerWidth;
                 myHeight = window.innerHeight;
             } else if( document.documentElement && ( document.documentElement.clientWidth || document.documentElement.clientHeight ) ) {
                 //IE 6+ in 'standards compliant mode'
                 myWidth = document.documentElement.clientWidth;
                 myHeight = document.documentElement.clientHeight;
             } else if( document.body && ( document.body.clientWidth || document.body.clientHeight ) ) {
                 //IE 4 compatible
                 myWidth = document.body.clientWidth;
                 myHeight = document.body.clientHeight;
             }
 
             if (myHeight <= 400) {
                 getByID("code").style.height=10;
                 getByID("previewiframe").style.height=10;
 
             } else{
                 getByID("code").style.height=((myHeight-400)/2);
                 getByID("previewiframe").style.height=((myHeight-400)/2);
             }
 
             getByID("previewiframe").style.height=200;
 
             // Resize documentation
             var height = document.documentElement.clientHeight;
             height -= getByID('shortDocFrame').offsetTop
             //height -= 20;
             getByID('shortDocFrame').style.height = height +"px";
         }
 
         </script>
         <table class="admin_wvar" cellspacing="0">
         <tr><th colspan="%(nb_menu_options)s" class="adminheaderleft">%(menu)s</th></tr>
         <tr>
         <td>0.&nbsp;<small><a href="format_templates_manage?ln=%(ln)s">%(close_editor)s</a></small>&nbsp;</td>
         <td>1.&nbsp;<small>%(template_editor)s</small>&nbsp;</td>
         ''' % {'ln': ln, 'filename': filename,
                'menu': _("Menu"),
                'label_show_doc': _("Show Documentation"),
                'label_hide_doc': _("Hide Documentation"),
                'close_editor': _("Close Editor"),
                'modify_template_attributes': _("Modify Template Attributes"),
                'template_editor': _("Template Editor"),
                'check_dependencies': _("Check Dependencies"),
                'nb_menu_options': nb_menu_options,
                'siteurl': CFG_SITE_SECURE_URL or CFG_SITE_URL
                }
 
         if not filename.endswith('.xsl'):
             out +='''<td>2.&nbsp;<small><a href="format_template_show_attributes?ln=%(ln)s&amp;bft=%(filename)s">%(modify_template_attributes)s</a></small>&nbsp;</td>
             <td>3.&nbsp;<small><a href="format_template_show_dependencies?ln=%(ln)s&amp;bft=%(filename)s">%(check_dependencies)s</a></small>&nbsp;</td>
             ''' % {'ln': ln, 'filename': filename,
                'menu': _("Menu"),
                'label_show_doc': _("Show Documentation"),
                'label_hide_doc': _("Hide Documentation"),
                'close_editor': _("Close Editor"),
                'modify_template_attributes': _("Modify Template Attributes"),
                'template_editor': _("Template Editor"),
                'check_dependencies': _("Check Dependencies"),
                'siteurl': CFG_SITE_SECURE_URL or CFG_SITE_URL
                }
 
         out +='''
         </tr>
         </table>
 
         <script type="text/javascript">
 
         function toggle_doc_visibility(){
         var doc = document.getElementById('docTable');
         var link = document.getElementById('docLink');
         if (doc.style.display=='none'){
         doc.style.display = '';
         link.innerHTML = "%(label_hide_doc)s"
         } else {
         doc.style.display = 'none';
         link.innerHTML = "%(label_show_doc)s"
         }
         }
 
         </script>
 
         ''' % {'ln': ln, 'filename': filename,
                'menu': _("Menu"),
                'label_show_doc': _("Show Documentation"),
                'label_hide_doc': _("Hide Documentation"),
                'close_editor': _("Close Editor"),
                'modify_template_attributes': _("Modify Template Attributes"),
                'template_editor': _("Template Editor"),
                'check_dependencies': _("Check Dependencies"),
                'siteurl': CFG_SITE_SECURE_URL or CFG_SITE_URL
                }
 
         disabled = ""
         readonly = ""
         toolbar = """<script type="text/javascript">edToolbar('%s/admin/bibformat/bibformatadmin.py/format_elements_doc?ln=%s');</script>""" % (CFG_SITE_URL, ln)
         if not editable:
             disabled = 'disabled="disabled"'
             readonly = 'readonly="readonly"'
             toolbar = ''
 
         #First column: template code and preview
         out += '''
         <table width="90%%" cellspacing="5">
         <tr>
         <td valign="top">
         <form action="format_template_show_preview_or_save?ln=%(ln)s&amp;bft=%(filename)s" method="POST" target="previewiframe">
         <table width="100%%" id="mainTable"><tr>
         <th class="adminheaderleft"><div style="float:left;">Format template code</div>
         <div style="float:right;">
         <a id="docLink" href="#" onclick="toggle_doc_visibility()">%(label_hide_doc)s</a>
         </div>
         </th>
         </tr>
         <tr><td colspan="2" id="codetd">
         %(toolbar)s
         <textarea name="code" id="code" rows="25" %(readonly)s
         style="width:100%%">%(code)s</textarea>
         <script type="text/javascript">var edCanvas = document.getElementById('code');</script>
         </td></tr>
         <tr><td align="right" valign="top">
         <input type="submit" class="adminbutton" name="save_action" value="Save Changes" %(disabled)s/>
         </td>
         </tr>
         </table>
         <table width="100%%">
         <tr><th class="adminheaderleft">
         Preview
         </th>
         </tr>
         <tr><td align="right" valign="top" style="font-size: small;">
         <nobr>
         <label for="content_type_for_preview">Content-type (MIME):</label> <select id="content_type_for_preview" name="content_type_for_preview" style="font-size: x-small;">
         ''' %  {'ln':ln,
                 'siteurl':CFG_SITE_URL,
                 'filename':filename,
                 'label_hide_doc':_("Hide Documentation"),
                 'code':code,
                 'readonly':readonly,
                 'disabled':disabled,
                 'toolbar':toolbar}
 
         for content_type in content_types:
             if content_type == content_type_for_preview:
                 out += '''<option value="%(content_type)s" selected="selected">%(content_type)s</option>''' % {'content_type':content_type}
             else:
                 out += '''<option value="%(content_type)s">%(content_type)s</option>''' % {'content_type':content_type}
 
         out += '''
         </select></nobr>
         <nobr><label for="ln_for_preview">Language:</label> <select id="ln_for_preview" name="ln_for_preview" style="font-size: x-small;">
         '''
 
         for lang in language_list_long():
             if lang[0] == ln_for_preview:
                 out += '''<option value="%(ln)s" selected="selected">%(language)s</option>''' % {'ln':lang[0],
                                                                                                  'language':lang[1]}
             else:
                 out += '''<option value="%(ln)s">%(language)s</option>''' % {'ln':lang[0], 'language':lang[1]}
 
 
         out += '''
         </select></nobr>
         &nbsp;
         <nobr><label for="pattern_for_preview">Search Pattern: </label><input type="text" value="%(pattern_for_preview)s" size="8" name="pattern_for_preview" id="pattern_for_preview" style="font-size: x-small;"/></nobr>&nbsp;
 
         <input type="submit" class="adminbutton" name="preview_action" value="Reload Preview"/>
         </td>
         </tr>
         <tr><td>
         <iframe src ="%(siteurl)s/admin/bibformat/bibformatadmin.py/format_template_show_preview_or_save?ln=%(ln)s&amp;ln_for_preview=%(ln_for_preview)s&amp;pattern_for_preview=%(pattern_for_preview)s&amp;bft=%(filename)s" name="previewiframe" id="previewiframe" width="100%%" height="400"></iframe>
 
         </td></tr>
         </table>
         </form>
         </td>
         ''' % {'code':code, 'ln':ln,
                'siteurl':CFG_SITE_URL, 'filename':filename,
                'ln_for_preview':ln_for_preview,
                'pattern_for_preview':pattern_for_preview
                }
 
 
         #Second column Print documentation
 
         out += '''
         <td valign="top" id="docTable">
         <table width="100%%"><tr>
         <th class="adminheaderleft">Elements Documentation</th>
         </tr>
         </table>
         <table width="100%%"><tr>
         <td class="admintdright">
         <form action="format_template_show_short_doc?ln=%(ln)s" method="POST" target="shortDocFrame">
         <nobr><label for="search_doc_pattern">Search for:&nbsp;</label><input type="text" size="15" name="search_doc_pattern" id="search_doc_pattern" value=""/> <input type="submit" class="adminbutton" name="search_in_doc" value="Search" /></nobr>
         </form>
         </td>
         </tr>
         </table>
 
         <iframe name="shortDocFrame" id="shortDocFrame" src ="%(siteurl)s/admin/bibformat/bibformatadmin.py/format_template_show_short_doc?ln=%(ln)s" height="90%%" width="98%%"></iframe>
 
         </td>
         </tr>
         </table>
         ''' % {'siteurl':CFG_SITE_URL, 'ln':ln}
 
         return out
 
     def tmpl_admin_format_template_show_short_doc(self, ln, format_elements):
         """
         Prints the format element documentation in a condensed way to display
         inside format template editor.
 
         This page is different from others: it is displayed inside a <iframe>
         tag in template tmpl_admin_format_template_show.
 
         @param ln language
         @param format_elements a list of format elements structures as returned by get_format_elements
         """
         out = '''
         <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
         <html>
         <head>
         <title>BibFormat Short Documentation of Format Elements</title>
         <link rel="stylesheet" href="%(siteurl)s/img/cds.css">
         <script src="%(siteurl)s/admin/bibformat/js_quicktags.js" type="text/javascript"></script>
         <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
         </head>
         <body>
 
         <script type="text/javascript">
 
 	function toggle_visibility(element, show, r,g,b){
 	var children = element.childNodes
 	var child
 	for(x=0; x<children.length; x++){
 	  if (children[x].id == 'params'){
 	    child = children[x]
 	  }
 	}
 	if (show=='show'){
 	element.style.background='rgb(201, 218, 255)'
 	element.style.cursor='pointer'
 	child.style.display=''
 	} else {
 	element.style.background="rgb("+r+","+g+","+b+")"
 	child.style.display='none'
 	}
 	}
         ///// FROM JS QuickTags ///////
 
         // Copyright (c) 2002-2005 Alex King
         // http://www.alexking.org/
         //
         // Licensed under the LGPL license
         // http://www.gnu.org/copyleft/lesser.html
 
         function insertAtCursor(myField, myValue) {
         //IE support
         if (document.selection) {
         myField.focus();
         sel = document.selection.createRange();
         sel.text = myValue;
         }
         //MOZILLA/NETSCAPE support
         else if (myField.selectionStart || myField.selectionStart == '0') {
         var startPos = myField.selectionStart;
         var endPos = myField.selectionEnd;
         myField.value = myField.value.substring(0, startPos)
         + myValue
         + myField.value.substring(endPos, myField.value.length);
         } else {
         myField.value += myValue;
         }
         }
         ///// END FROM JS QuickTags  /////
 
         function insert_my_code_into_container(code){
         var codeArea = parent.document.getElementById("code");
         if (codeArea.readOnly == false){
         //var clean_code = code.replace(=#,'="');
         //clean_code = clean_code.replace(# ,'" ');
         insertAtCursor(codeArea, code);
         }
         }
         </script>
         ''' % {'siteurl': CFG_SITE_SECURE_URL or CFG_SITE_URL}
 
         if len(format_elements) == 0:
             out += '''
             <em>No format elements found</em>
             '''
         else:
             line = 0
 
             #Print elements doc
             for format_element in format_elements:
                 format_attributes = format_element['attrs']
                 row_content = ""
                 name = format_attributes['name']
                 description = format_attributes['description']
                 params = [x['name'] + '=\u0022'+x['default']+'\u0022' for x in format_attributes['params']]
                 builtin_params = [x['name'] + '=\u0022'+x['default']+'\u0022' for x in format_attributes['builtin_params']]
                 code = "<BFE_" + name + ' ' + ' '.join(builtin_params)+ ' ' + ' '.join(params) +"/>"
 
                 if line % 2:
                     row_content += '''<div onmouseover="toggle_visibility(this, 'show', 235, 247, 255);"
                     onmouseout="toggle_visibility(this, 'hide', 235, 247, 255);"
                     style="background-color: rgb(235, 247, 255);"
                     onclick="insert_my_code_into_container('%s')"
                     ><hr/>''' % code
                 else:
                     row_content += '''<div onmouseover="toggle_visibility(this, 'show', 255, 255, 255);"
                     onmouseout="toggle_visibility(this, 'hide', 255, 255, 255);"
                     onclick="insert_my_code_into_container('%s')"
                     >''' % code
 
                 params_names = ""
                 for param in format_attributes['params']:
                     params_names += "<b>"+param['name'] +'</b> '
 
                 row_content += '''
                 <code> <b>&lt;BFE_%(name)s/&gt;</b><br/></code>
                 <small>%(description)s.</small>
                 <div id="params" style="display:none;">
                 <ul>
                 ''' % {'params_names':params_names, 'name':name, 'description':description}
 
                 for param in format_attributes['params']:
                     row_content += '''
                     <li><small><b>%(name)s</b>:&nbsp;%(description)s</small></li>
                     ''' % {'name':param['name'],
                            'description':param['description']}
                 for param in format_attributes['builtin_params']:
                     row_content += '''
                     <li><small><b>%(name)s</b>:&nbsp;%(description)s</small></li>
                     ''' % {'name':param['name'],
                            'description':param['description']}
 
                 row_content += '</ul></div>'
                 if line % 2:
                     row_content += '''<hr/></div>'''
                 else:
                     row_content += '</div>'
                 line += 1
 
                 out += row_content
 
 
         out += '''</body></html>'''
         return out
 
     def tmpl_admin_format_templates_management(self, ln, formats):
         """
         Returns the management console for formats. Includes list of formats and
         associated administration tools.
 
         @param ln language
         @param formats a list of dictionaries with formats attributes
         @return format management console as html
         """
 
         _ = gettext_set_language(ln)    # load the right message language
 
 
         #top of the page and table header
         out = '''
         <table class="admin_wvar" cellspacing="0">
         <tr><th colspan="4" class="adminheaderleft">%(menu)s</th></tr>
         <tr>
         <td>0.&nbsp;<small>%(manage_format_templates)s</small>&nbsp;</td>
         <td>1.&nbsp;<small><a href="output_formats_manage?ln=%(ln)s">%(manage_output_formats)s</a>&nbsp;</td>
         <td>2.&nbsp;<small><a href="format_elements_doc?ln=%(ln)s">%(format_elements_documentation)s</a></small>&nbsp;</td>
         <td>3.&nbsp;<small><a href="kb_manage?ln=%(ln)s">%(manage_knowledge_bases)s</a></small>&nbsp;</td>
         </tr>
         </table>
 
         <p>From here you can create, edit or delete formats templates.
         Have a look at the <a href="format_elements_doc?ln=%(ln)s">format elements documentation</a> to
         learn which elements you can use in your templates.</p>
 
 
         <table class="admin_wvar" width="95%%" cellspacing="0">
         <tr>
         <th class="adminheaderleft" >&nbsp;</th>
         <th class="adminheaderleft" >%(name)s</th>
         <th class="adminheaderleft" >%(description)s</th>
         <th class="adminheaderleft" >%(status)s</th>
         <th class="adminheaderleft" >%(last_modification_date)s</th>
         <th class="adminheadercenter" >%(action)s&nbsp;&nbsp;&nbsp;[<a href="%(siteurl)s/help/admin/bibformat-admin-guide#formatTemplates">?</a>]</th>
         </tr>
         ''' % {'name':_("Name"),
                'description':_("Description"),
                'menu': _("Menu"),
                'status':_("Status"),
                'last_modification_date':_("Last Modification Date"),
                'action':_("Action"),
                'ln':ln,
                'manage_output_formats':_("Manage Output Formats"),
                'manage_format_templates':_("Manage Format Templates"),
                'format_elements_documentation':_("Format Elements Documentation"),
                'manage_knowledge_bases':_("Manage Knowledge Bases"),
                'siteurl':CFG_SITE_URL}
 
         #table content: formats names, description and buttons
         if len(formats) == 0:
             out += '''<tr>
             <td colspan="6" class="admintd" align="center"><em>No format</em></td>
             </tr>'''
         else:
             line = 0
             for attrs in formats:
                 filename = attrs['filename']
                 if filename == "":
                     filename = "&nbsp;"
                 name = attrs['name']
                 if name == "":
                     name = "&nbsp;"
                 description = attrs['description']
                 if description == "":
                     description = "&nbsp;"
                 last_mod_date = attrs['last_mod_date']
                 status = attrs['status']
 
                 disabled = ""
                 if not attrs['editable']:
                     disabled = 'disabled="disabled"'
 
                 style = 'style="vertical-align: middle;'
                 if line % 2:
                     style = 'style="vertical-align: middle;background-color: rgb(235, 247, 255);'
                 line += 1
 
                 row_content = '''<tr>
                 <td class="admintdright" %(style)s">&nbsp;</td>
                 <td class="admintdleft" %(style)s white-space: nowrap;"><a href="format_template_show?bft=%(filename)s&amp;ln=%(ln)s">%(name)s</a></td>
                 <td class="admintdleft" %(style)s" >%(description)s</td>
                 <td class="admintdleft" %(style)s white-space: nowrap;" >%(status)s</td>
                 <td class="admintdleft" %(style)s white-space: nowrap;" >%(last_mod_date)s</td>
                 <td class="admintd" %(style)s white-space: nowrap;">
                 <form method="post" action="format_template_delete?ln=%(ln)s&amp;bft=%(filename)s">
                 <input class="adminbutton" type="submit" value="%(delete)s" %(disabled)s/>
                 </form>
                 </td>
                 </tr>
                 ''' % {'filename':filename,
                        'name':name,
                        'description':description,
                        'ln':ln,
                        'style':style,
                        'disabled':disabled,
                        'last_mod_date':last_mod_date,
                        'status':status,
                        'delete':_("Delete")
                        }
                 out += row_content
 
         #table footer, buttons and bottom of the page
         out += '''
         <tr>
         <td align="left" colspan="3">
         <form action="format_templates_manage?ln=%(ln)s">
         <input type="hidden" name="checking" value="1"></input>
         <input class="adminbutton" type="submit" value="%(extensive_checking)s"/>
         </form>
         </td>
         <td align="right" colspan="3">
         <form action="format_template_add?ln=%(ln)s">
         <input class="adminbutton" type="submit" value="%(add_format_template)s"/>
         </form>
 
         </td>
         </tr>
         </table>
 
         ''' % {'ln':ln,
                'add_format_template':_("Add New Format Template"),
                'extensive_checking':_("Check Format Templates Extensively")}
 
         return out
 
     def tmpl_admin_output_formats_management(self, ln, output_formats):
         """
         Returns the main management console for formats. Includes list of formats and
         associated administration tools.
         @param ln language
         @param output_formats a list of output formats
         @return main management console as html
         """
 
         _ = gettext_set_language(ln)    # load the right message language
 
 
         #top of the page and table header
         out = '''
         <table class="admin_wvar" cellspacing="0">
         <tr><th colspan="4" class="adminheaderleft">%(menu)s</th></tr>
         <tr>
         <td>0.&nbsp;<small><a href="format_templates_manage?ln=%(ln)s">%(manage_format_templates)s</a></small>&nbsp;</td>
         <td>1.&nbsp;<small>%(manage_output_formats)s</small>&nbsp;</td>
         <td>2.&nbsp;<small><a href="format_elements_doc?ln=%(ln)s">%(format_elements_documentation)s</a></small>&nbsp;</td>
         <td>3.&nbsp;<small><a href="kb_manage?ln=%(ln)s">%(manage_knowledge_bases)s</a></small>&nbsp;</td>
         </tr>
         </table>
 
         <p>From here you can add, edit or delete output formats available for collections. Output formats define which template to use. <br/>To edit templates go to the <a href="format_templates_manage?ln=%(ln)s">template administration page</a>.</p>
 
         <table class="admin_wvar" width="95%%" cellspacing="0">
         <tr>
         <th class="adminheaderleft" >&nbsp;</th>
         <th class="adminheaderleft" ><a href="output_formats_manage?ln=%(ln)s&amp;sortby=code">%(code)s</a></th>
         <th class="adminheaderleft" ><a href="output_formats_manage?ln=%(ln)s&amp;sortby=name">%(name)s</a></th>
         <th class="adminheaderleft" >%(description)s</th>
         <th class="adminheaderleft" >%(status)s</th>
         <th class="adminheaderleft" >%(last_modification_date)s</th>
         <th class="adminheadercenter" >%(action)s&nbsp;&nbsp;&nbsp;[<a href="%(siteurl)s/help/admin/bibformat-admin-guide#outputFormats">?</a>]</th>
         </tr>
         ''' %  {'code':_("Code"),
                 'name':_("Name"),
                 'description':_("Description"),
                 'status':_("Status"),
                 'last_modification_date':_("Last Modification Date"),
                 'action':_("Action"),
                 'ln':ln,
                 'manage_output_formats':_("Manage Output Formats"),
                 'manage_format_templates':_("Manage Format Templates"),
                 'format_elements_documentation':_("Format Elements Documentation"),
                 'manage_knowledge_bases':_("Manage Knowledge Bases"),
                 'menu': _("Menu"),
                 'siteurl':CFG_SITE_URL}
 
         #table content: formats names, description and buttons
         if len(output_formats) == 0:
             out += '''<tr>
             <td colspan="5" class="admintd" align="center"><em>No format</em></td>
             </tr>'''
         else:
             line = 0
             for output_format in output_formats:
                 format_attributes = output_format['attrs']
                 name = format_attributes['names']['generic']
                 if name == "":
                     name = "&nbsp;"
                 description = format_attributes['description']
                 if description == "":
                     description = "&nbsp;"
                 code = format_attributes['code']
                 if code == "":
                     code = "&nbsp;"
 
                 last_mod_date = output_format['last_mod_date']
                 status = output_format['status']
                 disabled = ""
                 if not output_format['editable']:
                     disabled = 'disabled="disabled"'
 
                 style = "vertical-align: middle;"
                 if line % 2:
                     style = 'vertical-align: middle; background-color: rgb(235, 247, 255);'
                 line += 1
                 row_content = '''<tr>
                 <td class="admintdright" style="%(style)s">&nbsp;</td>
                 <td class="admintdleft" style="white-space: nowrap; %(style)s">
                     <a href="output_format_show?bfo=%(code)s">%(code)s</a>
                 </td>
                 <td class="admintdleft" style="white-space: nowrap; %(style)s">
                     <a href="output_format_show?bfo=%(code)s">%(name)s</a>
                 </td>
                 <td class="admintdleft"style="%(style)s" >
                       %(description)s
                 </td>
                 <td class="admintd" style="white-space: nowrap; %(style)s" >%(status)s</td>
                 <td class="admintdleft" style="white-space: nowrap;%(style)s" >%(last_mod_date)s</td>
                 <td class="admintd" style="white-space: nowrap; %(style)s">
                 <form method="POST" action="output_format_delete?ln=%(ln)s&amp;bfo=%(code)s">
                 <input class="adminbutton" type="submit" value="Delete" %(disabled)s />
                 </form>
                 </td>
                 </tr>
                 ''' % {'style':style,
                        'code':code,
                        'description':description,
                        'name':name,
                        'ln':ln,
                        'disabled':disabled,
                        'last_mod_date':last_mod_date,
                        'status':status}
 
                 out += row_content
 
         #table footer, buttons and bottom of the page
         out += '''
         <tr>
         <td align="right" colspan="7">
         <form method="GET" action="output_format_add?ln=%(ln)s">
         <input class="adminbutton" type="submit" value="%(add_output_format)s"/>
         </form>
         </td>
         </tr>
         </table>
         ''' % {'ln':ln,
                'add_output_format':_("Add New Output Format")}
 
         return out
 
     def tmpl_admin_output_format_show(self, ln, code, name, rules, default, format_templates, editable):
         """
         Returns the content of an output format
 
         rules is an ordered list of dict (sorted by evaluation order),
         with keys 'field', 'value' and 'template'
 
         IMPORTANT: we display rules evaluation index starting at 1 in
         interface, but we start internally at 0
 
         @param ln language
         @param code the code of the output to show
         @param name the name of this output format
         @param rules the list of rules for this output format
         @param default the default format template of the output format
         @param format_templates the list of format_templates
         @param editable True if we let user edit, else False
         @return the management console for this output format
         """
         _ = gettext_set_language(ln)
         out = '''
           <table class="admin_wvar" cellspacing="0">
         <tr><th colspan="4" class="adminheaderleft">%(menu)s</th></tr>
         <tr>
         <td>0.&nbsp;<small><a href="output_formats_manage?ln=%(ln)s">%(close_output_format)s</a></small>&nbsp;</td>
         <td>1.&nbsp;<small>%(rules)s</small>&nbsp;</td>
         <td>2.&nbsp;<small><a href="output_format_show_attributes?ln=%(ln)s&amp;bfo=%(code)s">%(modify_output_format_attributes)s</a></small>&nbsp;</td>
         <td>3.&nbsp;<small><a href="output_format_show_dependencies?ln=%(ln)s&amp;bfo=%(code)s">%(check_dependencies)s</a></small>&nbsp;</td>
         </tr>
         </table>
         <p>Define here the rules the specifies which template to use for a given record.</p>
 
         ''' % {'code':code,
                'ln':ln,
                'menu':_("menu"),
                'close_output_format':_("Close Output Format"),
                'rules':_("Rules"),
                'modify_output_format_attributes':_("Modify Output Format Attributes"),
                'check_dependencies':_("Check Dependencies")
                }
 
         out += '''
         <form name="rules" action="output_format_show?ln=%(ln)s&amp;bfo=%(code)s" method="post">
         <table>
         <tr>
         <td>
         ''' % {'ln': ln, 'code':code}
 
         disabled = ""
         readonly = ""
         if not editable:
             disabled = 'disabled="disabled"'
             readonly = 'readonly="readonly"'
 
         if len(rules) == 0:
             out += '''<p align="center"><em>No special rule</em></p>'''
 
         line = 1
         for rule in rules:
             out += '''
             <table align="center" class="admin_wvar" cellspacing="0">
             <tr>
             '''
 
             out += '''
             <td rowspan="2" class="adminheader" style="vertical-align: middle;">'''
             if line > 1:
                 out += '''
                 <input type="image" src="%(siteurl)s/img/smallup.gif" alt="Increase priority of rule %(row)s" name="+ %(row)s" value="+ %(row)s" %(disabled)s/></div>
                 ''' % {'siteurl':CFG_SITE_URL, 'row':line, 'disabled':disabled}
 
             out += '''<div>%(row)s</div>''' % { 'row':line}
             if line < len(rules):
                 out += '''
                 <input type="image" src="%(siteurl)s/img/smalldown.gif" alt="Decrease priority of rule %(row)s" name="- %(row)s" value="- %(row)s" %(disabled)s/>
                 ''' % {'siteurl':CFG_SITE_URL,
                        'row':line,
                        'disabled':disabled}
 
             out += '''</td>
             <td class="adminheaderleft">&nbsp;</td>
             '''
 
             out += '''
             <td class="adminheaderleft" style="white-space: nowrap;">
             Use template&nbsp;<select name="r_tpl" %(disabled)s>''' % {'disabled':disabled}
 
 
             for template in format_templates:
                 attrs = format_templates[template]['attrs']
                 attrs['template'] = template
                 if template.endswith('.xsl') and not \
                    attrs['name'].endswith(' (XSL)'):
                     attrs['name'] += ' (XSL)'
 
                 if template != rule['template']:
                     out += '''<option value="%(template)s">%(name)s</option>''' % attrs
                 else:
                     out += '''<option value="%(template)s" selected="selected">%(name)s</option>''' % attrs
 
             if not format_templates.has_key(rule['template']) and rule['template'] != "":
                 #case where a non existing format template is use in output format
                 #we need to add it as option
                 out += '''<option value="%s" selected="selected">%s</option>''' % (rule['template'],
                                                                                    rule['template'])
 
             ################ FIXME remove when migration is done ####################
             #Let the user choose a non existing template, that is a placeholder
             #meaning that the template has not been migrated
             selected = ''
             if rule['template'] == 'migration_in_progress':
                 selected = 'selected="selected"'
             if CFG_PATH_PHP or selected != '':
                 out += '''<option disabled="disabled">For Migration:</option>'''
                 out += '''<option value="migration_in_progress" %s>defined in old BibFormat</option>''' % selected
             ################               END FIXME             ####################
 
             out += '''</select>&nbsp;if field
             &nbsp;<input type="text" name="r_fld" value="%(field)s" size="10" %(readonly)s/>&nbsp;is equal to&nbsp;<input type="text" value="%(value)s" name="r_val" %(readonly)s/>
             </td>
             <td class="adminheaderright" style="vertical-align: middle;">
             &nbsp;[<a href="%(siteurl)s/help/admin/bibformat-admin-guide#rulesOutputFormat">?</a>]
             </td>
             </tr>
             ''' % {'siteurl':CFG_SITE_URL,
                    'field': rule['field'],
                    'value':rule['value'],
                    'readonly':readonly}
 
             out += '''
             <tr>
             <td colspan ="3" class="adminheaderright" style="vertical-align: middle; white-space: nowrap;">
             <input type="submit" class="adminbutton" name="r_upd" value="%(remove_rule_label)s %(row)s" %(disabled)s/>&nbsp;
             </td>
             </tr>
             </table>
             ''' % {'remove_rule_label': _("Remove Rule"),
                    'row':line,
                    'disabled':disabled}
             line += 1
 
         out += '''
         <table width="100%" align="center" class="admin_wvar" cellspacing="0">
         <tr>
         '''
 
         out += '''
         <td width="30" class="adminheaderleft">&nbsp;</td>
         <td class="adminheaderleft">By default use <select id="default" name="default" %(disabled)s>''' % {'disabled':disabled}
 
         for template in format_templates:
             attrs = format_templates[template]['attrs']
             attrs['template'] = template
             if template.endswith('.xsl') and not \
                    attrs['name'].endswith(' (XSL)'):
                 attrs['name'] += ' (XSL)'
 
             if template  != default:
                 out += '''<option value="%(template)s">%(name)s</option>''' % attrs
             else:
                 out += '''<option value="%(template)s" selected="selected">%(name)s</option>''' % attrs
 
         if not format_templates.has_key(default) and default!= "":
             #case where a non existing format tempate is use in output format
             #we need to add it as option (only if it is not empty string)
             out += '''<option value="%s" selected="selected">%s</option>''' % (default,default)
 
         ################ FIXME remove when migration is done ####################
         #Let the user choose a non existing template, that is a placeholder
         #meaning that the template has not been migrated
         selected = ''
         if default == 'migration_in_progress':
             selected = 'selected="selected"'
         if CFG_PATH_PHP or selected != '':
             out += '''<option disabled="disabled">For Migration:</option>'''
             out += '''<option value="migration_in_progress" %s>defined in old BibFormat</option>''' % selected
         ################               END FIXME             ####################
 
         out += '''</select></td>
         </tr>
         </table>
         <div align="right">
         <input tabindex="6" class="adminbutton" type="submit" name="r_upd" value="%(add_new_rule_label)s" %(disabled)s/>
         <input tabindex="7" class="adminbutton" type="submit" name="r_upd" value="%(save_changes_label)s" %(disabled)s/>
         </div>
         </td>
         </tr>
         </table>
         </form>
         ''' % {'add_new_rule_label':_("Add New Rule"),
              'save_changes_label':_("Save Changes"),
              'disabled':disabled
              }
 
         return out
 
     def tmpl_admin_output_format_show_attributes(self, ln,
                                                  name,
                                                  description,
                                                  content_type,
                                                  code,
                                                  names_trans,
                                                  editable,
                                                  visible):
         """
         Returns a page to change output format name and description
 
         names_trans is an ordered list of dicts with keys 'lang' and 'trans'
 
         @param ln language
         @param name the name of the format
         @param description the description of the format
         @param code the code of the format
         @param content_type the (MIME) content type of the ouput format
         @param names_trans the translations in the same order as the languages from get_languages()
         @param editable True if we let user edit, else False
         @param visible True if output format should be shown in list of available output formats
         @return editor for output format attributes
         """
         _ = gettext_set_language(ln)    # load the right message language
 
         out = ""
 
         out += '''
         <table class="admin_wvar" cellspacing="0">
         <tr><th colspan="4" class="adminheaderleft">%(menu)s</th></tr>
         <tr>
         <td>0.&nbsp;<small><a href="output_formats_manage?ln=%(ln)s">%(close_output_format)s</a></small>&nbsp;</td>
         <td>1.&nbsp;<small><a href="output_format_show?ln=%(ln)s&amp;bfo=%(code)s">%(rules)s</a></small>&nbsp;</td>
         <td>2.&nbsp;<small>%(modify_output_format_attributes)s</small>&nbsp;</td>
         <td>3.&nbsp;<small><a href="output_format_show_dependencies?ln=%(ln)s&amp;bfo=%(code)s">%(check_dependencies)s</a></small>&nbsp;</td>
         </tr>
         </table><br/>
         ''' % {'ln':ln,
                'code':code,
                'close_output_format':_("Close Output Format"),
                'rules':_("Rules"),
                'modify_output_format_attributes':_("Modify Output Format Attributes"),
                'check_dependencies':_("Check Dependencies"),
                'menu':_("Menu")
                }
 
         disabled = ""
         readonly = ""
         if not editable:
             disabled = 'disabled="disabled"'
             readonly = 'readonly="readonly"'
 
         out += '''
         <form action="output_format_update_attributes?ln=%(ln)s&amp;bfo=%(code)s" method="POST">
         <table class="admin_wvar" cellspacing="0">
         <tr>
         <th colspan="2" class="adminheaderleft">
         Output Format Attributes&nbsp;[<a href="%(siteurl)s/help/admin/bibformat-admin-guide#attrsOutputFormat">?</a>]</th>
         </tr>
         <tr>
         <td class="admintdright"><label for="outputFormatCode">Code</label>:&nbsp;</td>
         <td><input tabindex="0" name="code" type="text" id="outputFormatCode" maxlength="6" size="6" value="%(code)s" %(readonly)s/></td>
         </tr>
         <tr>
         <td class="admintdright">Visibility:&nbsp;</td>
         <td><input tabindex="1" name="visibility" type="checkbox" id="outputFormatVisibility" %(visibility)s %(disabled)s value="1" /><small><label for="outputFormatVisibility">Show in list of available output formats (on public pages)</label></small></td>
         </tr>
         <td class="admintdright"><label for="outputFormatContentType">Content type</label>:&nbsp;</td>
         <td><input tabindex="2" name="content_type" type="text" id="outputFormatContentType" size="25"  value="%(content_type)s" %(readonly)s/> <small>Mime content-type. Specifies how the browser should handle this output.</small></td>
         <tr>
         <td class="admintdright"><label for="outputFormatName">Name</label>:&nbsp;</td>
         <td><input tabindex="3" name="name" type="text" id="outputFormatName" size="25" value="%(name)s" %(readonly)s/></td>
         </tr>
         ''' % {'name': name,
                'ln':ln,
                'code':code,
                'content_type':content_type,
                'readonly':readonly,
                'siteurl':CFG_SITE_URL,
                'visibility': visible==1 and 'checked="checked"' or '',
                'disabled':disabled}
 
         #Add translated names
         i = 3
         for name_trans in names_trans:
             i += 1
             out += '''
             <tr>
             <td class="admintdright"><label for="outputFormatName%(i)s">%(lang)s Name</label>:&nbsp;</td>
             <td><input tabindex="%(i)s" name="names_trans" type="text" id="outputFormatName%(i)s" size="25" value="%(name)s" %(readonly)s/></td>
             </tr>''' % {'name':name_trans['trans'],
                         'lang':name_trans['lang'],
                         'i':i,
                         'readonly':readonly}
         #Description and end of page
         out += '''
         <tr>
         <td  class="admintdright" valign="top"><label for="outputFormatDescription">Description</label>:&nbsp;</td>
         <td><textarea tabindex="%(tabindexdesc)s" name="description" id="outputFormatDescription" rows="4" cols="25" %(readonly)s>%(description)s</textarea> </td>
         </tr>
         <tr>
         <td colspan="2" align="right"><input tabindex="%(tabindexbutton)s" class="adminbutton" type="submit" value="Update Output Format Attributes" %(disabled)s/></td>
         </tr>
         </table>
         </form>
 
         ''' % {'description': description,
                'tabindexdesc': i + 1,
                'tabindexbutton': i + 2,
                'readonly':readonly,
                'disabled':disabled}
 
         return out
 
 
     def tmpl_admin_output_format_show_dependencies(self, ln, name, code, format_templates):
         """
         Shows the dependencies of the given format.
 
         @param name the name of the output format
         @param code the code of the output format
         @param format_templates format templates that depend on this format (and also elements and tags)
         """
         _ = gettext_set_language(ln)    # load the right message language
         out = '''
         <table class="admin_wvar">
         <tr><th colspan="4" class="adminheaderleft" cellspacing="0">%(menu)s</th></tr>
         <tr>
         <td>0.&nbsp;<small><a href="output_formats_manage?ln=%(ln)s">%(close_output_format)s</a></small>&nbsp;</td>
         <td>1.&nbsp;<small><a href="output_format_show?ln=%(ln)s&amp;bfo=%(code)s">%(rules)s</a></small>&nbsp;</td>
         <td>2.&nbsp;<small><a href="output_format_show_attributes?ln=%(ln)s&amp;bfo=%(code)s">%(modify_output_format_attributes)s</a></small>&nbsp;</td>
         <td>3.&nbsp;<small>%(check_dependencies)s</small>&nbsp;</td>
         </tr>
         </table><br/>
         <table width="90%%" class="admin_wvar" cellspacing="0"><tr>
 
         <th class="adminheaderleft">Format Templates that use %(name)s</th>
         <th class="adminheaderleft">Format Elements used by %(name)s</th>
         <th class="adminheaderleft">Tags Called*</th>
         </tr>
         ''' % {'name': name,
                'code': code,
                'ln':ln,
                'close_output_format':_("Close Output Format"),
                'rules':_("Rules"),
                'modify_output_format_attributes':_("Modify Output Format Attributes"),
                'check_dependencies':_("Check Dependencies"),
                'menu': _("Menu")
                }
 
         if len(format_templates) == 0:
             out += '''<tr><td colspan="3"><p align="center">
             <i>This output format uses no format template.</i></p></td></tr>'''
 
         for format_template in format_templates:
             name = format_template['name']
             filename = format_template['filename']
             out += '''<tr><td><a href="format_template_show?bft=%(filename)s&amp;ln=%(ln)s">%(name)s</a></td>
             <td>&nbsp;</td><td>&nbsp;</td></tr>''' % {'filename':filename,
                                                       'name':name,
                                                       'ln':ln}
             for format_element in format_template['elements']:
                 name = format_element['name']
                 filename = format_element['filename']
                 out += '''<tr><td>&nbsp;</td>
                 <td><a href="format_elements_doc?ln=%(ln)s#%(anchor)s">%(name)s</a></td>
                 <td>&nbsp;</td></tr>''' % {'anchor':name.upper(),
                                            'name':name,
                                            'ln':ln}
                 for tag in format_element['tags']:
                     out += '''<tr><td>&nbsp;</td><td>&nbsp;</td>
                     <td>%(tag)s</td></tr>''' % {'tag':tag}
 
         out += '''
         </table>
         <b>*Note</b>: Some tags linked with this format template might not be shown. Check manually.
         '''
         return out
 
     def tmpl_admin_format_elements_documentation(self, ln, format_elements):
         """
         Returns the main management console for format elements. Includes list of formats elements and
         associated administration tools.
 
         @param ln language
         @param formats a list of dictionaries with formats elements attributes
         @return main management console as html
         """
 
         _ = gettext_set_language(ln)    # load the right message language
 
 
         #top of the page and table header
         out = '''
         <table class="admin_wvar" cellspacing="0">
         <tr><th colspan="4" class="adminheaderleft">%(menu)s</th></tr>
         <tr>
         <td>0.&nbsp;<small><a href="format_templates_manage?ln=%(ln)s">%(manage_format_templates)s</a></small>&nbsp;</td>
         <td>1.&nbsp;<small><a href="output_formats_manage?ln=%(ln)s">%(manage_output_formats)s</a></small>&nbsp;</td>
         <td>2.&nbsp;<small>%(format_elements_documentation)s</small>&nbsp;</td>
         <td>3.&nbsp;<small><a href="kb_manage?ln=%(ln)s">%(manage_knowledge_bases)s</a></small>&nbsp;</td>
         </tr>
         </table>
 
 
         <p>Here you can read the APIs of the formats elements, the elementary bricks for formats.</p>
         ''' % {'ln':ln,
                'menu': _("Menu"),
                'manage_output_formats':_("Manage Output Formats"),
                'manage_format_templates':_("Manage Format Templates"),
                'format_elements_documentation':_("Format Elements Documentation"),
                'manage_knowledge_bases':_("Manage Knowledge Bases")
                }
 
 
         #table content: formats names, description and actions
         if len(format_elements) == 0:
             out += '''
             <em>No format elements found</em>
             '''
         else:
 
             #Print summary of elements (name + decription)
             out += '''<h2>Summary table of elements</h2>'''
             out += '''<table width="90%">'''
             for format_element in format_elements:
                 format_attributes = format_element['attrs']
                 out += '''
                 <tr>
                 <td>
                 <code><a href="#%(name)s">&lt;BFE_%(name)s/&gt;</a></code>
                 </td>
                 <td>
                 %(description)s
                 </td>
                 </tr>
                 ''' % format_attributes
             out += "</table>"
 
             #Print details of elements
             out += '''<h2>Details of elements</h2>'''
             for format_element in format_elements:
                 format_attributes = format_element['attrs']
                 element_name = format_attributes['name']
                 out += self.tmpl_admin_print_format_element_documentation(ln, element_name, format_attributes)
 
         #table footer, buttons and bottom of the page
         out += '''
         <table align="center" width="95%">
         </table>'''
         return out
 
     def tmpl_admin_print_format_element_documentation(self, ln, name, attributes, print_see_also=True):
         """
         Prints the formatted documentation of a single element. Used in main documentation of element and
         in creation of floater for Dreamweaver.
 
         @param ln language
         @param name the name of the element
         @param attributes the attributes of the element, as returned by get_format_element_attrs_from_*
         @param print_see_also if True, prints links to other sections related to element
         """
         params_names = ""
         for param in attributes['params']:
             params_names += "<b>"+param['name'] +'</b>="..." '
 
         out = '''
         <a name="%(name)s"></a><h3>%(name)s</h3>
 
         <b>&lt;BFE_%(name)s</b> %(params_names)s<b>/&gt;</b><br/><br/>
         &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<em>%(description)s.</em><br/><br/>
         &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<b>Parameters:</b><br/>
         ''' % {'params_names': params_names,
                'name':name,
                'description': attributes['description']}
         for param in attributes['params']:
             out += '''
             &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
             <code>%(name)s</code> - %(description)s. ''' % param
             if param['default'] != "":
                 default = cgi.escape(param['default'])
                 if default.strip() == "":
                     default = "&nbsp;"
                 out += '''
                 Default value is &laquo;<code>%s</code>&raquo;
                 ''' % default
 
             out += '<br/>'
 
         for param in attributes['builtin_params']:
             out += '''
             &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
             <code>%(name)s</code> - %(description)s. ''' % param
             if param['default'] != "":
                 default = cgi.escape(param['default'])
                 if default.strip() == "":
                     default = "&nbsp;"
                 out += '''
                 Default value is &laquo;<code>%s</code>&raquo;
                 ''' % default
 
             out += '<br/>'
 
         if print_see_also:
             out += '''<br/>
             &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
             <b>See also:</b><br/>'''
 
             for element in attributes['seealso']:
                 element_name = element.split('.')[0].upper()
                 out += '''
                 &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
                 <a href="#%(name)s">Element <em>%(name)s</em></a><br/>''' % {'name':element_name}
             out += '''
             &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
             <a href ="format_element_show_dependencies?ln=%(ln)s&amp;bfe=%(bfe)s">Dependencies of this element</a><br/>
             &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
             <a href ="validate_format?ln=%(ln)s&amp;bfe=%(bfe)s">The correctness of this element</a><br/>
             &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
             <a href ="format_element_test?ln=%(ln)s&amp;bfe=%(bfe)s">Test this element</a><br/>
             ''' % {'ln':ln, 'bfe':name}
 
         return out
 
     def tmpl_admin_format_element_show_dependencies(self, ln, name, format_templates, tags):
         """
         Shows the dependencies of the given format element
 
         @param name the name of the element
         @param format_templates format templates that depend on this element
         @param tags the tags that are called by this format element
         """
         out = '''
         <p>Go back to <a href="format_elements_doc?ln=%(ln)s#%(name)s">documentation</a></p>
         ''' % {'ln':ln, 'name':name.upper()}
 
         out += ''' <table width="90%" class="admin_wvar" cellspacing="0"><tr>'''
         out += '''
         <th class="adminheaderleft">Format Templates that use %(name)s</th>
         <th class="adminheaderleft">Tags Called*</th>
         </tr>
         <tr>
         <td>&nbsp;<br/>''' % {"name": name}
 
 
         #Print format elements (and tags)
         if len(format_templates) == 0:
             out += '''<p align="center">
             <i>This format element is not used in any format template.</i></p>'''
         for format_template in format_templates:
             name = format_template['name']
             filename = format_template['filename']
             out += '''<a href="format_template_show?ln=%(ln)s&amp;bft=%(filename)s">%(name)s</a><br/>''' % {'filename':filename,
                                                                                                         'name':name,
                                                                                                         'ln':ln}
 
         #Print tags
         out += "</td><td>&nbsp;<br/>"
         if len(tags) == 0:
             out += '''<p align="center">
             <i>This format element uses no tag.</i></p>'''
         for tag in tags:
             out += '''%(tag)s<br/>''' % {'tag':tag}
         out += '''
         </td>
         </tr>
         </table>
         <b>*Note</b>: Some tags linked with this format template might not be shown. Check manually.
         '''
         return out
 
     def tmpl_admin_format_element_test(self, ln, bfe, description, param_names, param_values, param_descriptions, result):
         """
         Prints a page where the user can test the given format element with his own parameters.
 
         @param ln language
         @param bfe the format element name
         @param description a description of the element
         @param param_names a list of parameters names/labels
         @param param_values a list of values for parameters
         @param param_descriptions a list of description for parameters
         @param result the result of the evaluation
         """
 
         out = '''
         <p>Go back to <a href="format_elements_doc?ln=%(ln)s#%(name)s">documentation</a></p>
         ''' % {'ln':ln, 'name':bfe.upper()}
 
         out += '''
         <h3>&lt;BFE_%(bfe)s /&gt;</h3>
         <p>%(description)s</p>
         <table width="100%%"><tr><td>
         <form method="post" action="format_element_test?ln=%(ln)s&amp;bfe=%(bfe)s">
         <table>
         ''' % {'bfe':bfe, 'ln':ln, 'description':description }
 
         for i in range(len(param_names)):
             out += '''
             <tr>
             <td class="admintdright">%(name)s</td>
             <td class="admintdright"><input type="text" name="param_values" value="%(value)s"/></td>
             <td class="admintdleft">%(description)s&nbsp;</td>
             </tr>
             ''' % {'name':param_names[i],
                    'value':param_values[i],
                    'description':param_descriptions[i]}
 
         out += '''
         <tr><td colspan="2" class="admintdright"><input type="submit" class="adminbutton" value="Test!"/></td>
         <td>&nbsp;</td>
         </tr>
         </table>
         </form>
         <fieldset style="display:inline;margin-left:auto;margin-right:auto;">
         <legend>Result:</legend>%(result)s</fieldset>
 
         ''' % {'result':result}
 
         out += '''
         </td></tr><tr><td>
         '''
         #out += self.tmpl_admin_print_format_element_documentation(ln, bfe, attributes, False)
         out += '''</td></tr></table>'''
         return out
 
     def tmpl_admin_add_format_element(self, ln):
         """
         Shows how to add a format element (mainly doc)
 
         @param ln language
         """
         _ = gettext_set_language(ln)    # load the right message language
 
         out = '''
         <p>To add a new basic element (only fetch the value of a field, without special post-processing), go to the <a href="%(siteurl)sadmin/bibindex/bibindexadmin.py/field">BibEdit "Manage Logical Fields"</a> page and add a name for a field. Make sure that the name is unique and corresponds well to the field. For example, to add an element that fetch the value of field 245__%, add a new logical field with name "title" and field "245__%". Then in your template, call BFE_TITLE to print the title.</p>
         <p>To add a new complex element (for eg. special formatting of the field, condition on the value, etc.) you must go to the lib/python/invenio/bibformat_elements directory of your Invenio installation, and add a new format element file. Read documentation for more information.</p>
         ''' % {'siteurl':CFG_SITE_URL}
 
         return out
 
-    def tmpl_admin_kbs_management(self, ln, kbs):
+    def tmpl_admin_kbs_management(self, ln, kbs, search=""):
         """
         Returns the main management console for knowledge bases.
 
         @param ln language
         @param kbs a list of dictionaries with knowledge bases attributes
+        @param search hunt for this string in kb's
         @return main management console as html
         """
 
         _ = gettext_set_language(ln)    # load the right message language
 
         #top of the page and table header
         out = '''
         <table class="admin_wvar" cellspacing="0">
         <tr><th colspan="4" class="adminheaderleft">%(menu)s</th></tr>
         <tr>
         <td>0.&nbsp;<small><a href="format_templates_manage?ln=%(ln)s">%(manage_format_templates)s</a></small>&nbsp;</td>
         <td>1.&nbsp;<small><a href="output_formats_manage?ln=%(ln)s">%(manage_output_formats)s</a></small>&nbsp;</td>
         <td>2.&nbsp;<small><a href="format_elements_doc?ln=%(ln)s">%(format_elements_documentation)s</a></small>&nbsp;</td>
         <td>3.&nbsp;<small>%(manage_knowledge_bases)s</small>&nbsp;</td>
         </tr>
         </table>
+
+        <!--make a search box-->
+        <table class="admin_wvar" cellspacing="0">
+                 <tr><td>
+                 <form action="kb_manage">
+                 Search for a term in knowledge bases:
+                 <input type="text" name="search" value="%(search)s" />
+                 <input type="hidden" name="ln" value="%(ln)s" />
+                 <input type="submit" class="adminbutton" value="Search">
+                 </form>
+                 </td></tr></table>
+
+
         <table class="admin_wvar" width="95%%" cellspacing="0">
         <tr>
         <th class="adminheaderleft" >&nbsp;</th>
         <th class="adminheaderleft" >Name</th>
         <th class="adminheaderleft" >Description</th>
         <th class="adminheadercenter" >Action&nbsp;&nbsp;&nbsp;[<a href="%(siteurl)s/help/admin/bibformat-admin-guide#KBs">?</a>]</th>
-        </tr>''' % {'ln':ln,
-                    'menu':_("Menu"),
-                    'manage_output_formats':_("Manage Output Formats"),
-                    'manage_format_templates':_("Manage Format Templates"),
-                    'format_elements_documentation':_("Format Elements Documentation"),
-                    'manage_knowledge_bases':_("Manage Knowledge Bases"),
-                    'siteurl':CFG_SITE_URL}
+        </tr>''' % {'ln': ln,
+                    'search': search,
+                    'menu': _("Menu"),
+                    'manage_output_formats': _("Manage Output Formats"),
+                    'manage_format_templates': _("Manage Format Templates"),
+                    'format_elements_documentation': _("Format Elements Documentation"),
+                    'manage_knowledge_bases': _("Manage Knowledge Bases"),
+                    'siteurl': CFG_SITE_URL}
+
 
         #table content: kb names, description and actions
         if len(kbs) == 0:
             out += '''<tr>
             <td colspan="5" class="admintd" align="center"><em>No Knowledge Base</em></td>
             </tr>'''
         else:
             line = 0
             for kb_attributes in kbs :
                 kb_attributes['style'] = ""
                 if line % 2:
                     kb_attributes['style'] = 'background-color: rgb(235, 247, 255);'
                 line += 1
                 kb_attributes['ln'] = ln
                 kb_attributes['siteurl'] = CFG_SITE_URL
+                kb_attributes['search'] = search
                 row_content = '''<tr>
                 <td class="admintdright" style="vertical-align: middle; %(style)s">&nbsp;</td>
-                <td class="admintdleft" style="vertical-align: middle; %(style)s white-space: nowrap;"><a href="kb_show?ln=%(ln)s&amp;kb=%(id)s">%(name)s</a></td>
+                <td class="admintdleft" style="vertical-align: middle; %(style)s white-space: nowrap;"><a href="kb_show?ln=%(ln)s&amp;kb=%(id)s&amp;search=%(search)s">%(name)s</a></td>
                 <td class="admintdleft"style="vertical-align: middle; %(style)s">%(description)s</td>
                 <td class="admintd" style="vertical-align: middle; %(style)s white-space: nowrap;">
                 <form action="kb_delete?ln=%(ln)s" type="POST">
                 <input type="submit" class="adminbutton" value="Delete">
                 <input type="hidden" id="kb" name="kb" value="%(id)s">
                 </form>
                 </td>
                 </tr>
                 ''' % kb_attributes
                 out += row_content
 
         #table footer, buttons and bottom of the page
         out += ''' </table>
         <table align="center" width="95%">
         <tr>
         <td align="left" valign="top">&nbsp;</td>
         '''
         out += '''
         <td align="left">
         <form action="kb_add?ln=%(ln)s">
         <input class="adminbutton" type="submit" value="Add New Knowledge Base"/>
         </form>
         </td>
 
         <td align="right">
         <form method="post" action="kb_add?ln=%(ln)s&amp;kbtype=taxonomy">
         <input class="adminbutton" type="submit" value="Add New Taxonomy"/>
         </form>
         </td>
 
         </tr>
         </table>''' % {'ln': ln}
 
         return out
 
-    def tmpl_admin_kb_show(self, ln, kb_id, kb_name, mappings, sortby, startat=0, kb_type=None):
+    def tmpl_prevnextlink(self, porn, ln, kb_id, sortby, startat):
+        """
+        An aux routine to make "Next" link
+        @param porn p for previous, n for next
+        @param ln language
+        @param kb_id knowledge base id
+        @param sortby sort by to or from
+        @param startat start at this pair
+        """
+        _ = gettext_set_language(ln)    # load the right message language
+        label = _("Next")
+        if porn == 'p':
+            label = _("Previous")
+        return '<a href="kb_show?ln=%(ln)s&amp;kb=%(kb_id)s&amp;sortby=%(sortby)s&amp;startat=%(newstart)s">%(label)s</a>'% { 'ln':ln, 'kb_id':kb_id, 'sortby':sortby, 'newstart': str(startat), 'label': label }
+
+    def tmpl_admin_kb_show(self, ln, kb_id, kb_name, mappings, sortby, startat=0, kb_type=None, search=""):
         """
         Returns the content of a knowledge base.
 
         @param ln language
         @param kb_id the id of the kb
         @param kb_name the name of the kb
-        @param content a list of dictionaries with mappings
+        @param mappings a list of dictionaries with mappings
         @param sortby the sorting criteria ('from' or 'to')
         @param startat start showing the mappings from number x. Usefull for large kb's.
-        @kb_type None or 't' meaning taxonomy. If taxonomy, show 'broader term/narrower term' instead of map from/to
+        @param kb_type None or 't' meaning taxonomy. If taxonomy, show 'broader term/narrower term' instead of map from/to
+        @param search focus on this left side if it is in the KB
         @return main management console as html
         """
 
         _ = gettext_set_language(ln)    # load the right message language
 
         #top of the page and  main table that split screen in two parts
+
         out = '''
         <table class="admin_wvar" cellspacing="0">
         <tr><th colspan="4" class="adminheaderleft">%(menu)s</th></tr>
         <tr>
         <td>0.&nbsp;<small><a href="kb_manage?ln=%(ln)s&amp;sortby=%(sortby)s">%(close)s</a></small>&nbsp;</td>
         <td>1.&nbsp;<small>%(mappings)s</small>&nbsp;</td>
         <td>2.&nbsp;<small><a href="kb_show_attributes?ln=%(ln)s&amp;kb=%(kb_id)s&amp;sortby=%(sortby)s">%(attributes)s</a></small>&nbsp;</td>
         <td>3.&nbsp;<small><a href="kb_show_dependencies?ln=%(ln)s&amp;kb=%(kb_id)s&amp;sortby=%(sortby)s">%(dependencies)s</a></small>&nbsp;</td>
         </tr>
         </table> ''' % {'ln':ln,
                         'kb_id':kb_id,
                         'sortby':sortby,
                         'close': _("Close Editor"),
                         'mappings': _("Knowledge Base Mappings"),
                         'attributes':_("Knowledge Base Attributes"),
                         'dependencies':_("Knowledge Base Dependencies"),
                         'menu': _("Menu")}
 
+        #Define some constants
+        try:
+            startati = int(startat)
+        except ValueError:
+            startati = 0
+
+        hereyoucan = _("Here you can add new mappings to this base and change the base attributes.")
 
         out += '''
-        <p>Here you can add new mappings to this base and change the base attributes.</p>
+        <p>
         <table width="100%" align="center">
         <tr>
         '''
 
         #First column of table: add mapping form
         out += '''
         <td width="300" valign="top">
 
         <form name="addNewMapping"
         action="kb_add_mapping?ln=%(ln)s&amp;kb=%(kb_id)s&amp;sortby=%(sortby)s&amp;forcetype=no&amp;kb_type=%(kb_type)s"
         method="post">''' % {'ln':ln, 'kb_id':kb_id, 'sortby':sortby, 'kb_type': kb_type}
 
         mapfromstring = _("Map From")
         maptostring = _("To")
         if kb_type == 't':
             mapfromstring = _("Broader term")
             maptostring = _("Narrower term")
         out += '''
         <table class="admin_wvar" width="100%%" cellspacing="0">
         <tr>
         <th colspan="2" class="adminheaderleft">Add New Mapping &nbsp;[<a href="%(siteurl)s/help/admin/bibformat-admin-guide#addMappingKB">?</a>]</th>
         </tr>
+
         <tr>
         <td class="admintdright"><label for="mapFrom"><span style="white-space: nowrap;">%(mapfrom)s</span></label>:&nbsp;</td>
         <td><input tabindex="1" name="mapFrom" type="text" id="mapFrom" size="25"/></td>
         </tr>
         <tr>
         <td class="admintdright"><label for="mapTo">%(mapto)s</label>:&nbsp;</td>
         <td><input tabindex="2" name="mapTo" type="text" id="mapTo" size="25"/></td>
         </tr>
+
         <tr>
         <td colspan="2" align="right"><input tabindex="3" class="adminbutton" type="submit" value="Add new Mapping"/></td>
         </tr>
         </table>
         </form>
         </td>
         ''' % {'siteurl':CFG_SITE_URL, 'mapfrom': mapfromstring, 'mapto': maptostring }
 
+        #calculate if prev/next are needed
+        #add prev/next buttons if needed
+        prevlink = ""
+        nextlink = ""
+
+        if startati > 0:
+            newstart=startati-MAX_MAPPINGS
+            if newstart < 0:
+                newstart = 0
+            prevlink = self.tmpl_prevnextlink('p', ln, kb_id, sortby, newstart)
+
+        if len(mappings) > startati+MAX_MAPPINGS:
+            #all of them were not shown yet
+            newstart = startati+MAX_MAPPINGS
+            nextlink = self.tmpl_prevnextlink('n', ln, kb_id, sortby, newstart)
+
         #Second column: mappings table
         #header and footer
         out += '''
         <td valign="top">
 
         <table class="admin_wvar">
         <thead>
+        <!--prev/next-->
+        <tr>
+        <td>%(prevlink)s</td><td>%(nextlink)s</td>
+        </tr>
+
         <tr>
         <th class="adminheaderleft" width="25">&nbsp;</th>
         <th class="adminheaderleft" width="34%%"><a href="kb_show?ln=%(ln)s&amp;kb=%(kb_id)s&amp;sortby=from">%(mapfrom)s</a></th>
         <th class="adminheaderleft">&nbsp;</th>
         <th class="adminheaderleft" width="34%%"><a href="kb_show?ln=%(ln)s&amp;kb=%(kb_id)s&amp;sortby=to">%(mapto)s</a></th>
         <th class="adminheadercenter" width="25%%">Action&nbsp;&nbsp;&nbsp;[<a href="%(siteurl)s/help/admin/bibformat-admin-guide#removeMappingKB">?</a>]</th>
         </tr>
         </thead>
         <tfoot>
         <tr>
         <td colspan="5">&nbsp;</td>
         </tr>
         </tfoot>
         <tbody>
         ''' % {'ln':ln,
                'kb_id':kb_id,
-               'siteurl':CFG_SITE_URL, 'mapfrom': mapfromstring, 'mapto': maptostring }
-
-        try:
-            startati = int(startat)
-        except ValueError:
-            startati = 0
+               'siteurl':CFG_SITE_URL,
+               'mapfrom': mapfromstring, 'mapto': maptostring,
+               'prevlink': prevlink, 'nextlink': nextlink }
 
         #table content: key, value and actions
         if len(mappings) == 0:
             out += '''
             <tr>
             <td colspan="5" class="admintd" align="center"><em>Knowledge base is empty</em></td>
             </tr></tbody>'''
         else:
             line = 0
             tabindex_key = 6
             tabindex_value = 7
             tabindex_save_button = 8
             mnum = 0 #current iteration in mappings
             for mapping in mappings:
                 #roll to startat
                 mnum += 1
                 if mnum > startati and mnum <= startati+MAX_MAPPINGS:
                     style = "vertical-align: middle;"
                     if line % 2:
                         style += 'background-color: rgb(235, 247, 255);'
                     line += 1
                     tabindex_key += 3
                     tabindex_value += 3
                     tabindex_save_button += 3
-
                     row_content = '''
                     <tr>
                     <td colspan="5">
                     <form action="kb_edit_mapping?ln=%(ln)s&amp;kb=%(kb_id)s&amp;sortby=%(sortby)s" name="%(key)s" method="post">
                     <table>
                     <tr>
                     <td class="admintdright" style="%(style)s" width="5">
                     &nbsp;
                     <input type="hidden" name="key" value="%(key)s"/>
                     </td>
                     <td class="admintdleft" style="%(style)s">
                         <input type="text" name="mapFrom" size="30" maxlength="255" value="%(key)s" tabindex="%(tabindex_key)s"/>
                     </td>
                     <td class="admintdleft" style="%(style)s white-space: nowrap;" width="5">=&gt;</td>
                     <td class="admintdleft"style="%(style)s">
                         <input type="text" name="mapTo" size="30" value="%(value)s" tabindex="%(tabindex_value)s">
                     </td>
                     <td class="admintd" style="%(style)s white-space: nowrap;">
                         <input class="adminbutton" type="submit" name="update" value="Save" tabindex="%(tabindex_save_button)s"/>
                         <input class="adminbutton" type="submit" name="delete"value="Delete"/></td>
                     </tr></table></form></td></tr>
                     ''' % {'key': mapping['key'],
                         'value':mapping['value'],
                         'ln':ln,
                         'style':style,
                         'tabindex_key': tabindex_key,
                         'tabindex_value': tabindex_value,
                         'tabindex_save_button': tabindex_save_button,
                         'kb_id':kb_id,
                         'sortby':sortby}
 
                     out += row_content
 
         #End of table
         out += '</tbody></table>'
 
-        #add prev/next buttons if needed
-        if startati > 0:
-            newstart=startati-MAX_MAPPINGS
-            if newstart < 0:
-                newstart = 0
-            out += '<a href="kb_show?ln=%(ln)s&amp;kb=%(kb_id)s&amp;sortby=%(sortby)s">%(Previous)s</a>' % { 'ln':ln, 'kb_id':kb_id, 'sortby':sortby, 'Previous': _("Previous") }
-
-        if len(mappings) > startati+MAX_MAPPINGS:
-            #all of them were not shown yet
-            out += '&nbsp;'
-            newstart = startati+MAX_MAPPINGS
-            out += '<a href="kb_show?ln=%(ln)s&amp;kb=%(kb_id)s&amp;sortby=%(sortby)s&amp;startat=%(newstart)s">%(Next)s</a>' % { 'ln':ln, 'kb_id':kb_id, 'sortby':sortby, 'newstart':str(newstart), 'Next': _("Next") }
+        out += prevlink+"&nbsp;"+nextlink
 
         out += '</td>'
         out+= '''
         <td width="20%">&nbsp;</td>
         </tr>
         </table>
         '''
         #add a note about exporting
+        export = CFG_SITE_URL+"/admin/bibformat/bibformatadmin.py/kb_export?kbname="+kb_name
         out += "<p>"+_("You can get a these mappings in textual format by: ")
-        out += CFG_SITE_URL+"/admin/bibformat/bibformatadmin.py/kb_export?kbname="+kb_name+"</p>"
+        out += "<a href=\""+export+"\">"+export+"</a><br/>"
+        out += _("And the KBA version by:")+" "
+        export = export+"&format=kba"
+        out += "<a href=\""+export+"\">"+export+"</a><br/>"
 
         #add script that will put focus on first field of "add mapping" form
         out += '''
         <script type="text/javascript">
         self.focus();document.addNewMapping.mapFrom.focus()
         </script>
         '''
 
         return out
 
     def tmpl_admin_kb_show_attributes(self, ln, kb_id, kb_name, description, sortby, kb_type=None):
         """
         Returns the attributes of a knowledge base.
 
         @param ln language
         @param kb_id the id of the kb
         @param kb_name the name of the kb
         @param description the description of the kb
         @param sortby the sorting criteria ('from' or 'to')
         @param kb_type: None or taxonomy
         @return main management console as html
         """
 
         _ = gettext_set_language(ln)    # load the right message language
 
         out = '''
         <table class="admin_wvar" cellspacing="0">
         <tr><th colspan="4" class="adminheaderleft">%(menu)s</th></tr>
         <tr>
         <td>0.&nbsp;<small><a href="kb_manage?ln=%(ln)s&amp;sortby=%(sortby)s">%(close)s</a></small>&nbsp;</td>
         <td>1.&nbsp;<small><a href="kb_show?ln=%(ln)s&amp;kb=%(kb_id)s&amp;sortby=%(sortby)s">%(mappings)s</a></small>&nbsp;</td>
         <td>2.&nbsp;<small>%(attributes)s</small>&nbsp;</td>
         <td>3.&nbsp;<small><a href="kb_show_dependencies?ln=%(ln)s&amp;kb=%(kb_id)s&amp;sortby=%(sortby)s">%(dependencies)s</a></small>&nbsp;</td>
         </tr>
         </table> ''' % {'ln':ln,
                         'kb_id':kb_id,
                         'sortby':sortby,
                         'close': _("Close Editor"),
                         'menu': _("Menu"),
                         'mappings': _("Knowledge Base Mappings"),
                         'attributes':_("Knowledge Base Attributes"),
                         'dependencies':_("Knowledge Base Dependencies")}
 
         out += '''
         <form name="updateAttributes"
         action="kb_update_attributes?ln=%(ln)s&amp;kb=%(kb_id)s&amp;sortby=%(sortby)s&kb_type=%(kb_type)s" method="post">
         <table class="admin_wvar" cellspacing="0">
         <tr>
 
         ''' % {'ln':ln,
                'kb_id':kb_id,
                'sortby':sortby,
                'kb_type':kb_type}
 
         out += '''
         <th colspan="2" class="adminheaderleft">%(kb_name)s attributes&nbsp;[<a href="%(siteurl)s/help/admin/bibformat-admin-guide#attrsKB">?</a>]</th>''' % {'kb_name': kb_name,
                                                                                                                                                        'siteurl': CFG_SITE_URL}
 
         out += '''
          </tr>
         <tr>
         <td class="admintdright">
         <input type="hidden" name="key" value="%(kb_id)s"/>
         <label for="name">Name</label>:&nbsp;</td>
         <td><input tabindex="4" name="name" type="text" id="name" size="25" value="%(kb_name)s"/></td>
         </tr>
         <tr>
         <td  class="admintdright" valign="top"><label for="description">Description</label>:&nbsp;</td>
         <td><textarea tabindex="5" name="description" id="description" rows="4" cols="25">%(kb_description)s</textarea> </td>
         </tr>
         <tr>
         <td>&nbsp;</td>
         <td align="right"><input tabindex="6" class="adminbutton" type="submit" value="Update Base Attributes"/></td>
         </tr>
         </table>
         </form></td>''' % {'kb_name': kb_name,
                            'kb_description': description,
                            'kb_id':kb_id}
 
         return out
 
     def tmpl_admin_kb_show_dependencies(self, ln, kb_id, kb_name, sortby, format_elements):
         """
         Returns the attributes of a knowledge base.
 
         @param ln language
         @param kb_id the id of the kb
         @param kb_name the name of the kb
         @param sortby the sorting criteria ('from' or 'to')
         @param format_elements the elements that use this kb
         """
 
         _ = gettext_set_language(ln)    # load the right message language
 
         out = '''
         <table class="admin_wvar" cellspacing="0">
         <tr><th colspan="4" class="adminheaderleft">%(menu)s</th></tr>
         <tr>
         <td>0.&nbsp;<small><a href="kb_manage?ln=%(ln)s&amp;sortby=%(sortby)s">%(close)s</a></small>&nbsp;</td>
         <td>1.&nbsp;<small><a href="kb_show?ln=%(ln)s&amp;kb=%(kb_id)s&amp;sortby=%(sortby)s">%(mappings)s</a></small>&nbsp;</td>
         <td>2.&nbsp;<small><a href="kb_show_attributes?ln=%(ln)s&amp;kb=%(kb_id)s&amp;sortby=%(sortby)s">%(attributes)s</a></small>&nbsp;</td>
         <td>3.&nbsp;<small>%(dependencies)s</small>&nbsp;</td>
         </tr>
         </table> <br/>''' % {'ln':ln,
                              'kb_id':kb_id,
                              'sortby':sortby,
                              'close': _("Close Editor"),
                              'menu' : _("Menu"),
                              'mappings': _("Knowledge Base Mappings"),
                              'attributes':_("Knowledge Base Attributes"),
                              'dependencies':_("Knowledge Base Dependencies")}
 
         out += ''' <table width="90%" class="admin_wvar" cellspacing="0"><tr>'''
         out += '''
         <th class="adminheaderleft">Format Elements used by %(name)s*</th>
         </tr>
         <tr>
         <td valign="top">&nbsp;''' % {"name": kb_name}
 
         if len(format_elements) == 0:
             out += '<p align="center"><i>This knowledge base is not used in any format elements.</i></p>'
         for format_element in format_elements:
             name = format_element['name']
             out += '''<a href="format_elements_doc?ln=%(ln)s#%(anchor)s">%(name)s</a><br/>''' % {'name':"bfe_"+name.lower(),
                                                                                                  'anchor':name.upper(),
                                                                                                  'ln':ln}
         out += '''
         </td>
         </tr>
         </table>
         <b>*Note</b>: Some knowledge base usages might not be shown. Check manually.
         '''
 
         return out
 
     def tmpl_dreamweaver_floater(self, ln, format_elements):
         """
         Returns the content of the BibFormat palette for Dreamweaver. This
         'floater' will let users of Dreamweaver to insert Format elements
         into their code right from the floater.
 
         @param format_elements an ordered list of format elements structures as returned by get_format_elements
         """
         names_list = [] # list of element names such as ['Authors', 'Title']
         codes_list = [] # list of element code such as ['<BFE_AUTHORS limit="" separator="," />', '<BFE_TITLE />']
         docs_list = [] # list of HTML doc for each element
 
         for format_element in format_elements:
             format_attributes = format_element['attrs']
             name = format_attributes['name']
             #description = format_attributes['description']
             params = [x['name'] + '="'+x['default']+'"' for x in format_attributes['params']]
             builtin_params = [x['name'] + '="'+x['default']+'"' for x in format_attributes['builtin_params']]
             code = ("<BFE_" + name + ' ' + ' '.join(builtin_params)+ ' ' + ' '.join(params) +"/>").replace("'", r"\'")
             doc = self.tmpl_admin_print_format_element_documentation(ln, name, format_attributes, print_see_also=False).replace("'", r"\'")
 
             names_list.append(name)
             codes_list.append(code)
             docs_list.append(doc)
 
         out = '''
         <!DOCTYPE HTML SYSTEM "-//Macromedia//DWExtension layout-engine5.0//floater">
         <html>
         <head>
         <!-- This file is to be used as floating panel for Dreamweaver.
 
              To install, drag and drop inside /Configuration/Floaters of your Dreamweaver
              application directory. You also have to enable a menu to open the floater:
              Edit file Menu.xml located inside /Configuration/Menus of your Dreamweaver
              application directory and copy-paste the following line in the menu you want
              (typically inside tag 'menu' with attribute id = 'DWMenu_Window_Others'):
              <menuitem name="BibFormat Elements" enabled="true" command="dw.toggleFloater('BibFormat_floater.html')" checked="dw.getFloaterVisibility('BibFormat_floater.html')" />
          -->
         <title>BibFormat Elements</title>
         <script language="JavaScript">
         var docs = new Array(%(docs)s);
         var codes = new Array(%(codes)s);
         function selectionChanged(){
             // get the selected node
             var theDOM = dw.getDocumentDOM();
             var theNode = theDOM.getSelectedNode();
 
             // check if node is a BibFormat Element
             if (theNode.nodeType == Node.COMMENT_NODE && theNode.data.length >= 5  && theNode.data.toLowerCase().substring(0,5) == "<bfe_"){
                 var names = document.elementsList.options;
                 for (i=0;i<names.length; i++){
                     if (names[i].text.toLowerCase() == theNode.data.split(' ')[0].toLowerCase() ||
                         names[i].text.toLowerCase() == theNode.data.split(' ')[0].toLowerCase().substring(5,theNode.data.length)){
                         document.elementsList.selectedIndex = i;
                         selectElement(document.elementsList);
                         return;
                     }
                 }
              }
         }
         function isAvailableInCodeView(){
             return true;
         }
 
         function selectElement(elementsList){
             document.infoBFE.innerHTML = docs[elementsList.selectedIndex];
         }
         function insertElement(){
             // insert selection into code
             var element_code = codes[document.elementsList.selectedIndex];
 
             // get the DOM
             var theDOM = dw.getDocumentDOM();
             var theDocEl = theDOM.documentElement;
             var theWholeDoc = theDocEl.outerHTML;
             // Get the offsets of the selection
             var theSel = theDOM.getSelection();
 
             theDocEl.outerHTML = theWholeDoc.substring(0,theSel[0]) + element_code + theWholeDoc.substring(theSel[1]);
 
         }
         </script>
         </head>
 
         <body>
         <table width="100%%" border="0" cellspacing="0" cellpadding="3">
           <tr>
             <td valign="top">
                 <select name="elementsList" id="elementsList" size="15" onChange="selectElement(this)">
                 %(names)s
                   </select><br/>
                   <input type="submit" name="Submit" value="Insert" onClick="insertElement()">
         </td>
             <td valign="top" width="100%%">
                 <div id="infoBFE">
                 <center>No Format Element selected. Select one from the list on the right.</center>
                 </div>
                 </td>
           </tr>
         </table>
         </body>
         </html>
         ''' % {'docs': ', '.join(["'"+x+"'" for x in docs_list]).replace('\n','\\n'),
                'codes': ', '.join(["'"+x+"'" for x in codes_list]).replace('\n','\\n'),
                'names': '\n'.join(['<option>'+x+'</option>' for x in names_list])}
 
         return out
 
     def tmpl_admin_validate_format(self, ln, errors):
         """
         Prints the errors of the validation of a format (might be any
         kind of format)
 
         @param ln language
         @param errors a list of tuples (error code, string error message)
         """
         _ = gettext_set_language(ln)    # load the right message language
         out = ""
 
         if len(errors) == 0:
             out += '''<span style="color: rgb(0, 255, 0);" >%s.</span>''' % _('No problem found with format')
         elif len(errors) == 1:
             out += '''<span style="color: rgb(255, 0, 0);" >%s:</span><br/>''' % _('An error has been found')
         else:
             out += '''<span style="color: rgb(255, 0, 0);" >%s:</span><br/>''' % _('The following errors have been found')
 
         for error in errors:
             out += error + "<br/>"
 
         return out
 
     def tmpl_admin_dialog_box(self, url, ln, title, message, options):
         """
         Prints a dialog box with given title, message and options
 
         @param url the url of the page that must process the result of the dialog box
         @param ln language
         @param title the title of the dialog box
         @param message a formatted message to display inside dialog box
         @param options a list of string options to display as button to the user
         """
 
         out = ""
         out += '''
         <div style="text-align:center;">
         <fieldset style="display:inline;margin-left:auto;margin-right:auto;">
         <legend>%(title)s:</legend>
         <p>%(message)s</p>
         <form method="post" action="%(url)s">
         ''' % {'title':title,
                'message':message,
                'url':url}
 
         for option in options:
             out += '''<input type="submit" class="adminbutton" name="chosen_option" value="%(value)s" />&nbsp;''' % {'value':option}
 
         out += '''</form></fieldset></div>'''
         return out
 
     def tmpl_select_rule_action(self, ln, kbid, left, right, leftorright, current, tuples):
         """
         Returns a form of actions for the user to descide what to do
         if there are overlapping rules.
         """
         _ = gettext_set_language(ln)    # load the right message language
 
-        gen=""
+        gen= _("Your rule")+": "+left+"->"+right+"<p>"
         if (leftorright=='left'):
-            gen = _("The left side of the rule ")+" ("+left+") "
+            gen += _("The left side of the rule ")+" ("+left+") "
         else:
-            gen = _("The right side of the rule ")+" ("+right+") "
-        gen+=_("already appears in these knowledge bases:")+"<br/>"
+            gen += _("The right side of the rule ")+" ("+right+") "
+        gen += _("already appears in these knowledge bases")+":<br/>"
         inkbs = []
         dontdoit = False
         for t in tuples:
             (kib, kb, l, r) = t
             if kb==current and leftorright=='left':
                 dontdoit=True
                 #two rules with same left side in the same kb? no.
             if inkbs.count(kb)==0:
                 inkbs.append(kb)
         kbstr=" ".join(inkbs)
         kbstr="<strong>"+kbstr+"</strong>"
         gen+=kbstr
         message = _("Please select action")
         optreplace = _("Replace the selected rules with this rule")
         optadd = _("Add this rule in the current knowledge base")+" ("+current+")"
         optcancel = _("Cancel: do not add this rule")
         formreplace = '''<form action="kb_add_mapping?ln=%(ln)s&amp;kb=%(kb_id)s&amp;forcetype=all"
                     method="post">
                     <input type="hidden" name="mapFrom" value="%(left)s"/>
                     <input type="hidden" name="mapTo" value="%(right)s"/>
                  ''' % {  'ln':ln, 'kb_id':kbid, 'left':left, 'right':right }
 
         #make a selectable list of kb's where to push the value..
         for t in tuples:
             (kib, kb, l, r) = t
             value=kb+"++++"+l+"++++"+r
             formreplace+="<input type=\"checkbox\" name=\"replacements\" value=\""+value+"\">"+kb+": "+l+"=>"+r+"</input><br/>"
 
         formreplace+=''' <input class="adminbutton"
                      type="submit" value="%(opt)s"/></form>''' % { 'opt':optreplace }
 
         formadd = '''<form action="kb_add_mapping?ln=%(ln)s&amp;kb=%(kb_id)s&amp;forcetype=curr" method="post">
                     <input type="hidden" name="mapFrom" value="%(left)s"/>
                     <input type="hidden" name="mapTo" value="%(right)s"/>
 	            <input class="adminbutton"
                      type="submit" value="%(opt)s"/></form>''' % { 'opt':optadd, 'ln':ln,
                                                                     'kb_id':kbid,
                                                                     'left':left, 'right':right }
         formcancel = '''<form action="kb_show?ln=%(ln)s&amp;kb=%(kb_id)s">
                     <input type="hidden" name="kb" value="%(kb_id)s">
 	            <input  class="adminbutton"
                      type="submit" value="%(opt)s"/></form>''' % { 'ln': ln, 'kb_id':kbid, 'opt':optcancel }
 
         if dontdoit:
             formadd = _("It is not possible to have two rules with the same left side in the same knowledge base.")+"<p>"
         out = gen+"<P>"+message+"<P>"+formadd+formcancel+"<P><P><P>"+formreplace
         return out
diff --git a/modules/bibformat/lib/bibformatadminlib.py b/modules/bibformat/lib/bibformatadminlib.py
index ff519cb50..3cc005707 100644
--- a/modules/bibformat/lib/bibformatadminlib.py
+++ b/modules/bibformat/lib/bibformatadminlib.py
@@ -1,1646 +1,1679 @@
 # -*- coding: utf-8 -*-
 ##
 ## $Id$
 ##
 ## This file is part of CDS Invenio.
 ## Copyright (C) 2002, 2003, 2004, 2005, 2006, 2007, 2008 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.
 
 """
 Handle requests from the web interface to configure BibFormat.
 """
 
 __revision__ = "$Id$"
 
 import os
 import re
 import stat
 import time
 import cgi
 
 from invenio.config import CFG_SITE_LANG, CFG_SITE_URL, CFG_ETCDIR
 from invenio.bibformat_config import \
      CFG_BIBFORMAT_TEMPLATES_PATH, \
      CFG_BIBFORMAT_OUTPUTS_PATH, \
      CFG_BIBFORMAT_ELEMENTS_PATH, \
      CFG_BIBFORMAT_FORMAT_TEMPLATE_EXTENSION
 from invenio.urlutils import wash_url_argument
 from invenio.errorlib import get_msgs_for_code_list
 from invenio.messages import gettext_set_language, wash_language, language_list_long
 from invenio.search_engine import perform_request_search, encode_for_xml
 from invenio import bibformat_dblayer
 from invenio import bibformat_engine
 
 import invenio.template
 bibformat_templates = invenio.template.load('bibformat')
 
 def getnavtrail(previous = '', ln=CFG_SITE_LANG):
     """Get the navtrail"""
     previous = wash_url_argument(previous, 'str')
     ln = wash_language(ln)
     _ = gettext_set_language(ln)
     navtrail = '''<a class="navtrail" href="%s/help/admin">%s</a> &gt; <a class="navtrail" href="%s/admin/bibformat/bibformatadmin.py?ln=%s">%s</a> ''' % \
                (CFG_SITE_URL, _("Admin Area"), CFG_SITE_URL, ln,  _("BibFormat Admin"))
     navtrail = navtrail + previous
     return navtrail
 
 def perform_request_index(ln=CFG_SITE_LANG, warnings=None, is_admin=False):
     """
     Returns the main BibFormat admin page.
 
     @param ln language
     @param warnings a list of messages to display at top of the page, that prevents writability in etc
     @param is_admin indicate if user is authorized to use BibFormat
     @return the main admin page
     """
     if warnings is not None and len(warnings) > 0:
         warnings = get_msgs_for_code_list(warnings, 'warning', ln)
         warnings = [x[1] for x in warnings] # Get only message, not code
 
     return bibformat_templates.tmpl_admin_index(ln, warnings, is_admin)
 
 def perform_request_format_templates_management(ln=CFG_SITE_LANG, checking=0):
     """
     Returns the main management console for format templates
 
     @param ln language
     @param checking the level of checking (0: basic, 1:extensive (time consuming) )
     @return the main page for format templates management
     """
 
 
     # Reload in case a format was changed
     bibformat_engine.clear_caches()
 
     # Get formats lists of attributes
     formats = bibformat_engine.get_format_templates(with_attributes=True)
     formats_attrs = []
     for filename in formats:
         attrs = formats[filename]['attrs']
         attrs['filename'] = filename
         if filename.endswith('.xsl'):
             attrs['name'] += ' (XSL)'
         attrs['editable'] = can_write_format_template(filename)
         path = CFG_BIBFORMAT_TEMPLATES_PATH + os.sep + filename
         try:
             attrs['last_mod_date'] = time.ctime(os.stat(path)[stat.ST_MTIME])
         except OSError:
             # File does not exist. Happens with temporary files
             # created by editors.
             continue
 
         status = check_format_template(filename, checking)
         if len(status) > 1 or (len(status)==1 and status[0][0] != 'ERR_BIBFORMAT_CANNOT_READ_TEMPLATE_FILE'):
             status = '''
             <a style="color: rgb(255, 0, 0);"
             href="%(siteurl)s/admin/bibformat/bibformatadmin.py/validate_format?ln=%(ln)s&amp;bft=%(bft)s">Not OK</a>
             ''' % {'siteurl':CFG_SITE_URL,
                    'ln':ln,
                    'bft':filename}
         else:
             status = '<span style="color: rgb(0, 255, 0);">OK</span>'
         attrs['status'] = status
         formats_attrs.append(attrs)
 
     def sort_by_attr(seq):
         """
         Sort 'seq' by attribute name.
         @param seq a list of dictionaries, containing each one key named 'name'
         """
         intermed = [ (x['name'].lower(), i, x) for i, x in enumerate(seq)]
         intermed.sort()
         return [x[-1] for x in intermed]
 
     sorted_format_templates = sort_by_attr(formats_attrs)
 
     return bibformat_templates.tmpl_admin_format_templates_management(ln, sorted_format_templates)
 
 def perform_request_format_template_show(bft, ln=CFG_SITE_LANG, code=None,
                                          ln_for_preview=CFG_SITE_LANG, pattern_for_preview="",
                                          content_type_for_preview="text/html"):
     """
     Returns the editor for format templates.
 
     @param ln language
     @param bft the template to edit
     @param code, the code being edited
     @param ln_for_preview the language for the preview (for bfo)
     @param pattern_for_preview the search pattern to be used for the preview (for bfo)
     @return the main page for formats management
     """
     format_template = bibformat_engine.get_format_template(filename=bft, with_attributes=True)
 
     # Either use code being edited, or the original code inside template
     if code is None:
         code = cgi.escape(format_template['code'])
 
     # Build a default pattern if it is empty
     if pattern_for_preview == "":
         recIDs = perform_request_search()
         if len(recIDs) > 0:
             recID = recIDs[0]
             pattern_for_preview = "recid:%s" % recID
 
     editable = can_write_format_template(bft)
 
     # Look for all existing content_types
     content_types = bibformat_dblayer.get_existing_content_types()
 
     # Add some standard content types if not already there
     standard_content_types = ['text/xml', 'application/rss+xml', 'text/plain', 'text/html']
     content_types.extend([content_type for content_type in standard_content_types
                           if content_type not in content_types])
 
     return bibformat_templates.tmpl_admin_format_template_show(ln, format_template['attrs']['name'],
                                                                format_template['attrs']['description'],
                                                                code, bft,
                                                                ln_for_preview=ln_for_preview,
                                                                pattern_for_preview=pattern_for_preview,
                                                                editable=editable,
                                                                content_type_for_preview=content_type_for_preview,
                                                                content_types=content_types)
 
 def perform_request_format_template_show_dependencies(bft, ln=CFG_SITE_LANG):
     """
     Show the dependencies (on elements) of the given format.
 
     @param ln language
     @param bft the filename of the template to show
     """
     format_template = bibformat_engine.get_format_template(filename=bft, with_attributes=True)
     name = format_template['attrs']['name']
     output_formats = get_outputs_that_use_template(bft)
     format_elements = get_elements_used_by_template(bft)
     tags = []
     for output_format in output_formats:
         for tag in output_format['tags']:
             tags.append(tag)
     for format_element in format_elements:
         for tag in format_element['tags']:
             tags.append(tag)
 
     tags.sort()
     return bibformat_templates.tmpl_admin_format_template_show_dependencies(ln,
                                                                             name,
                                                                             bft,
                                                                             output_formats,
                                                                             format_elements,
                                                                             tags)
 
 def perform_request_format_template_show_attributes(bft, ln=CFG_SITE_LANG, new=False):
     """
     Page for template name and descrition attributes edition.
 
     If format template is new, offer the possibility to
     make a duplicate of an existing format template.
 
     @param ln language
     @param bft the template to edit
     @param new if True, the template has just been added (is new)
     @return the main page for format templates attributes edition
     """
     all_templates = []
     if new:
         all_templates_attrs = bibformat_engine.get_format_templates(with_attributes=True)
         if all_templates_attrs.has_key(bft): # Sanity check. Should always be true at this stage
             del all_templates_attrs[bft] # Remove in order not to make a duplicate of self..
 
     # Sort according to name, inspired from Python Cookbook
 
         def sort_by_name(seq, keys):
             """
             Sort the sequence 'seq' by 'keys'
             """
             intermed = [(x['attrs']['name'], keys[i], i, x) for i, x in enumerate(seq)]
             intermed.sort()
             return [(x[1], x[0]) for x in intermed]
 
         all_templates = sort_by_name(all_templates_attrs.values(), all_templates_attrs.keys())
 	#keys = all_templates_attrs.keys()
 	#keys.sort()
 	#all_templates = map(lambda x: (x, all_templates_attrs.get(x)['attrs']['name']), keys)
 
     format_template = bibformat_engine.get_format_template(filename=bft, with_attributes=True)
     name = format_template['attrs']['name']
     description = format_template['attrs']['description']
     editable = can_write_format_template(bft)
 
     return bibformat_templates.tmpl_admin_format_template_show_attributes(ln,
                                                                           name,
                                                                           description,
                                                                           bft,
                                                                           editable,
 									  all_templates,
 									  new)
 
 
 def perform_request_format_template_show_short_doc(ln=CFG_SITE_LANG, search_doc_pattern=""):
     """
     Returns the format elements documentation to be included inside format templated editor.
 
     Keep only elements that have 'search_doc_pattern' text inside description,
     if pattern not empty
 
     @param ln language
     @param search_doc_pattern a search pattern that specified which elements to display
     @return a brief version of the format element documentation
     """
     # Get format elements lists of attributes
     elements = bibformat_engine.get_format_elements(with_built_in_params=True)
 
     keys =  elements.keys()
     keys.sort()
     elements = map(elements.get, keys)
 
     def filter_elem(element):
         """Keep element if is string representation contains all keywords of search_doc_pattern,
         and if its name does not start with a number (to remove 'garbage' from elements in tags table)"""
         if element['type'] != 'python' and \
                element['attrs']['name'][0] in ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']:
             return False
         text = str(element).upper() # Basic text representation
         if search_doc_pattern != "":
             for word in search_doc_pattern.split():
                 if word.upper() != "AND" and text.find(word.upper()) == -1:
                     return False
 
         return True
 
     elements = filter(filter_elem, elements)
 
 
 
     return bibformat_templates.tmpl_admin_format_template_show_short_doc(ln, elements)
 
 def perform_request_format_elements_documentation(ln=CFG_SITE_LANG):
     """
     Returns the main management console for format elements.
 
     Includes list of format elements and associated administration tools.
     @param ln language
     @return the main page for format elements management
     """
     # Get format elements lists of attributes
     elements = bibformat_engine.get_format_elements(with_built_in_params=True)
 
     keys =  elements.keys()
     keys.sort()
     elements = map(elements.get, keys)
     # Remove all elements found in table and that begin with a number (to remove 'garbage')
     filtered_elements = [element for element in elements \
                          if element is not None and \
                          element['type'] == 'python' and \
                          element['attrs']['name'][0] not in \
                          ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']]
 
     return bibformat_templates.tmpl_admin_format_elements_documentation(ln, filtered_elements)
 
 def perform_request_format_element_show_dependencies(bfe, ln=CFG_SITE_LANG):
     """
     Show the dependencies of the given format.
 
     @param ln language
     @param bfe the filename of the format element to show
     """
     format_templates = get_templates_that_use_element(bfe)
     tags = get_tags_used_by_element(bfe)
 
     return bibformat_templates.tmpl_admin_format_element_show_dependencies(ln,
                                                                            bfe,
                                                                            format_templates,
                                                                            tags)
 
 def perform_request_format_element_test(bfe, ln=CFG_SITE_LANG, param_values=None, user_info=None):
     """
     Show the dependencies of the given format.
 
     'param_values' is the list of values to pass to 'format'
     function of the element as parameters, in the order ...
     If params is None, this means that they have not be defined by user yet.
 
     @param ln language
     @param bfe the name of the format element to show
     @param params the list of parameters to pass to element format function
     @param user_info the user_info of this request
     """
     _ = gettext_set_language(ln)
     format_element = bibformat_engine.get_format_element(bfe, with_built_in_params=True)
 
     # Load parameter names and description
     ##
     param_names = []
     param_descriptions = []
 
     # First value is a search pattern to choose the record
     param_names.append(_("Test with record:")) # Caution: keep in sync with same text below
     param_descriptions.append(_("Enter a search query here."))
 
     # Parameters defined in this element
     for param in format_element['attrs']['params']:
         param_names.append(param['name'])
         param_descriptions.append(param['description'])
 
     # Parameters common to all elements of a kind
     for param in format_element['attrs']['builtin_params']:
         param_names.append(param['name'])
         param_descriptions.append(param['description'])
 
     # Load parameters values
     ##
 
     if param_values is None: #First time the page is loaded
         param_values = []
 
         # Propose an existing record id by default
         recIDs = perform_request_search()
         if len(recIDs) > 0:
             recID = recIDs[0]
             param_values.append("recid:%s" % recID)
 
         # Default values defined in this element
         for param in format_element['attrs']['params']:
             param_values.append(param['default'])
 
         #Parameters common to all elements of a kind
         for param in format_element['attrs']['builtin_params']:
             param_values.append(param['default'])
 
 
     # Execute element with parameters
     ##
     params = dict(zip(param_names, param_values))
 
     # Find a record corresponding to search pattern
     search_pattern = params[_("Test with record:")] # Caution keep in sync with same text above and below
     recIDs = perform_request_search(p=search_pattern)
     del params[_("Test with record:")] # Caution keep in sync with same text above
 
     if len(recIDs) > 0:
         bfo = bibformat_engine.BibFormatObject(recID = recIDs[0],
                                                ln = ln,
                                                search_pattern = search_pattern.split(' '),
                                                xml_record = None,
                                                user_info = user_info)
         (result, errors) = bibformat_engine.eval_format_element(format_element, bfo, params)
     else:
         result = get_msgs_for_code_list([("ERR_BIBFORMAT_NO_RECORD_FOUND_FOR_PATTERN", search_pattern)],
                                         stream='error', ln=CFG_SITE_LANG)[0][1]
 
     return bibformat_templates.tmpl_admin_format_element_test(ln,
                                                               bfe,
                                                               format_element['attrs']['description'],
                                                               param_names,
                                                               param_values,
                                                               param_descriptions,
                                                               result)
 
 def perform_request_output_formats_management(ln=CFG_SITE_LANG, sortby="code"):
     """
     Returns the main management console for output formats.
 
     Includes list of output formats and associated administration tools.
     @param ln language
     @param sortby the sorting crieteria (can be 'code' or 'name')
     @return the main page for output formats management
     """
     # Reload in case a format was changed
     bibformat_engine.clear_caches()
 
     # Get output formats lists of attributes
     output_formats_list = bibformat_engine.get_output_formats(with_attributes=True)
     output_formats = {}
     for filename in output_formats_list:
         output_format = output_formats_list[filename]
         code = output_format['attrs']['code']
         path = CFG_BIBFORMAT_OUTPUTS_PATH + os.sep + filename
         output_format['editable'] = can_write_output_format(code)
         try:
             output_format['last_mod_date'] = time.ctime(os.stat(path)[stat.ST_MTIME])
         except OSError:
             # File does not exist. Happens with temporary files
             # created by editors.
             continue
         # Validate the output format
         status = check_output_format(code)
         # If there is an error but the error is just 'format is not writable', do not display as error
         if len(status) > 1 or (len(status)==1 and status[0][0] != 'ERR_BIBFORMAT_CANNOT_WRITE_OUTPUT_FILE'):
             status = '''
             <a style="color: rgb(255, 0, 0);"
             href="%(siteurl)s/admin/bibformat/bibformatadmin.py/validate_format?ln=%(ln)s&bfo=%(bfo)s">Not OK</a>
             ''' % {'siteurl':CFG_SITE_URL,
                    'ln':ln,
                    'bfo':code}
         else:
             status = '<span style="color: rgb(0, 255, 0);">OK</span>'
         output_format['status'] = status
         output_formats[filename] = output_format
 
     # Sort according to code or name, inspired from Python Cookbook
     def get_attr(dic, attr):
         """
         Returns the value given by 'attr' in the dictionary 'dic', representing
         an output format attributes.
         If attr is equal to 'code', returns the code attribute of the dictionary.
         Else returns the generic name
 
         @param dic a dictionary of the attribute of an output format, as returned by bibformat_engine.get_output_format
         @param the attribute we want to fetch. Either 'code' or any other string
         """
         if attr == "code":
             return dic['attrs']['code']
         else:
             return dic['attrs']['names']['generic']
 
     def sort_by_attr(seq, attr):
         """
         Sort dictionaries given in 'seq' according to parameter 'attr'
         """
         intermed = [ (get_attr(x, attr), i, x) for i, x in enumerate(seq)]
         intermed.sort()
         return [x[-1] for x in intermed]
 
     if sortby != "code" and sortby != "name":
         sortby = "code"
 
     sorted_output_formats = sort_by_attr(output_formats.values(), sortby)
 
     return bibformat_templates.tmpl_admin_output_formats_management(ln, sorted_output_formats)
 
 def perform_request_output_format_show(bfo, ln=CFG_SITE_LANG, r_fld=[], r_val=[], r_tpl=[], default="", r_upd="", args={}):
     """
     Returns the editing tools for a given output format.
 
     The page either shows the output format from file, or from user's
     POST session, as we want to let him edit the rules without
     saving. Policy is: r_fld, r_val, rules_tpl are list of attributes
     of the rules.  If they are empty, load from file. Else use
     POST. The i th value of each list is one of the attributes of rule
     i. Rule i is the i th rule in order of evaluation.  All list have
     the same number of item.
 
     r_upd contains an action that has to be performed on rules. It
     can composed of a number (i, the rule we want to modify) and an
     operator : "save" to save the rules, "add" or "del".
     syntax: operator [number]
     For eg: r_upd = _("Save Changes") saves all rules (no int should be specified).
     For eg: r_upd = _("Add New Rule") adds a rule (no int should be specified).
     For eg: r_upd = _("Remove Rule") + " 5"  deletes rule at position 5.
     The number is used only for operation delete.
 
     An action can also be in **args. We must look there for string starting
     with '(+|-) [number]' to increase (+) or decrease (-) a rule given by its
     index (number).
     For example "+ 5" increase priority of rule 5 (put it at fourth position).
     The string in **args can be followed by some garbage that looks like .x
     or .y, as this is returned as the coordinate of the click on the
     <input type="image">. We HAVE to use args and reason on its keys, because for <input> of
     type image, iexplorer does not return the value of the tag, but only the name.
 
     Action is executed only if we are working from user's POST session
     (means we must have loaded the output format first, which is
     totally normal and expected behaviour)
 
     IMPORTANT: we display rules evaluation index starting at 1 in
     interface, but we start internally at 0
 
     @param ln language
     @param bfo the filename of the output format to show
     @param r_fld the list of 'field' attribute for each rule
     @param r_val the list of 'value' attribute for each rule
     @param r_tpl the list of 'template' attribute for each rule
     @param default the default format template used by this output format
     @param r_upd the rule that we want to increase/decrease in order of evaluation
     """
 
     output_format = bibformat_engine.get_output_format(bfo, with_attributes=True)
     format_templates =  bibformat_engine.get_format_templates(with_attributes=True)
     name = output_format['attrs']['names']['generic']
     rules = []
     debug = ""
     if len(r_fld) == 0 and r_upd=="":
         # Retrieve rules from file
         rules = output_format['rules']
         default = output_format['default']
     else:
         # Retrieve rules from given lists
 
         # Transform a single rule (not considered as a list with length
         # 1 by the templating system) into a list
         if not isinstance(r_fld, list):
             r_fld = [r_fld]
             r_val = [r_val]
             r_tpl = [r_tpl]
 
         for i in range(len(r_fld)):
             rule = {'field': r_fld[i],
                     'value': r_val[i],
                     'template': r_tpl[i]}
             rules.append(rule)
         # Execute action
         _ = gettext_set_language(ln)
         if r_upd.startswith(_("Remove Rule")):
             # Remove rule
             index = int(r_upd.split(" ")[-1]) -1
             del rules[index]
         elif r_upd.startswith(_("Save Changes")):
             # Save
             update_output_format_rules(bfo, rules, default)
         elif r_upd.startswith(_("Add New Rule")):
             # Add new rule
             rule = {'field': "",
                     'value': "",
                     'template': ""}
             rules.append(rule)
         else:
             # Get the action in 'args'
             # The action must be constructed from string of the kind:
             # + 5  or  - 4  or + 5.x  or -4.y
             for button_val in args.keys():#for all elements of form not handled yet
                 action = button_val.split(" ")
                 if action[0] == '-' or action[0] == '+':
                     index = int(action[1].split(".")[0]) -1
                     if action[0] == '-':
                         # Decrease priority
                         rule = rules[index]
                         del rules[index]
                         rules.insert(index + 1, rule)
                         # debug = 'Decrease rule '+ str(index)
                         break
                     elif action[0] == '+':
                         # Increase priority
                         rule = rules[index]
                         del rules[index]
                         rules.insert(index - 1, rule)
                         # debug = 'Increase rule ' + str(index)
                         break
 
 
     editable = can_write_output_format(bfo)
 
     return bibformat_templates.tmpl_admin_output_format_show(ln,
                                                             bfo,
                                                             name,
                                                             rules,
                                                             default,
                                                             format_templates,
                                                             editable)
 
 def perform_request_output_format_show_dependencies(bfo, ln=CFG_SITE_LANG):
     """
     Show the dependencies of the given format.
 
     @param ln language
     @param bfo the filename of the output format to show
     """
     output_format = bibformat_engine.get_output_format(code=bfo, with_attributes=True)
     name = output_format['attrs']['names']['generic']
     format_templates = get_templates_used_by_output(bfo)
 
     return bibformat_templates.tmpl_admin_output_format_show_dependencies(ln,
                                                                           name,
                                                                           bfo,
                                                                           format_templates)
 
 def perform_request_output_format_show_attributes(bfo, ln=CFG_SITE_LANG):
     """
     Page for output format names and description attributes edition.
 
     @param ln language
     @param bfo filename of output format to edit
     @return the main page for output format attributes edition
     """
     output_format = bibformat_engine.get_output_format(code=bfo, with_attributes=True)
 
     name = output_format['attrs']['names']['generic']
     description = output_format['attrs']['description']
     content_type = output_format['attrs']['content_type']
     visible = output_format['attrs']['visibility']
     # Get translated names. Limit to long names now.
     # Translation are given in order of languages in language_list_long()
     names_trans = []
     for lang in language_list_long():
         name_trans = output_format['attrs']['names']['ln'].get(lang[0], "")
         names_trans.append({'lang':lang[1], 'trans':name_trans})
 
     editable = can_write_output_format(bfo)
 
     return bibformat_templates.tmpl_admin_output_format_show_attributes(ln,
                                                                         name,
                                                                         description,
                                                                         content_type,
                                                                         bfo,
                                                                         names_trans,
                                                                         editable,
                                                                         visible)
 
 
-def perform_request_knowledge_bases_management(ln=CFG_SITE_LANG):
+def perform_request_knowledge_bases_management(ln=CFG_SITE_LANG, search=""):
     """
     Returns the main page for knowledge bases management.
 
     @param ln language
+    @param search search for this string in kb's
     @return the main page for knowledge bases management
     """
     kbs = bibformat_dblayer.get_kbs()
 
-    return bibformat_templates.tmpl_admin_kbs_management(ln, kbs)
-
-def perform_request_knowledge_base_show(kb_id, ln=CFG_SITE_LANG, sortby="to", startat=0):
+    #if search is nonempty, filter out kb's that do not have the
+    #the string that we search
+    newkbs = []
+    if search:
+        for kb in kbs:
+            kbname = kb['name']
+            #get mappings
+            mappings = bibformat_dblayer.get_kb_mappings(kbname)
+            skip = 0
+            for mapping in mappings:
+                if skip == 0:
+                    key =  mapping['key']
+                    value = mapping['value']
+                    if key.count(search)> 0 or value.count(search)> 0:
+                        #add this in newkbs
+                        newkbs.append(kb)
+                        #skip the rest, we know there's ok stuff in this kb
+                        skip = 1
+        kbs = newkbs
+
+    return bibformat_templates.tmpl_admin_kbs_management(ln, kbs, search)
+
+def perform_request_knowledge_base_show(kb_id, ln=CFG_SITE_LANG, sortby="to", startat=0, search=""):
     """
     Show the content of a knowledge base
 
     @param ln language
     @param kb a knowledge base id
     @param sortby the sorting criteria ('from' or 'to')
     @param startat start showing mapping rules at what number
+    @param search search for this string in kb
     @return the content of the given knowledge base
     """
     name = bibformat_dblayer.get_kb_name(kb_id)
     mappings = bibformat_dblayer.get_kb_mappings(name, sortby)
     kb_type = bibformat_dblayer.get_kb_type(kb_id)
-    return bibformat_templates.tmpl_admin_kb_show(ln, kb_id, name, mappings, sortby, startat, kb_type)
+    #filter in only the requested rules if the user is searching..
+    if search:
+        newmappings = []
+        for mapping in mappings:
+            key =  mapping['key']
+            value = mapping['value']
+            if key.count(search)> 0 or value.count(search)> 0:
+                newmappings.append(mapping)
+        #we were searching, so replace
+        mappings = newmappings
+
+    return bibformat_templates.tmpl_admin_kb_show(ln, kb_id, name, mappings, sortby, startat, kb_type, search)
 
 
 def perform_request_knowledge_base_show_attributes(kb_id, ln=CFG_SITE_LANG, sortby="to"):
     """
     Show the attributes of a knowledge base
 
     @param ln language
     @param kb a knowledge base id
     @param sortby the sorting criteria ('from' or 'to')
     @return the content of the given knowledge base
     """
     name = bibformat_dblayer.get_kb_name(kb_id)
     description = bibformat_dblayer.get_kb_description(name)
     kb_type =  bibformat_dblayer.get_kb_type(name)
     return bibformat_templates.tmpl_admin_kb_show_attributes(ln, kb_id, name, description, sortby, kb_type)
 
 
 def perform_request_knowledge_base_show_dependencies(kb_id, ln=CFG_SITE_LANG, sortby="to"):
     """
     Show the dependencies of a kb
 
     @param ln language
     @param kb a knowledge base id
     @param sortby the sorting criteria ('from' or 'to')
     @return the dependencies of the given knowledge base
     """
     name = bibformat_dblayer.get_kb_name(kb_id)
     format_elements = get_elements_that_use_kb(name)
 
     return bibformat_templates.tmpl_admin_kb_show_dependencies(ln, kb_id, name, sortby, format_elements)
 
 def add_format_template():
     """
     Adds a new format template (mainly create file with unique name)
 
     @return the filename of the created format
     """
     (filename, name) = bibformat_engine.get_fresh_format_template_filename("Untitled")
 
     out = ""
     if not filename.endswith(".xsl"):
         out = '<name>%(name)s</name><description></description>' % {'name': name}
     path = CFG_BIBFORMAT_TEMPLATES_PATH + os.sep + filename
     format = open(path, 'w')
     format.write(out)
     format.close
 
     return filename
 
 def delete_format_template(filename):
     """
     Delete a format template given by its filename
 
     If format template is not writable, do not remove
 
     @param filename the format template filename
     """
     if not can_write_format_template(filename):
         return
 
     path = CFG_BIBFORMAT_TEMPLATES_PATH + os.sep + filename
     os.remove(path)
     bibformat_engine.clear_caches()
 
 def update_format_template_code(filename, code=""):
     """
     Saves code inside template given by filename
     """
     format_template = bibformat_engine.get_format_template_attrs(filename)
     name = format_template['name']
     description = format_template['description']
     code = re.sub("\r\n", "\n", code)
     out = ""
     if not filename.endswith(".xsl"):
         out = """<name>%(name)s</name>
 <description>%(description)s</description>
 """ % {'name': name, 'description': description}
     out += code
     path = CFG_BIBFORMAT_TEMPLATES_PATH + os.sep + filename
     format = open(path, 'w')
     format.write(out)
     format.close
 
     bibformat_engine.clear_caches()
 
 def update_format_template_attributes(filename, name="", description="", duplicate=None):
     """
     Saves name and description inside template given by filename.
 
     the filename must change according to name, and every output format
     having reference to filename must be updated.
 
     If name already exist, use fresh filename (we never overwrite other templates) amd
     remove old one.
 
     if duplicate is different from None and is not empty string, then it means that we must copy
     the code of the template whoose filename is given in 'duplicate' for the code
     of our template.
 
     @param duplicate the filename of a template that we want to copy
     @return the filename of the modified format
     """
     if filename.endswith('.'+CFG_BIBFORMAT_FORMAT_TEMPLATE_EXTENSION):
         format_template = bibformat_engine.get_format_template(filename, with_attributes=True)
         if duplicate is not None and duplicate != "":
             format_template_to_copy = bibformat_engine.get_format_template(duplicate)
             code = format_template_to_copy['code']
         else:
             code = format_template['code']
         if format_template['attrs']['name'] != name:
             # Name has changed, so update filename
             old_filename = filename
             old_path = CFG_BIBFORMAT_TEMPLATES_PATH + os.sep + old_filename
             # Remove old one
             os.remove(old_path)
 
             (filename, name) = bibformat_engine.get_fresh_format_template_filename(name)
 
             # Change output formats that calls this template
             output_formats = bibformat_engine.get_output_formats()
 
             for output_format_filename in output_formats:
                 if can_read_output_format(output_format_filename) and can_write_output_format(output_format_filename):
                     output_path = CFG_BIBFORMAT_OUTPUTS_PATH + os.sep + output_format_filename
                     format = open(output_path, 'r')
                     output_text = format.read()
                     format.close
                     output_pattern = re.compile("---(\s)*" + old_filename, re.IGNORECASE)
                     mod_output_text = output_pattern.sub("--- " + filename, output_text)
                     if output_text != mod_output_text:
                         format = open(output_path, 'w')
                         format.write(mod_output_text)
                         format.close
 
         description = cgi.escape(description)
         name = cgi.escape(name)
         # Write updated format template
         out = ""
         if not filename.endswith(".xsl"):
             out = """<name>%(name)s</name><description>%(description)s</description>""" % {'name': name,
                                                                                            'description': description,}
         out += code
 
         path = CFG_BIBFORMAT_TEMPLATES_PATH + os.sep + filename
         format = open(path, 'w')
         format.write(out)
         format.close
 
         bibformat_engine.clear_caches()
 
     return filename
 
 def add_output_format():
     """
     Adds a new output format (mainly create file with unique name)
 
     @return the code of the created format, or None if it could not be created
     """
 
     if not os.access(CFG_BIBFORMAT_OUTPUTS_PATH, os.W_OK):
         return None
 
     (filename, code) = bibformat_engine.get_fresh_output_format_filename("UNTLD")
 
     # Add entry in database
     bibformat_dblayer.add_output_format(code)
     bibformat_dblayer.set_output_format_name(code, "Untitled", lang="generic")
     bibformat_dblayer.set_output_format_content_type(code, "text/html")
 
     # Add file
     out = ""
     path = CFG_BIBFORMAT_OUTPUTS_PATH + os.sep + filename
     format = open(path, 'w')
     format.write(out)
     format.close
 
     return code
 
 def delete_output_format(code):
     """
     Delete a format template given by its code
 
     if file is not writable, don't remove
 
     @param code the 6 letters code of the output format to remove
     """
     if not can_write_output_format(code):
         return
 
     # Remove entry from database
     bibformat_dblayer.remove_output_format(code)
 
     # Remove file
     filename = bibformat_engine.resolve_output_format_filename(code)
     path = CFG_BIBFORMAT_OUTPUTS_PATH + os.sep + filename
     os.remove(path)
 
     bibformat_engine.clear_caches()
 
 
 def update_output_format_rules(code, rules=[], default=""):
     """
     Saves rules inside output format given by code
     """
 
     # Generate output format syntax
     # Try to group rules by field
     previous_field = ""
     out = ""
     for rule in rules:
         field = rule["field"]
         value = rule["value"]
         template = rule["template"]
         if previous_field != field:
             out += "tag %s:\n" % field
 
         out +="%(value)s --- %(template)s\n" % {'value':value, 'template':template}
         previous_field = field
 
     out += "default: %s" % default
     filename = bibformat_engine.resolve_output_format_filename(code)
     path = CFG_BIBFORMAT_OUTPUTS_PATH + os.sep + filename
     format = open(path, 'w')
     format.write(out)
     format.close
 
     bibformat_engine.clear_caches()
 
 def update_output_format_attributes(code, name="", description="", new_code="",
                                     content_type="", names_trans=[], visibility=1):
     """
     Saves name and description inside output format given by filename.
 
     If new_code already exist, use fresh code (we never overwrite other output).
 
     @param description the new description
     @param name the new name
     @param code the new short code (== new bfo) of the output format
     @param code the code of the output format to update
     @param names_trans the translations in the same order as the languages from get_languages()
     @param content_type the new content_type of the output format
     @param visibility the visibility of the output format in the output formats list (public pages)
     @return the filename of the modified format
     """
 
     bibformat_dblayer.set_output_format_description(code, description)
     bibformat_dblayer.set_output_format_content_type(code, content_type)
     bibformat_dblayer.set_output_format_visibility(code, visibility)
     bibformat_dblayer.set_output_format_name(code, name, lang="generic")
     i = 0
     for lang in language_list_long():
         if names_trans[i] != "":
             bibformat_dblayer.set_output_format_name(code, names_trans[i], lang[0])
         i += 1
 
     new_code = new_code.upper()
     if code != new_code:
         # If code has changed, we must update filename with a new unique code
         old_filename = bibformat_engine.resolve_output_format_filename(code)
         old_path = CFG_BIBFORMAT_OUTPUTS_PATH + os.sep + old_filename
         (new_filename, new_code) = bibformat_engine.get_fresh_output_format_filename(new_code)
         new_path = CFG_BIBFORMAT_OUTPUTS_PATH + os.sep + new_filename
         os.rename(old_path, new_path)
         bibformat_dblayer.change_output_format_code(code, new_code)
 
     bibformat_engine.clear_caches()
 
     return new_code
 
 def add_kb_mapping(kb_name, key, value=""):
     """
     Adds a new mapping to given kb
 
     @param kb_name the name of the kb where to insert the new value
     @param key the key of the mapping
     @param value the value of the mapping
     """
     bibformat_dblayer.add_kb_mapping(kb_name, key, value)
 
 def remove_kb_mapping(kb_name, key):
     """
     Delete an existing kb mapping in kb
 
     @param kb_name the name of the kb where to insert the new value
     @param key the key of the mapping
     """
     bibformat_dblayer.remove_kb_mapping(kb_name, key)
 
 def update_kb_mapping(kb_name, old_key, key, value):
     """
     Update an existing kb mapping with key old_key with a new key and value
 
     @param kb_name the name of the kb where to insert the new value
     @param the key of the mapping in the kb
     @param key the new key of the mapping
     @param value the new value of the mapping
     """
     bibformat_dblayer.update_kb_mapping(kb_name, old_key, key, value)
 
 def kb_exists(kb_name):
     """Returns True if a kb with the given name exists"""
     return bibformat_dblayer.kb_exists(kb_name)
 
 def get_kb_name(kb_id):
     """
     Returns the name of the kb given by id
     """
     return bibformat_dblayer.get_kb_name(kb_id)
 
 def update_kb_attributes(kb_name, new_name, new_description):
     """
     Updates given kb_name with a new name and new description
 
     @param kb_name the name of the kb to update
     @param new_name the new name for the kb
     @param new_description the new description for the kb
     """
     bibformat_dblayer.update_kb(kb_name, new_name, new_description)
 
 def add_kb(kb_name="Untitled", kb_type=None):
     """
     Adds a new kb in database, and returns its id
     The name of the kb will be 'Untitled#'
     such that it is unique.
 
     @param kb_name the name of the kb
     @param kb_type the type of the kb, incl 'taxonomy'. None for typical.
     @return the id of the newly created kb
     """
     name = kb_name
     i = 1
     while bibformat_dblayer.kb_exists(name):
         name = kb_name + " " + str(i)
         i += 1
 
     kb_id = bibformat_dblayer.add_kb(name, "", kb_type)
 
     return kb_id
 
 def delete_kb(kb_name):
     """
     Deletes given kb from database
     """
     bibformat_dblayer.delete_kb(kb_name)
 
 def can_read_format_template(filename):
     """
     Returns 0 if we have read permission on given format template, else
     returns other integer
     """
     path = "%s%s%s" % (CFG_BIBFORMAT_TEMPLATES_PATH, os.sep, filename)
     return os.access(path, os.R_OK)
 
 def can_read_output_format(bfo):
     """
     Returns 0 if we have read permission on given output format, else
     returns other integer
     """
     filename = bibformat_engine.resolve_output_format_filename(bfo)
     path = "%s%s%s" % (CFG_BIBFORMAT_OUTPUTS_PATH, os.sep, filename)
     return os.access(path, os.R_OK)
 
 def can_read_format_element(name):
     """
     Returns 0 if we have read permission on given format element, else
     returns other integer
     """
 
     filename = bibformat_engine.resolve_format_element_filename(name)
     path = "%s%s%s" % (CFG_BIBFORMAT_ELEMENTS_PATH, os.sep, filename)
     return os.access(path, os.R_OK)
 
 def can_write_format_template(bft):
     """
     Returns 0 if we have write permission on given format template, else
     returns other integer
     """
     if not can_read_format_template(bft):
         return False
 
     path = "%s%s%s" % (CFG_BIBFORMAT_TEMPLATES_PATH, os.sep, bft)
     return os.access(path, os.W_OK)
 
 def can_write_output_format(bfo):
     """
     Returns 0 if we have write permission on given output format, else
     returns other integer
     """
     if not can_read_output_format(bfo):
         return False
 
     filename = bibformat_engine.resolve_output_format_filename(bfo)
     path = "%s%s%s" % (CFG_BIBFORMAT_OUTPUTS_PATH, os.sep, filename)
     return os.access(path, os.W_OK)
 
 def can_write_etc_bibformat_dir():
     """
     Returns true if we can write in etc/bibformat dir.
     """
     path = "%s%sbibformat" % (CFG_ETCDIR, os.sep)
     return os.access(path, os.W_OK)
 
 def get_outputs_that_use_template(filename):
     """
     Returns a list of output formats that call the given format template.
     The returned output formats also give their dependencies on tags.
 
     We don't return the complete output formats but some reference to
     them (filename + names)
 
     [ {'filename':"filename_1.bfo"
        'names': {'en':"a name", 'fr': "un nom", 'generic':"a name"}
        'tags': ['710__a', '920__']
       },
       ...
     ]
 
     Returns output formats references sorted by (generic) name
 
     @param filename a format template filename
     """
     output_formats_list = {}
     tags = []
     output_formats = bibformat_engine.get_output_formats(with_attributes=True)
     for output_format in output_formats:
         name = output_formats[output_format]['attrs']['names']['generic']
         # First look at default template, and add it if necessary
         if output_formats[output_format]['default'] == filename:
             output_formats_list[name] = {'filename':output_format,
                                          'names':output_formats[output_format]['attrs']['names'],
                                          'tags':[]}
         # Second look at each rule
         found = False
         for rule in output_formats[output_format]['rules']:
             if rule['template'] == filename:
                 found = True
                 tags.append(rule['field']) #Also build dependencies on tags
 
         # Finally add dependency on template from rule (overwrite default dependency,
         # which is weaker in term of tag)
         if found:
             output_formats_list[name] = {'filename':output_format,
                                          'names':output_formats[output_format]['attrs']['names'],
                                          'tags':tags}
 
 
 
     keys = output_formats_list.keys()
     keys.sort()
     return map(output_formats_list.get, keys)
 
 def get_elements_used_by_template(filename):
     """
     Returns a list of format elements that are called by the given format template.
     The returned elements also give their dependencies on tags.
 
     Dependencies on tag might be approximative. See get_tags_used_by_element()
     doc string.
 
     We must handle usage of bfe_field in a special way if we want to retrieve
     used tag: used tag is given in "tag" parameter, not inside element code.
 
     The list is returned sorted by name
 
     [ {'filename':"filename_1.py"
        'name':"filename_1"
        'tags': ['710__a', '920__']
       },
       ...
     ]
 
     Returns elements sorted by name
 
     @param filename a format template filename
     """
     format_elements = {}
     format_template = bibformat_engine.get_format_template(filename=filename, with_attributes=True)
     code = format_template['code']
     format_elements_iter = bibformat_engine.pattern_tag.finditer(code)
     for result in format_elements_iter:
         function_name = result.group("function_name").lower()
         if function_name is not None and not format_elements.has_key(function_name) \
                and not function_name == "field":
             filename = bibformat_engine.resolve_format_element_filename("BFE_"+function_name)
             if filename is not None:
                 tags = get_tags_used_by_element(filename)
                 format_elements[function_name] = {'name':function_name.lower(),
                                                   'filename':filename,
                                                   'tags':tags}
         elif function_name == "field":
             # Handle bfe_field element in a special way
             if not format_elements.has_key(function_name):
                 #Indicate usage of bfe_field if not already done
                 filename = bibformat_engine.resolve_format_element_filename("BFE_"+function_name)
                 format_elements[function_name] = {'name':function_name.lower(),
                                                   'filename':filename,
                                                   'tags':[]}
             # Retrieve value of parameter "tag"
             all_params = result.group('params')
             function_params_iterator = bibformat_engine.pattern_function_params.finditer(all_params)
             for param_match in function_params_iterator:
                 name = param_match.group('param')
                 if name == "tag":
                     value = param_match.group('value')
                     if not value in format_elements[function_name]['tags']:
                         format_elements[function_name]['tags'].append(value)
                     break
 
     keys = format_elements.keys()
     keys.sort()
     return map(format_elements.get, keys)
 
 
 # Format Elements Dependencies
 ##
 
 def get_tags_used_by_element(filename):
     """
     Returns a list of tags used by given format element
 
     APPROXIMATIVE RESULTS: the tag are retrieved in field(), fields()
     and control_field() function. If they are used computed, or saved
     in a variable somewhere else, they are not retrieved
     @TODO: There is room for improvements. For example catch
     call to BibRecord functions.
 
     Returns tags sorted by value
 
     @param filename a format element filename
     """
     tags = {}
 
     format_element = bibformat_engine.get_format_element(filename)
     if format_element is None:
         return []
     elif format_element['type']=="field":
         tags = format_element['attrs']['tags']
         return tags
 
     filename = bibformat_engine.resolve_format_element_filename(filename)
     path = CFG_BIBFORMAT_ELEMENTS_PATH + os.sep + filename
     format = open(path, 'r')
     code = format.read()
     format.close
     tags_pattern = re.compile('''
     (field|fields|control_field)\s*       #Function call
     \(\s*                                 #Opening parenthesis
     [\'"]+                                #Single or double quote
     (?P<tag>.+?)                          #Tag
     [\'"]+\s*                             #Single or double quote
     (,[^\)]+)*                            #Additional function param
     \)                                    #Closing parenthesis
      ''', re.VERBOSE | re.MULTILINE)
 
     tags_iter = tags_pattern.finditer(code)
     for result in tags_iter:
         tags[result.group("tag")] = result.group("tag")
 
     return tags.values()
 
 def get_templates_that_use_element(name):
     """
     Returns a list of format templates that call the given format element.
     The returned format templates also give their dependencies on tags.
 
     [ {'filename':"filename_1.bft"
        'name': "a name"
        'tags': ['710__a', '920__']
       },
       ...
     ]
 
     Returns templates sorted by name
 
     @param name a format element name
     """
     format_templates = {}
     tags = []
     files = os.listdir(CFG_BIBFORMAT_TEMPLATES_PATH) #Retrieve all templates
     for possible_template in files:
         if possible_template.endswith(CFG_BIBFORMAT_FORMAT_TEMPLATE_EXTENSION):
             format_elements = get_elements_used_by_template(possible_template) #Look for elements used in template
             format_elements = map(lambda x: x['name'].lower(), format_elements)
             try: #Look for element
                 format_elements.index(name.lower()) #If not found, get out of "try" statement
 
                 format_template = bibformat_engine.get_format_template(filename=possible_template, with_attributes=True)
                 template_name = format_template['attrs']['name']
                 format_templates[template_name] = {'name':template_name,
                                                    'filename':possible_template}
             except:
                 pass
 
     keys = format_templates.keys()
     keys.sort()
     return map(format_templates.get, keys)
 
 # Output Formats Dependencies
 ##
 
 def get_templates_used_by_output(code):
     """
     Returns a list of templates used inside an output format give by its code
     The returned format templates also give their dependencies on elements and tags
 
     [ {'filename':"filename_1.bft"
        'name': "a name"
        'elements': [{'filename':"filename_1.py", 'name':"filename_1", 'tags': ['710__a', '920__']
       }, ...]
       },
       ...
     ]
 
     Returns templates sorted by name
 
     """
     format_templates = {}
     output_format = bibformat_engine.get_output_format(code, with_attributes=True)
 
     filenames = map(lambda x: x['template'], output_format['rules'])
     if output_format['default'] != "":
         filenames.append(output_format['default'])
 
     for filename in filenames:
         template = bibformat_engine.get_format_template(filename, with_attributes=True)
         name = template['attrs']['name']
         elements = get_elements_used_by_template(filename)
         format_templates[name] = {'name':name,
                                   'filename':filename,
                                   'elements':elements}
 
 
     keys = format_templates.keys()
     keys.sort()
     return map(format_templates.get, keys)
 
 
 # Knowledge Bases Dependencies
 ##
 
 def get_elements_that_use_kb(name):
     """
     Returns a list of elements that call given kb
 
     [ {'filename':"filename_1.py"
        'name': "a name"
       },
       ...
     ]
 
     Returns elements sorted by name
     """
 
     format_elements = {}
     files = os.listdir(CFG_BIBFORMAT_ELEMENTS_PATH) #Retrieve all elements in files
     for filename in files:
         if filename.endswith(".py"):
             path = CFG_BIBFORMAT_ELEMENTS_PATH + os.sep + filename
             format = open(path, 'r')
             code = format.read()
             format.close
             # Search for use of kb inside code
             kb_pattern = re.compile('''
             (bfo.kb)\s*                #Function call
             \(\s*                      #Opening parenthesis
             [\'"]+                     #Single or double quote
             (?P<kb>%s)                 #kb
             [\'"]+\s*                  #Single or double quote
             ,                          #comma
             ''' % name, re.VERBOSE | re.MULTILINE | re.IGNORECASE)
 
             result = kb_pattern.search(code)
             if result is not None:
                 name = ("".join(filename.split(".")[:-1])).lower()
                 if name.startswith("bfe_"):
                     name = name[4:]
                 format_elements[name] = {'filename':filename, 'name': name}
 
 
     keys = format_elements.keys()
     keys.sort()
     return map(format_elements.get, keys)
 
 # Validation tools
 ##
 
 def perform_request_format_validate(ln=CFG_SITE_LANG, bfo=None, bft=None, bfe=None):
     """
     Returns a page showing the status of an output format or format
     template or format element. This page is called from output
     formats management page or format template management page or
     format elements documentation.
 
     The page only shows the status of one of the format, depending on
     the specified one. If multiple are specified, shows the first one.
 
     @param ln language
     @param bfo an output format 6 chars code
     @param bft a format element filename
     @param bfe a format element name
     """
 
     if bfo is not None:
         errors = check_output_format(bfo)
         messages = get_msgs_for_code_list(code_list = errors, ln=ln)
     elif bft is not None:
         errors = check_format_template(bft, checking=1)
         messages = get_msgs_for_code_list(code_list = errors, ln=ln)
     elif bfe is not None:
         errors = check_format_element(bfe)
         messages = get_msgs_for_code_list(code_list = errors, ln=ln)
 
     if messages is None:
         messages = []
 
     messages = map(lambda x: encode_for_xml(x[1]), messages)
 
     return bibformat_templates.tmpl_admin_validate_format(ln, messages)
 
 
 def check_output_format(code):
     """
     Returns the list of errors in the output format given by code
 
     The errors are the formatted errors defined in bibformat_config.py file.
 
     @param code the 6 chars code of the output format to check
     @return a list of errors
     """
     errors = []
     filename = bibformat_engine.resolve_output_format_filename(code)
     if can_read_output_format(code):
         path = CFG_BIBFORMAT_OUTPUTS_PATH + os.sep + filename
         format = open(path)
         current_tag = ''
         i = 0
         for line in format:
             i += 1
             if line.strip() == "":
                 # Ignore blank lines
                 continue
             clean_line = line.rstrip("\n\r ") #remove spaces and eol
             if line.strip().endswith(":") or (line.strip().lower().startswith("tag") and line.find('---') == -1):
                 # Check tag
                 if not clean_line.endswith(":"):
                     # Column misses at the end of line
                     errors.append(("ERR_BIBFORMAT_OUTPUT_RULE_FIELD_COL", line, i))
                 if not clean_line.lower().startswith("tag"):
                     # Tag keyword is missing
                     errors.append(("ERR_BIBFORMAT_OUTPUT_TAG_MISSING", line, i))
                 elif not clean_line.startswith("tag"):
                     # Tag was not lower case
                     errors.append(("ERR_BIBFORMAT_OUTPUT_WRONG_TAG_CASE", line, i))
 
                 clean_line = clean_line.rstrip(": ") #remove : and spaces at the end of line
 
                 current_tag = "".join(clean_line.split()[1:]).strip() #the tag starts at second position
                 if len(clean_line.split()) > 2: #We should only have 'tag' keyword and tag
                     errors.append(("ERR_BIBFORMAT_INVALID_OUTPUT_RULE_FIELD", i))
                 else:
                     if len(check_tag(current_tag)) > 0:
                         # Invalid tag
                         errors.append(("ERR_BIBFORMAT_INVALID_OUTPUT_RULE_FIELD_tag", current_tag, i))
                     if not clean_line.startswith("tag"):
                         errors.append(("ERR_BIBFORMAT_INVALID_OUTPUT_RULE_FIELD", i))
 
             elif line.find('---') != -1:
                 # Check condition
                 if current_tag == "":
                     errors.append(("ERR_BIBFORMAT_OUTPUT_CONDITION_OUTSIDE_FIELD", line, i))
 
                 words = line.split('---')
                 if len(words) != 2:
                     errors.append(("ERR_BIBFORMAT_INVALID_OUTPUT_CONDITION", line, i))
                 template = words[-1].strip()
                 path = CFG_BIBFORMAT_TEMPLATES_PATH + os.sep + template
                 if not os.path.exists(path):
                     errors.append(("ERR_BIBFORMAT_WRONG_OUTPUT_RULE_TEMPLATE_REF", template, i))
 
             elif line.find(':') != -1 or (line.strip().lower().startswith("default") and line.find('---') == -1):
                 # Check default template
                 clean_line = line.strip()
                 if line.find(':') == -1:
                     # Column misses after default
                     errors.append(("ERR_BIBFORMAT_OUTPUT_RULE_DEFAULT_COL", line, i))
                 if not clean_line.startswith("default"):
                     # Default keyword is missing
                     errors.append(("ERR_BIBFORMAT_OUTPUT_DEFAULT_MISSING", line, i))
                 if not clean_line.startswith("default"):
                     # Default was not lower case
                     errors.append(("ERR_BIBFORMAT_OUTPUT_WRONG_DEFAULT_CASE", line, i))
                 default = "".join(line.split(':')[1]).strip()
                 path = CFG_BIBFORMAT_TEMPLATES_PATH + os.sep + default
                 if not os.path.exists(path):
                     errors.append(("ERR_BIBFORMAT_WRONG_OUTPUT_RULE_TEMPLATE_REF", default, i))
 
             else:
                 # Check others
                 errors.append(("ERR_BIBFORMAT_WRONG_OUTPUT_LINE", line, i))
     else:
         errors.append(("ERR_BIBFORMAT_CANNOT_READ_OUTPUT_FILE", filename, ""))
 
     return errors
 
 def check_format_template(filename, checking=0):
     """
     Returns the list of errors in the format template given by its filename
 
     The errors are the formatted errors defined in bibformat_config.py file.
 
     @param filename the filename of the format template to check
     @param checking the level of checking (0:basic, >=1 extensive (time-consuming))
     @return a list of errors
     """
     errors = []
     if can_read_format_template(filename):#Can template be read?
         if filename.endswith('.'+CFG_BIBFORMAT_FORMAT_TEMPLATE_EXTENSION):
             #format_template = bibformat_engine.get_format_template(filename, with_attributes=True)
             format = open("%s%s%s" % (CFG_BIBFORMAT_TEMPLATES_PATH, os.sep, filename))
             code = format.read()
             format.close()
             # Look for name
             match = bibformat_engine.pattern_format_template_name.search(code)
             if match is None:#Is tag <name> defined in template?
                 errors.append(("ERR_BIBFORMAT_TEMPLATE_HAS_NO_NAME", filename))
 
             # Look for description
             match = bibformat_engine.pattern_format_template_desc.search(code)
             if match is None:#Is tag <description> defined in template?
                 errors.append(("ERR_BIBFORMAT_TEMPLATE_HAS_NO_DESCRIPTION", filename))
 
             format_template = bibformat_engine.get_format_template(filename, with_attributes=False)
             code = format_template['code']
             # Look for calls to format elements
             # Check existence of elements and attributes used in call
             elements_call = bibformat_engine.pattern_tag.finditer(code)
             for element_match in elements_call:
                 element_name = element_match.group("function_name")
                 filename = bibformat_engine.resolve_format_element_filename(element_name)
                 if filename is None and not bibformat_dblayer.tag_exists_for_name(element_name): #Is element defined?
                     errors.append(("ERR_BIBFORMAT_TEMPLATE_CALLS_UNDEFINED_ELEM", filename, element_name))
                 else:
                     format_element = bibformat_engine.get_format_element(element_name, with_built_in_params=True)
                     if format_element is None:#Can element be loaded?
                         if not can_read_format_element(element_name):
                             errors.append(("ERR_BIBFORMAT_TEMPLATE_CALLS_UNREADABLE_ELEM", filename, element_name))
                         else:
                             errors.append(("ERR_BIBFORMAT_TEMPLATE_CALLS_UNLOADABLE_ELEM", element_name, filename))
                     else:
                         # Are the parameters used defined in element?
                         params_call = bibformat_engine.pattern_function_params.finditer(element_match.group())
                         all_params = {}
                         for param_match in params_call:
                             param = param_match.group("param")
                             value = param_match.group("value")
                             all_params[param] = value
                             allowed_params = []
 
                             # Built-in params
                             for allowed_param in format_element['attrs']['builtin_params']:
                                 allowed_params.append(allowed_param['name'])
 
                             # Params defined in element
                             for allowed_param in format_element['attrs']['params']:
                                 allowed_params.append(allowed_param['name'])
 
                             if not param in allowed_params:
                                 errors.append(("ERR_BIBFORMAT_TEMPLATE_WRONG_ELEM_ARG",
                                                element_name, param, filename))
 
                         # The following code is too much time consuming. Only do where really requested
                         if checking > 0:
                             # Try to evaluate, with any object and pattern
                             recIDs = perform_request_search()
                             if len(recIDs) > 0:
                                 recID = recIDs[0]
                                 bfo = bibformat_engine.BibFormatObject(recID, search_pattern="Test")
                                 (result, errors_) = bibformat_engine.eval_format_element(format_element, bfo, all_params, verbose=7)
                                 errors.extend(errors_)
 
     else:# Template cannot be read
         errors.append(("ERR_BIBFORMAT_CANNOT_READ_TEMPLATE_FILE", filename, ""))
     return errors
 
 def check_format_element(name):
     """
     Returns the list of errors in the format element given by its name
 
     The errors are the formatted errors defined in bibformat_config.py file.
 
     @param name the name of the format element to check
     @return a list of errors
     """
     errors = []
     filename = bibformat_engine.resolve_format_element_filename(name)
     if filename is not None:#Can element be found in files?
         if can_read_format_element(name):#Can element be read?
             # Try to load
             try:
                 module_name = filename
                 if module_name.endswith(".py"):
                     module_name = module_name[:-3]
 
                 module = __import__("invenio.bibformat_elements."+module_name)
                 function_format  = module.bibformat_elements.__dict__[module_name].format
 
                 # Try to evaluate, with any object and pattern
                 recIDs = perform_request_search()
                 if len(recIDs) > 0:
                     recID = recIDs[0]
                     bfo = bibformat_engine.BibFormatObject(recID, search_pattern="Test")
                     element = bibformat_engine.get_format_element(name)
                     (result, errors_) = bibformat_engine.eval_format_element(element, bfo, verbose=7)
                     errors.extend(errors_)
             except Exception, e:
                 errors.append(("ERR_BIBFORMAT_IN_FORMAT_ELEMENT", name, e))
         else:
             errors.append(("ERR_BIBFORMAT_CANNOT_READ_ELEMENT_FILE", filename, ""))
     elif bibformat_dblayer.tag_exists_for_name(name):#Can element be found in database?
         pass
     else:
         errors.append(("ERR_BIBFORMAT_CANNOT_RESOLVE_ELEMENT_NAME", name))
 
     return errors
 
 def check_tag(tag):
     """
     Checks the validity of a tag
     """
     errors = []
     return errors
 
 
 def perform_request_dreamweaver_floater():
     """
     Returns a floater for Dreamweaver with all Format Elements avalaible.
     """
     # Get format elements lists of attributes
     elements = bibformat_engine.get_format_elements(with_built_in_params=True)
 
     keys =  elements.keys()
     keys.sort()
     elements = map(elements.get, keys)
 
     def filter_elem(element):
         """Keep element if is string representation contains all keywords of search_doc_pattern,
         and if its name does not start with a number (to remove 'garbage' from elements in tags table)"""
         if element['type'] != 'python' and \
                element['attrs']['name'][0] in ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']:
             return False
         else:
             return True
 
     elements = filter(filter_elem, elements)
 
     return bibformat_templates.tmpl_dreamweaver_floater(CFG_SITE_LANG, elements)
 
 
 def perform_request_verify_rule(ln, kbid, left, right, leftorright, currentname, tuples):
     """
     Returns a page element by which the user chooses an action:
     What to do if a rule already exists in some kb.
     Parameters:
     @ln language
     @kbid current kb id
     @left left side of rule
     @right right side of rule
     @leftorright "left" or "right" checking
     @currentname the name of the current kb
     @tuples a list containing "kb - rule" tuples
     """
     return bibformat_templates.tmpl_select_rule_action(ln, kbid, left, right, leftorright, currentname, tuples)
diff --git a/modules/bibformat/web/admin/bibformatadmin.py b/modules/bibformat/web/admin/bibformatadmin.py
index 90ed8fbf9..74a5f547e 100644
--- a/modules/bibformat/web/admin/bibformatadmin.py
+++ b/modules/bibformat/web/admin/bibformatadmin.py
@@ -1,1577 +1,1586 @@
 ## $Id$
 ##
 ## This file is part of CDS Invenio.
 ## Copyright (C) 2002, 2003, 2004, 2005, 2006, 2007, 2008 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.
 
 """CDS Invenio BibFormat Administrator Interface."""
 
 __revision__ = "$Id$"
 
 __lastupdated__ = """$Date$"""
 
 import MySQLdb
 
 from invenio import bibformatadminlib, \
                     config, \
                     bibformat_dblayer,\
                     bibformat_engine
 
 import os
 import re
 from invenio.bibrankadminlib import check_user
 from invenio.webpage import page, create_error_box
 from invenio.webuser import getUid, page_not_authorized, collect_user_info
 from invenio.messages import wash_language, gettext_set_language
 from invenio.urlutils import wash_url_argument, redirect_to_url
 from invenio.search_engine import search_pattern, \
                                   create_basic_search_units
 
 def index(req, ln=config.CFG_SITE_LANG):
     """
     Main BibFormat administration page.
 
     Displays a warning if we find out that etc/biformat dir is not writable by us
     (as most opeation of BibFormat must write in this directory).
 
     @param ln: language
     """
     warnings = []
 
     if not bibformatadminlib.can_write_etc_bibformat_dir():
         warnings.append(("WRN_BIBFORMAT_CANNOT_WRITE_IN_ETC_BIBFORMAT"))
 
     ln = wash_language(ln)
     _ = gettext_set_language(ln)
 
     # Check if user is authorized to administer
     # If not, still display page but offer to log in
     try:
         uid = getUid(req)
     except MySQLdb.Error, e:
         return error_page(req)
     (auth_code, auth_msg) = check_user(req, 'cfgbibformat')
     if not auth_code:
         is_admin = True
     else:
         is_admin = False
 
     navtrail = '''<a class="navtrail" href="%s/help/admin">%s</a>''' % \
                (config.CFG_SITE_URL, _("Admin Area"))
 
     return page(title=_("BibFormat Admin"),
                 body=bibformatadminlib.perform_request_index(ln=ln,
                                                              warnings=warnings,
                                                              is_admin=is_admin),
                 language=ln,
                 uid=uid,
                 navtrail = navtrail,
                 lastupdated=__lastupdated__,
                 req=req,
                 warnings=warnings)
 
 def output_formats_manage(req, ln=config.CFG_SITE_LANG, sortby="code"):
     """
     Main page for output formats management. Check for authentication and print output formats list.
     @param ln language
     @param sortby the sorting crieteria (can be 'code' or 'name')
     """
     ln = wash_language(ln)
     _ = gettext_set_language(ln)
     navtrail_previous_links = bibformatadminlib.getnavtrail()
 
     try:
         uid = getUid(req)
     except MySQLdb.Error, e:
         return error_page(req)
 
     (auth_code, auth_msg) = check_user(req, 'cfgbibformat')
     if not auth_code:
         sortby = wash_url_argument(sortby, 'str')
         return page(title=_("Manage Output Formats"),
                 body=bibformatadminlib.perform_request_output_formats_management(ln=ln, sortby=sortby),
                 uid=uid,
                 language=ln,
                 navtrail = navtrail_previous_links,
                 lastupdated=__lastupdated__,
                 req=req)
     else:
         return page_not_authorized(req=req,
                                    text=auth_msg,
                                    navtrail=navtrail_previous_links)
 
 def output_format_show(req, bfo, ln=config.CFG_SITE_LANG,
                        r_fld=[], r_val=[], r_tpl=[],
                        default="", r_upd="", chosen_option="",
                        **args):
     """
     Show a single output format. Check for authentication and print output format settings.
 
     The page either shows the output format from file, or from user's
     POST session, as we want to let him edit the rules without
     saving. Policy is: r_fld, r_val, rules_tpl are list of attributes
     of the rules.  If they are empty, load from file. Else use
     POST. The i th value of each list is one of the attributes of rule
     i. Rule i is the i th rule in order of evaluation.  All list have
     the same number of item.
 
     r_upd contains an action that has to be performed on rules. It
     can composed of a number (i, the rule we want to modify) and an
     operator : "save" to save the rules, "add" or "del".
     syntax: operator [number]
     For eg: r_upd = _("Save Changes") saves all rules (no int should be specified).
     For eg: r_upd = _("Add New Rule") adds a rule (no int should be specified).
     For eg: r_upd = _("Remove Rule") + " 5"  deletes rule at position 5.
     The number is used only for operation delete.
 
     An action can also be in **args. We must look there for string starting
     with '(+|-) [number]' to increase (+) or decrease (-) a rule given by its
     index (number).
     For example "+ 5" increase priority of rule 5 (put it at fourth position).
     The string in **args can be followed by some garbage that looks like .x
     or .y, as this is returned as the coordinate of the click on the
     <input type="image">. We HAVE to use args and reason on its keys, because for <input> of
     type image, iexplorer does not return the value of the tag, but only the name.
 
     Action is executed only if we are working from user's POST session
     (means we must have loaded the output format first, which is
     totally normal and expected behaviour)
 
 
 
     @param ln language
     @param bfo the filename of the output format to show
     @param r_fld the list of 'field' attribute for each rule
     @param r_val the list of 'value' attribute for each rule
     @param r_tpl the list of 'template' attribute for each rule
     @param default the default format template used by this output format
     @param r_upd the rule that we want to increase/decrease in order of evaluation
     """
     ln = wash_language(ln)
     _ = gettext_set_language(ln)
     navtrail_previous_links = bibformatadminlib.getnavtrail(''' &gt; <a class="navtrail" href="%s/admin/bibformat/bibformatadmin.py/output_formats_manage?ln=%s">%s</a>''' % (config.CFG_SITE_URL, ln, _("Manage Output Formats")))
     code = wash_url_argument(bfo, 'str')
 
     try:
         uid = getUid(req)
     except MySQLdb.Error, e:
         return error_page(req)
 
     (auth_code, auth_msg) = check_user(req, 'cfgbibformat')
     if not auth_code:
         bfo = wash_url_argument(bfo, 'str')
         default = wash_url_argument(default, 'str')
         r_upd = wash_url_argument(r_upd, 'str')
 
         if not bibformatadminlib.can_read_output_format(bfo): #No read permission
             return page(title=_("Restricted Output Format"),
                         body = """You don't have permission to
                         view this output format.""",
                         language=ln,
                         navtrail = navtrail_previous_links,
                         errors = [("ERR_BIBFORMAT_CANNOT_READ_OUTPUT_FILE",
                                    bfo ,
                                    "")],
                         lastupdated=__lastupdated__,
                         req=req)
 
         output_format = bibformat_engine.get_output_format(code=bfo,
                                                            with_attributes=True)
         name = output_format['attrs']['names']['generic']
         if name == "":
             name = bfo
 
         if not bibformatadminlib.can_write_output_format(bfo) and \
                chosen_option == "":#No write permission
             return dialog_box(req=req,
                               ln=ln,
                               title="File Permission on %s" % name,
                               message="You don't have write permission " \
                               "on <i>%s</i>.<br/> You can view the output " \
                               "format, but not edit it." % name,
                               navtrail=navtrail_previous_links,
                               options=[ _("Ok")])
 
         return page(title=_('Output Format %s Rules' % name),
                     body=bibformatadminlib.perform_request_output_format_show(bfo=bfo,
                                                                               ln=ln,
                                                                               r_fld=r_fld,
                                                                               r_val=r_val,
                                                                               r_tpl=r_tpl,
                                                                               default=default,
                                                                               r_upd=r_upd,
                                                                               args=args),
                     uid=uid,
                     language=ln,
                     navtrail = navtrail_previous_links,
                     lastupdated=__lastupdated__,
                     req=req)
     else:
         return page_not_authorized(req=req,
                                    text=auth_msg,
                                    navtrail=navtrail_previous_links)
 
 def output_format_show_attributes(req, bfo, ln=config.CFG_SITE_LANG):
     """
     Page for output format names and descrition attributes edition.
 
     @param ln language
     @param bfo the filename of the template to show
     """
     ln = wash_language(ln)
     _ = gettext_set_language(ln)
     navtrail_previous_links = bibformatadminlib.getnavtrail(''' &gt; <a class="navtrail" href="%s/admin/bibformat/bibformatadmin.py/output_formats_manage?ln=%s">%s</a>''' % (config.CFG_SITE_URL, ln , _("Manage Output Formats")))
 
     try:
         uid = getUid(req)
     except MySQLdb.Error, e:
         return error_page(req)
 
     (auth_code, auth_msg) = check_user(req, 'cfgbibformat')
     if not auth_code:
         bfo = wash_url_argument(bfo, 'str')
 
         if not bibformatadminlib.can_read_output_format(bfo): #No read permission
             return page(title=_("Restricted Output Format"),
                         body = """You don't have permission to
                         view this output format.""",
                         language=ln,
                         navtrail = navtrail_previous_links,
                         errors = [("ERR_BIBFORMAT_CANNOT_READ_OUTPUT_FILE", bfo ,"")],
                         lastupdated=__lastupdated__,
                         req=req)
 
         output_format = bibformat_engine.get_output_format(code=bfo,
                                                            with_attributes=True)
         name = output_format['attrs']['names']['generic']
 
         return page(title=_("Output Format %s Attributes" % name),
                     body=bibformatadminlib.perform_request_output_format_show_attributes(bfo, ln=ln),
                     uid=uid,
                     language=ln,
                     navtrail = navtrail_previous_links ,
                     lastupdated=__lastupdated__,
                     req=req)
 
     else:
         return page_not_authorized(req=req, text=auth_msg)
 
 def output_format_show_dependencies(req, bfo, ln=config.CFG_SITE_LANG):
     """
     Show the dependencies of the given output format.
 
     @param ln language
     @param bfo the filename of the output format to show
     """
     ln = wash_language(ln)
     _ = gettext_set_language(ln)
     navtrail_previous_links = bibformatadminlib.getnavtrail(''' &gt; <a class="navtrail" href="%s/admin/bibformat/bibformatadmin.py/format_templates_manage?ln=%s">%s </a>''' % (config.CFG_SITE_URL, ln, _("Manage Output Formats")))
 
     try:
         uid = getUid(req)
     except MySQLdb.Error, e:
         return error_page(req)
 
     (auth_code, auth_msg) = check_user(req, 'cfgbibformat')
     if not auth_code:
         bfo = wash_url_argument(bfo, 'str')
 
         if not bibformatadminlib.can_read_output_format(bfo): #No read permission
             return page(title=_("Restricted Output Format"),
                         body = """You don't have permission
                         to view this output format.""",
                         language=ln,
                         navtrail = navtrail_previous_links,
                         errors = [("ERR_BIBFORMAT_CANNOT_READ_OUTPUT_FILE",
                                    bfo ,
                                    "")],
                         lastupdated=__lastupdated__,
                         req=req)
 
         format_name = bibformat_engine.get_output_format_attrs(bfo)['names']['generic']
 
         return page(title=_("Output Format %s Dependencies" % format_name),
                     body=bibformatadminlib.perform_request_output_format_show_dependencies(bfo, ln=ln),
                     uid=uid,
                     language=ln,
                     navtrail = navtrail_previous_links,
                     lastupdated=__lastupdated__,
                     req=req)
 
     else:
         return page_not_authorized(req=req, text=auth_msg)
 
 def output_format_update_attributes(req, bfo, ln=config.CFG_SITE_LANG,
                                     name = "", description="",
                                     code="", content_type="",
                                     names_trans=[], visibility="0"):
     """
     Update the name, description and code of given output format
 
     @param ln language
     @param description the new description
     @param name the new name
     @param code the new short code (== new bfo) of the output format
     @param content_type the new content_type of the output format
     @param bfo the filename of the output format to update
     @param names_trans the translations in the same order as the languages from get_languages()
     @param visibility the visibility of the output format in the output formats list (public pages)
     """
     ln = wash_language(ln)
     _ = gettext_set_language(ln)
 
     try:
         uid = getUid(req)
     except MySQLdb.Error, e:
         return error_page(req)
 
     (auth_code, auth_msg) = check_user(req, 'cfgbibformat')
     if not auth_code:
 
         name = wash_url_argument(name, 'str')
         description = wash_url_argument(description, 'str')
         bfo = wash_url_argument(bfo, 'str')
         code = wash_url_argument(code, 'str')
         visibility = wash_url_argument(visibility, 'int')
         bfo = bibformatadminlib.update_output_format_attributes(bfo,
                                                                 name,
                                                                 description,
                                                                 code,
                                                                 content_type,
                                                                 names_trans,
                                                                 visibility)
 
         redirect_to_url(req, "output_format_show?ln=%(ln)s&bfo=%(bfo)s" % {'ln':ln,
                                                                            'bfo':bfo,
                                                                            'names_trans':names_trans})
     else:
         return page_not_authorized(req=req,
                                    text=auth_msg,
                                    chosen_option="")
 
 def output_format_delete(req, bfo, ln=config.CFG_SITE_LANG, chosen_option=""):
     """
     Delete an output format
 
     @param bfo the filename of the output format to delete
     """
     ln = wash_language(ln)
     _ = gettext_set_language(ln)
     navtrail_previous_links = bibformatadminlib.getnavtrail(''' &gt; <a class="navtrail" href="%s/admin/bibformat/bibformatadmin.py/output_formats_manage?ln=%s">%s</a> &gt; %s''' % (config.CFG_SITE_URL, ln, _("Manage Output Formats"), _("Delete Output Format")))
 
     try:
         uid = getUid(req)
     except MySQLdb.Error, e:
         return error_page(req)
 
     (auth_code, auth_msg) = check_user(req, 'cfgbibformat')
     if not auth_code:
 
         #Ask confirmation to user if not already done
         chosen_option = wash_url_argument(chosen_option, 'str')
         if chosen_option == "":
             bfo = wash_url_argument(bfo, 'str')
             format_name = bibformat_dblayer.get_output_format_names(bfo)['generic']
             return dialog_box(req=req,
                               ln=ln,
                               title="Delete %s"%format_name,
                               message="Are you sure you want to" \
                               "delete output format <i>%s</i>?" % format_name,
                               navtrail=navtrail_previous_links,
                               options=[_("Cancel"), _("Delete")])
 
         elif chosen_option==_("Delete"):
             bibformatadminlib.delete_output_format(bfo)
         redirect_to_url(req, "output_formats_manage?ln=%(ln)s"%{'ln':ln})
     else:
         return page_not_authorized(req=req, text=auth_msg)
 
 def output_format_add(req, ln=config.CFG_SITE_LANG):
     """
     Adds a new output format
     """
     ln = wash_language(ln)
     _ = gettext_set_language(ln)
 
     try:
         uid = getUid(req)
     except MySQLdb.Error, e:
         return error_page(req)
 
     (auth_code, auth_msg) = check_user(req, 'cfgbibformat')
     if not auth_code:
 
         bfo = bibformatadminlib.add_output_format()
         if bfo == None:
             return page(title=_("Cannot create output format"),
                         body = """BibFormat cannot add an output format.
                         Check output formats directory permissions.""",
                         language=ln,
                         lastupdated=__lastupdated__,
                         req=req)
         redirect_to_url(req, "output_format_show_attributes?ln=%(ln)s&bfo=%(bfo)s" % {'ln':ln, 'bfo':bfo})
     else:
         return page_not_authorized(req=req, text=auth_msg)
 
 def format_templates_manage(req, ln=config.CFG_SITE_LANG, checking='0'):
     """
     Main page for formats templates management. Check for authentication and print formats list.
     @param ln language
     @param checking if 0, basic checking. Else perform extensive checking (time-consuming)
     """
     ln = wash_language(ln)
     _ = gettext_set_language(ln)
     navtrail_previous_links = bibformatadminlib.getnavtrail()
 
     try:
         uid = getUid(req)
     except MySQLdb.Error, e:
         return error_page(req)
 
     (auth_code, auth_msg) = check_user(req, 'cfgbibformat')
     if not auth_code:
         checking_level = wash_url_argument(checking, 'int')
         return page(title=_("Manage Format Templates"),
                 body=bibformatadminlib.perform_request_format_templates_management(ln=ln, checking=checking_level),
                 uid=uid,
                 language=ln,
                 navtrail = navtrail_previous_links,
                 lastupdated=__lastupdated__,
                 req=req)
     else:
         return page_not_authorized(req=req,
                                    text=auth_msg,
                                    navtrail=navtrail_previous_links)
 
 
 def format_template_show(req, bft, code=None, ln=config.CFG_SITE_LANG,
                          ln_for_preview=config.CFG_SITE_LANG,
                          pattern_for_preview="",
                          content_type_for_preview="text/html",
                          chosen_option=""):
     """
     Main page for template edition. Check for authentication and print formats editor.
 
     @param ln language
     @param code the code being edited
     @param bft the name of the template to show
     @param ln_for_preview the language for the preview (for bfo)
     @param pattern_for_preview the search pattern to be used for the preview (for bfo)
     @param content_type_for_preview the (MIME) content type of the preview
     @param chosen_option returned value for dialog_box warning
     """
     ln = wash_language(ln)
     _ = gettext_set_language(ln)
 
     navtrail_previous_links = bibformatadminlib.getnavtrail('''
     &gt; <a class="navtrail" href="%s/admin/bibformat/bibformatadmin.py/format_templates_manage?ln=%s">%s</a>''' % (config.CFG_SITE_URL, ln ,  _("Manage Format Templates")))
 
     try:
         uid = getUid(req)
     except MySQLdb.Error, e:
         return error_page(req)
 
     (auth_code, auth_msg) = check_user(req, 'cfgbibformat')
     if not auth_code:
         format_template = wash_url_argument(bft, 'str')
         ln_preview = wash_language(ln_for_preview)
         pattern_preview = wash_url_argument(pattern_for_preview, 'str')
         if not bibformatadminlib.can_read_format_template(bft): #No read permission
             return page(title=_("Restricted Format Template"),
                         body = """You don't have permission
                         to view this format template.""",
                         language=ln,
                         navtrail = navtrail_previous_links,
                         errors = [("ERR_BIBFORMAT_CANNOT_READ_TEMPLATE_FILE",
                                    format_template ,
                                    "")],
                         lastupdated=__lastupdated__,
                         req=req)
 
         format_name = bibformat_engine.get_format_template_attrs(bft)['name']
         if not bibformatadminlib.can_write_format_template(bft) and \
                chosen_option == "": #No write permission
             return dialog_box(req=req,
                               ln=ln,
                               title="File Permission on %s" % format_name,
                               message="You don't have write permission " \
                               "on <i>%s</i>.<br/> You can view the template" \
                               ", but not edit it." % format_name,
                               navtrail=navtrail_previous_links,
                               options=[ _("Ok")])
 
 
         if bft.endswith('.xsl'):
             format_name += ' (XSL)'
         return page(title=_("Format Template %s"%format_name),
                 body=bibformatadminlib.perform_request_format_template_show(format_template,
                                                           code=code,
                                                           ln=ln,
                                                           ln_for_preview=ln_preview,
                                                           pattern_for_preview=pattern_preview,
                                                           content_type_for_preview=content_type_for_preview),
                 uid=uid,
                 language=ln,
                 navtrail = navtrail_previous_links,
                 lastupdated=__lastupdated__,
                 req=req)
     else:
         return page_not_authorized(req=req,
                                    text=auth_msg,
                                    navtrail=navtrail_previous_links)
 
 def format_template_show_attributes(req, bft, ln=config.CFG_SITE_LANG, new=0):
     """
     Page for template name and descrition attributes edition.
 
     This is also the first page shown when a format template
     has just been added. In that case new is different from
     False and we can offer specific option to user (for ex
     let him make a duplicate of existing template).
 
     @param ln language
     @param bft the name of the template to show
     @param new if "False", the template has not just been added
     """
     ln = wash_language(ln)
     _ = gettext_set_language(ln)
     navtrail_previous_links = bibformatadminlib.getnavtrail(''' &gt; <a class="navtrail" href="%s/admin/bibformat/bibformatadmin.py/format_templates_manage?ln=%s">%s</a>''' % (config.CFG_SITE_URL, ln, _("Manage Format Templates")))
 
     try:
         uid = getUid(req)
     except MySQLdb.Error, e:
         return error_page(req)
 
     (auth_code, auth_msg) = check_user(req, 'cfgbibformat')
     if not auth_code:
         format_template = wash_url_argument(bft, 'str')
         format_name = bibformat_engine.get_format_template_attrs(bft)['name']
         is_new = wash_url_argument(new, 'int')
 
         if not bibformatadminlib.can_read_format_template(bft): #No read permission
             return page(title=_("Restricted Format Template"),
                         body = """You don't have permission
                         to view this format template.""",
                         language=ln,
                         navtrail = navtrail_previous_links,
                         errors = [("ERR_BIBFORMAT_CANNOT_READ_TEMPLATE_FILE",
                                    format_template ,
                                    "")],
                         lastupdated=__lastupdated__,
                         req=req)
 
         return page(title=_("Format Template %s Attributes"%format_name),
                     body=bibformatadminlib.perform_request_format_template_show_attributes(bft, ln=ln, new=is_new),
                     uid=uid,
                     language=ln,
                     navtrail = navtrail_previous_links ,
                     lastupdated=__lastupdated__,
                     req=req)
 
     else:
         return page_not_authorized(req=req, text=auth_msg)
 
 def format_template_show_dependencies(req, bft, ln=config.CFG_SITE_LANG):
     """
     Show the dependencies (on elements) of the given format.
 
     @param ln language
     @param bft the filename of the template to show
     """
     ln = wash_language(ln)
     _ = gettext_set_language(ln)
     navtrail_previous_links = bibformatadminlib.getnavtrail(''' &gt; <a class="navtrail" href="%s/admin/bibformat/bibformatadmin.py/format_templates_manage?ln=%s">%s</a>''' % (config.CFG_SITE_URL, ln, _("Manage Format Templates")))
 
     try:
         uid = getUid(req)
     except MySQLdb.Error, e:
         return error_page(req)
 
     (auth_code, auth_msg) = check_user(req, 'cfgbibformat')
     if not auth_code:
         format_template = wash_url_argument(bft, 'str')
         format_name = bibformat_engine.get_format_template_attrs(bft)['name']
 
         return page(title=_("Format Template %s Dependencies" % format_name),
                     body=bibformatadminlib.perform_request_format_template_show_dependencies(bft, ln=ln),
                     uid=uid,
                     language=ln,
                     navtrail = navtrail_previous_links,
                     lastupdated=__lastupdated__,
                     req=req)
 
     else:
         return page_not_authorized(req=req, text=auth_msg)
 
 def format_template_update_attributes(req, bft, ln=config.CFG_SITE_LANG,
                                       name = "", description="",
                                       duplicate=None):
     """
     Update the name and description of given format template
 
     @param ln language
     @param description the new description
     @param name the new name
     @param bft the filename of the template to update
     @param duplicate the filename of template that we want to copy (the code)
     """
     ln = wash_language(ln)
     _ = gettext_set_language(ln)
 
     try:
         uid = getUid(req)
     except MySQLdb.Error, e:
         return error_page(req)
 
     (auth_code, auth_msg) = check_user(req, 'cfgbibformat')
     if not auth_code:
 
         if duplicate is not None:
             duplicate = wash_url_argument(duplicate, 'str')
         name = wash_url_argument(name, 'str')
         description = wash_url_argument(description, 'str')
         bft = bibformatadminlib.update_format_template_attributes(bft,
                                                                   name,
                                                                   description,
                                                                   duplicate)
 
         redirect_to_url(req, "format_template_show?ln=%(ln)s&bft=%(bft)s" % {'ln':ln, 'bft':bft})
     else:
         return page_not_authorized(req=req, text=auth_msg)
 
 def format_template_delete(req, bft, ln=config.CFG_SITE_LANG, chosen_option=""):
     """
     Delete a format template
     """
     ln = wash_language(ln)
     _ = gettext_set_language(ln)
     navtrail_previous_links = bibformatadminlib.getnavtrail('''
     &gt; <a class="navtrail" href="%s/admin/bibformat/bibformatadmin.py/format_templates_manage?ln=%s">%s</a> &gt; %s''' % (config.CFG_SITE_URL, ln ,_("Manage Format Templates"),_("Delete Format Template")))
 
     try:
         uid = getUid(req)
     except MySQLdb.Error, e:
         return error_page(req)
 
     (auth_code, auth_msg) = check_user(req, 'cfgbibformat')
     if not auth_code:
         #Ask confirmation to user if not already done
         chosen_option = wash_url_argument(chosen_option, 'str')
         if chosen_option == "":
             format_template = wash_url_argument(bft, 'str')
             format_name = bibformat_engine.get_format_template_attrs(bft)['name']
             return dialog_box(req=req,
                               ln=ln,
                               title="Delete %s" % format_name,
                               message="Are you sure you want to delete" \
                               "format template <i>%s</i>?" % format_name,
                               navtrail=navtrail_previous_links,
                               options=[_("Cancel"), _("Delete")])
 
         elif chosen_option==_("Delete"):
             bibformatadminlib.delete_format_template(bft)
 
         redirect_to_url(req, "format_templates_manage?ln=%(ln)s" % {'ln':ln})
     else:
         return page_not_authorized(req=req, text=auth_msg)
 
 def format_template_add(req, ln=config.CFG_SITE_LANG):
     """
     Adds a new format template
     """
     ln = wash_language(ln)
     _ = gettext_set_language(ln)
 
     try:
         uid = getUid(req)
     except MySQLdb.Error, e:
         return error_page(req)
 
     (auth_code, auth_msg) = check_user(req, 'cfgbibformat')
     if not auth_code:
 
         bft = bibformatadminlib.add_format_template()
         redirect_to_url(req, "format_template_show_attributes?ln=%(ln)s&bft=%(bft)s&new=1" % {'ln':ln, 'bft':bft})
     else:
         return page_not_authorized(req=req, text=auth_msg)
 
 def format_template_show_preview_or_save(req, bft, ln=config.CFG_SITE_LANG, code=None,
                                          ln_for_preview=config.CFG_SITE_LANG,
                                          pattern_for_preview="",
                                          content_type_for_preview='text/html',
                                          save_action=None,
                                          navtrail=""):
     """
     Print the preview of a record with a format template. To be included inside Format template
     editor. If the save_action has a value, then the code should also be saved at the same time
 
     @param code the code of a template to use for formatting
     @param ln_for_preview the language for the preview (for bfo)
     @param pattern_for_preview the search pattern to be used for the preview (for bfo)
     @param save_action has a value if the code has to be saved
     @param bft the filename of the template to save
     @param navtrail standard navtrail
     """
     ln = wash_language(ln)
     _ = gettext_set_language(ln)
 
     (auth_code, auth_msg) = check_user(req, 'cfgbibformat')
     if not auth_code:
         user_info = collect_user_info(req)
         uid = user_info['uid']
         bft = wash_url_argument(bft, 'str')
         if save_action is not None and code is not None:
             #save
             bibformatadminlib.update_format_template_code(bft, code=code)
         bibformat_engine.clear_caches()
         if code is None:
             code = bibformat_engine.get_format_template(bft)['code']
 
         ln_for_preview = wash_language(ln_for_preview)
         pattern_for_preview = wash_url_argument(pattern_for_preview, 'str')
         if pattern_for_preview == "":
             try:
                 recID = search_pattern(p='-collection:DELETED').pop()
             except KeyError:
                 return page(title="No Document Found",
                             body="",
                             uid=uid,
                             language=ln_for_preview,
                             navtrail = "",
                             lastupdated=__lastupdated__,
                             req=req,
                             navmenuid='search')
 
             pattern_for_preview = "recid:%s" % recID
         else:
             try:
                 recID = search_pattern(p=pattern_for_preview + \
                                         ' -collection:DELETED').pop()
             except KeyError:
                 return page(title="No Record Found for %s" % pattern_for_preview,
                             body="",
                             uid=uid,
                             language=ln_for_preview,
                             navtrail = "",
                             lastupdated=__lastupdated__,
                             req=req)
 
         units = create_basic_search_units(None, pattern_for_preview, None)
         keywords = [unit[1] for unit in units if unit[0] != '-']
         bfo = bibformat_engine.BibFormatObject(recID = recID,
                                                ln = ln_for_preview,
                                                search_pattern = keywords,
                                                xml_record = None,
                                                user_info = user_info)
         (body, errors) = bibformat_engine.format_with_format_template(bft,
                                                                       bfo,
                                                                       verbose=7,
                                                                       format_template_code=code)
 
         if content_type_for_preview == 'text/html':
             #Standard page display with CDS headers, etc.
             return page(title="",
                         body=body,
                         uid=uid,
                         language=ln_for_preview,
                         navtrail = navtrail,
                         lastupdated=__lastupdated__,
                         req=req,
                         navmenuid='search')
         else:
             #Output with chosen content-type.
             req.content_type = content_type_for_preview
             req.send_http_header()
             req.write(body)
     else:
         return page_not_authorized(req=req, text=auth_msg)
 
 def format_template_show_short_doc(req, ln=config.CFG_SITE_LANG, search_doc_pattern=""):
     """
     Prints the format elements documentation in a brief way. To be included inside Format template
     editor.
 
     @param ln: language
     @param search_doc_pattern a search pattern that specified which elements to display
     @param bft the name of the template to show
     """
     ln = wash_language(ln)
     _ = gettext_set_language(ln)
 
     try:
         uid = getUid(req)
     except MySQLdb.Error, e:
         return error_page(req)
 
     (auth_code, auth_msg) = check_user(req, 'cfgbibformat')
     if not auth_code:
         search_doc_pattern = wash_url_argument(search_doc_pattern, 'str')
         return bibformatadminlib.perform_request_format_template_show_short_doc(ln=ln, search_doc_pattern=search_doc_pattern)
     else:
         return page_not_authorized(req=req, text=auth_msg)
 
 
 def format_elements_doc(req, ln=config.CFG_SITE_LANG):
     """
     Main page for format elements documentation. Check for authentication and print format elements list.
     @param ln language
     """
     ln = wash_language(ln)
     _ = gettext_set_language(ln)
     navtrail_previous_links = bibformatadminlib.getnavtrail()
 
     try:
         uid = getUid(req)
     except MySQLdb.Error, e:
         return error_page(req)
 
     (auth_code, auth_msg) = check_user(req, 'cfgbibformat')
     if not auth_code:
         return page(title=_("Format Elements Documentation"),
                 body=bibformatadminlib.perform_request_format_elements_documentation(ln=ln),
                 uid=uid,
                 language=ln,
                 navtrail = navtrail_previous_links,
                 lastupdated=__lastupdated__,
                 req=req)
     else:
         return page_not_authorized(req=req,
                                    text=auth_msg,
                                    navtrail=navtrail_previous_links)
 
 def format_element_show_dependencies(req, bfe, ln=config.CFG_SITE_LANG):
     """
     Shows format element dependencies
 
     @param bfe the name of the bfe to show
     @param ln language
     """
     ln = wash_language(ln)
     _ = gettext_set_language(ln)
     navtrail_previous_links = bibformatadminlib.getnavtrail(''' &gt; <a class="navtrail" href="%s/admin/bibformat/bibformatadmin.py/format_elements_doc?ln=%s">%s</a>''' % (config.CFG_SITE_URL, ln , _("Format Elements Documentation")))
     try:
         uid = getUid(req)
     except MySQLdb.Error, e:
         return error_page(req)
 
     (auth_code, auth_msg) = check_user(req, 'cfgbibformat')
     if not auth_code:
         bfe = wash_url_argument(bfe, 'str')
         return page(title=_("Format Element %s Dependencies" % bfe),
                 body=bibformatadminlib.perform_request_format_element_show_dependencies(bfe=bfe, ln=ln),
                 uid=uid,
                 language=ln,
                 navtrail = navtrail_previous_links,
                 lastupdated=__lastupdated__,
                 req=req)
     else:
         return page_not_authorized(req=req, text=auth_msg, navtrail=navtrail_previous_links)
 
 def format_element_test(req, bfe, ln=config.CFG_SITE_LANG, param_values=None):
     """
     Allows user to test element with different parameters and check output
 
     'param_values' is the list of values to pass to 'format'
     function of the element as parameters, in the order ...
     If params is None, this means that they have not be defined by user yet.
 
     @param bfe the name of the element to test
     @param ln language
     @param param_values the list of parameters to pass to element format function
     """
     ln = wash_language(ln)
     _ = gettext_set_language(ln)
     navtrail_previous_links = bibformatadminlib.getnavtrail(''' &gt; <a class="navtrail" href="%s/admin/bibformat/bibformatadmin.py/format_elements_doc?ln=%s">%s</a>''' %( config.CFG_SITE_URL, ln , _("Format Elements Documentation")))
 
     (auth_code, auth_msg) = check_user(req, 'cfgbibformat')
     if not auth_code:
         bfe = wash_url_argument(bfe, 'str')
         user_info = collect_user_info(req)
         uid = user_info['uid']
         return page(title=_("Test Format Element %s" % bfe),
                 body=bibformatadminlib.perform_request_format_element_test(bfe=bfe,
                                                                            ln=ln,
                                                                            param_values=param_values,
                                                                            user_info=user_info),
                 uid=uid,
                 language=ln,
                 navtrail = navtrail_previous_links,
                 lastupdated=__lastupdated__,
                 req=req)
     else:
         return page_not_authorized(req=req,
                                    text=auth_msg,
                                    navtrail=navtrail_previous_links)
 
-def kb_manage(req, ln=config.CFG_SITE_LANG):
+def kb_manage(req, ln=config.CFG_SITE_LANG, search=""):
     """
     Main page for knowledge bases management. Check for authentication.
 
-    @param ln: language
+    @param ln language
+    @param search search for this in kb's
     """
     ln = wash_language(ln)
     _ = gettext_set_language(ln)
     navtrail_previous_links = bibformatadminlib.getnavtrail()
 
     try:
         uid = getUid(req)
     except MySQLdb.Error, e:
         return error_page(req)
 
     (auth_code, auth_msg) = check_user(req, 'cfgbibformat')
     if not auth_code:
         return page(title=_("Manage Knowledge Bases"),
-                body=bibformatadminlib.perform_request_knowledge_bases_management(ln=ln),
+                body=bibformatadminlib.perform_request_knowledge_bases_management(ln=ln, search=search),
                 uid=uid,
                 language=ln,
                 navtrail = navtrail_previous_links,
                 lastupdated=__lastupdated__,
                 req=req)
     else:
         return page_not_authorized(req=req,
                                    text=auth_msg,
                                    navtrail=navtrail_previous_links)
 
 
-def kb_show(req, kb, sortby="to", ln=config.CFG_SITE_LANG, startat=0, kb_type=None):
+def kb_show(req, kb, sortby="to", ln=config.CFG_SITE_LANG, startat=0, kb_type=None, search=""):
     """
     Shows the content of the given knowledge base id. Check for authentication and kb existence.
     Before displaying the content of the knowledge base, check if a form was submitted asking for
     adding, editing or removing a value.
 
     @param ln language
     @param kb the kb id to show
     @param sortby the sorting criteria ('from' or 'to')
     @param startat the number from which start showing mapping rules in kb
-    @param kb_type: None or taxonomy
+    @param kb_type None or taxonomy
+    @param search search for these in the kb
     """
 
     ln = wash_language(ln)
     _ = gettext_set_language(ln)
     navtrail_previous_links = bibformatadminlib.getnavtrail(''' &gt; <a class="navtrail" href="%s/admin/bibformat/bibformatadmin.py/kb_manage?ln=%s">%s</a>''' % (config.CFG_SITE_URL, ln, _("Manage Knowledge Bases")))
 
     try:
         uid = getUid(req)
     except MySQLdb.Error, e:
         return error_page(req)
 
     (auth_code, auth_msg) = check_user(req, 'cfgbibformat')
     if not auth_code:
 
         kb_id = wash_url_argument(kb, 'int')
         kb_name = bibformatadminlib.get_kb_name(kb_id)
 
         if kb_name is None:
             return page(title=_("Unknown Knowledge Base"),
                         body = "",
                         language=ln,
                         navtrail = navtrail_previous_links,
                         errors = [("ERR_BIBFORMAT_KB_ID_UNKNOWN", kb)],
                         lastupdated=__lastupdated__,
                         req=req)
 
 
         return page(title=_("Knowledge Base %s" % kb_name),
                 body=bibformatadminlib.perform_request_knowledge_base_show(ln=ln,
-                kb_id=kb_id, sortby=sortby, startat=startat),
+                kb_id=kb_id, sortby=sortby, startat=startat, search=search),
                 uid=uid,
                 language=ln,
                 navtrail = navtrail_previous_links,
                 lastupdated=__lastupdated__,
                 req=req)
     else:
         return page_not_authorized(req=req,
                                    text=auth_msg,
                                    navtrail=navtrail_previous_links)
 
 def kb_show_attributes(req, kb, ln=config.CFG_SITE_LANG, sortby="to"):
     """
     Shows the attributes (name, description) of a given kb
 
     @param ln language
     @param kb the kb id to show
     @param sortby the sorting criteria ('from' or 'to')
     """
     ln = wash_language(ln)
     _ = gettext_set_language(ln)
     navtrail_previous_links = bibformatadminlib.getnavtrail(''' &gt; <a class="navtrail" href="%s/admin/bibformat/bibformatadmin.py/kb_manage?ln=%s">%s</a>''' % (config.CFG_SITE_URL, ln, _("Manage Knowledge Bases")))
 
     try:
         uid = getUid(req)
     except MySQLdb.Error, e:
         return error_page(req)
 
     (auth_code, auth_msg) = check_user(req, 'cfgbibformat')
     if not auth_code:
 
         kb_id = wash_url_argument(kb, 'int')
         kb_name = bibformatadminlib.get_kb_name(kb_id)
 
         if kb_name is None:
             return page(title=_("Unknown Knowledge Base"),
                         body = "",
                         language=ln,
                         navtrail = navtrail_previous_links,
                         errors = [("ERR_BIBFORMAT_KB_ID_UNKNOWN", kb)],
                         lastupdated=__lastupdated__,
                         req=req)
 
 
         return page(title=_("Knowledge Base %s Attributes" % kb_name),
                 body=bibformatadminlib.perform_request_knowledge_base_show_attributes(ln=ln,
                                                                                       kb_id=kb_id,
                                                                                       sortby=sortby),
                 uid=uid,
                 language=ln,
                 navtrail = navtrail_previous_links,
                 lastupdated=__lastupdated__,
                 req=req)
     else:
         return page_not_authorized(req=req, text=auth_msg, navtrail=navtrail_previous_links)
 
 def kb_show_dependencies(req, kb, ln=config.CFG_SITE_LANG, sortby="to"):
     """
     Shows the dependencies of a given kb
 
     @param ln language
     @param kb the kb id to show
     @param sortby the sorting criteria ('from' or 'to')
     """
     ln = wash_language(ln)
     _ = gettext_set_language(ln)
     navtrail_previous_links = bibformatadminlib.getnavtrail(''' &gt; <a class="navtrail" href="%s/admin/bibformat/bibformatadmin.py/kb_manage?ln=%s">%s</a>''' % (config.CFG_SITE_URL, ln, _("Manage Knowledge Bases")))
 
     try:
         uid = getUid(req)
     except MySQLdb.Error, e:
         return error_page(req)
 
     (auth_code, auth_msg) = check_user(req, 'cfgbibformat')
     if not auth_code:
 
         kb_id = wash_url_argument(kb, 'int')
         kb_name = bibformatadminlib.get_kb_name(kb_id)
 
         if kb_name is None:
             return page(title=_("Unknown Knowledge Base"),
                         body = "",
                         language=ln,
                         navtrail = navtrail_previous_links,
                         errors = [("ERR_BIBFORMAT_KB_ID_UNKNOWN", kb)],
                         lastupdated=__lastupdated__,
                         req=req)
 
 
         return page(title=_("Knowledge Base %s Dependencies" % kb_name),
                 body=bibformatadminlib.perform_request_knowledge_base_show_dependencies(ln=ln,
                                                                                         kb_id=kb_id,
                                                                                         sortby=sortby),
                 uid=uid,
                 language=ln,
                 navtrail = navtrail_previous_links,
                 lastupdated=__lastupdated__,
                 req=req)
     else:
         return page_not_authorized(req=req,
                                    text=auth_msg,
                                    navtrail=navtrail_previous_links)
 
 def kb_add_mapping(req, kb, mapFrom, mapTo, sortby="to", ln=config.CFG_SITE_LANG, forcetype=None, replacements=None, kb_type=None):
     """
     Adds a new mapping to a kb.
 
     @param ln language
     @param kb the kb id to show
     @param sortby the sorting criteria ('from' or 'to')
     @param forcetype indicates if this function should ask about replacing left/right sides (None or 'no')
                      replace in current kb ('curr') or in all ('all')
     @param replacements an object containing kbname+++left+++right strings.
                      Can be a string or an array of strings
     @param kb_type None for normal from-to kb's, 't' for taxonomies
     """
     ln = wash_language(ln)
     _ = gettext_set_language(ln)
 
     navtrail_previous_links = bibformatadminlib.getnavtrail(''' &gt; <a class="navtrail" href="%s/admin/bibformat/bibformatadmin.py/kb_manage?ln=%s">%s</a>''' % (config.CFG_SITE_URL, ln, _("Manage Knowledge Bases")))
 
     try:
         uid = getUid(req)
     except MySQLdb.Error, e:
         return error_page(req)
 
     (auth_code, auth_msg) = check_user(req, 'cfgbibformat')
     if not auth_code:
 
         kb_id = wash_url_argument(kb, 'int')
         kb_name = bibformatadminlib.get_kb_name(kb_id)
 
         if kb_name is None:
             return page(title=_("Unknown Knowledge Base"),
                         body = "",
                         language=ln,
                         navtrail = navtrail_previous_links,
                         errors = [("ERR_BIBFORMAT_KB_ID_UNKNOWN", kb)],
                         lastupdated=__lastupdated__,
                         req=req)
 
         key = wash_url_argument(mapFrom, 'str')
         value = wash_url_argument(mapTo, 'str')
 
 	#check if key or value already exists in some KB
         left_sides = bibformat_dblayer.kb_key_rules(key)
         right_sides = bibformat_dblayer.kb_value_rules(value)
 
         if (len(right_sides) == 0) and (len(left_sides) == 0):
             #no problems, just add in current
             forcetype="curr"
 
         #likewise, if this is a taxonomy, just pass on
         if kb_type == 't':
             forcetype="curr"
 
         if forcetype and not forcetype == "no":
             pass
         else:
             if len(left_sides) > 0:
                 return page(title=_("Left side exists"),
                         body = bibformatadminlib.perform_request_verify_rule(ln, kb_id, key, value, "left", kb_name, left_sides),
                         language=ln,
                         navtrail = navtrail_previous_links,
                         lastupdated=__lastupdated__,
                         req=req)
 
             if len(right_sides) > 0:
                 return page(title=_("Right side exists"),
                         body = bibformatadminlib.perform_request_verify_rule(ln, kb_id, key, value, "right", kb_name, right_sides),
                         language=ln,
                         navtrail = navtrail_previous_links,
                         lastupdated=__lastupdated__,
                         req=req)
 
         if forcetype == "curr":
             bibformatadminlib.add_kb_mapping(kb_name, key, value)
         if forcetype == "all":
             #a bit tricky.. remove the rules given in param replacement and add the current
             #rule in the same kb's
             if replacements:
                 #"replacements" can be either a string or an arry. Let's make it always an array
                 if type(replacements) == type("this is a string"):
                     mystr = replacements
                     replacements = []
                     replacements.append(mystr)
                 for r in replacements:
                     if r.find("++++") > 0:
                         (rkbname, rleft, rright) = r.split('++++')
                         bibformatadminlib.remove_kb_mapping(rkbname, rleft)
                         #add only if this is not yet there..
                         if not bibformat_dblayer.kb_mapping_exists(rkbname, key):
                             bibformatadminlib.add_kb_mapping(rkbname, key, value)
 
         redirect_to_url(req, "kb_show?ln=%(ln)s&kb=%(kb)s&sortby=%(sortby)s&kb_type=%(kb_type)s" % {'ln':ln,
                                                                                 'kb':kb_id,
                                                                                 'sortby':sortby,
                                                                                 'kb_type':kb_type})
     else:
         return page_not_authorized(req=req,
                                    text=auth_msg,
                                    navtrail=navtrail_previous_links)
 
 def kb_edit_mapping(req, kb, key, mapFrom, mapTo,
                     update="", delete="", sortby="to", ln=config.CFG_SITE_LANG):
     """
     Edit a mapping to in kb. Edit can be "update old value" or "delete existing value"
 
     @param kb the knowledge base id to edit
     @param key the key of the mapping that will be modified
     @param mapFrom the new key of the mapping
     @param mapTo the new value of the mapping
     @param update contains a value if the mapping is to be updated
     @param delete contains a value if the mapping is to be deleted
     @param sortby the sorting criteria ('from' or 'to')
     """
     ln = wash_language(ln)
     _ = gettext_set_language(ln)
     navtrail_previous_links = bibformatadminlib.getnavtrail(''' &gt; <a class="navtrail" href="%s/admin/bibformat/bibformatadmin.py/kb_manage?ln=%s">%s</a>''' % (config.CFG_SITE_URL, ln, _("Manage Knowledge Bases")))
 
     try:
         uid = getUid(req)
     except MySQLdb.Error, e:
         return error_page(req)
 
     (auth_code, auth_msg) = check_user(req, 'cfgbibformat')
     if not auth_code:
         kb_id = wash_url_argument(kb, 'int')
         kb_name = bibformatadminlib.get_kb_name(kb_id)
 
         if kb_name is None:
             return page(title=_("Unknown Knowledge Base"),
                         body = "",
                         language=ln,
                         navtrail = navtrail_previous_links,
                         errors = [("ERR_BIBFORMAT_KB_ID_UNKNOWN", kb)],
                         lastupdated=__lastupdated__,
                         req=req)
 
 
         key = wash_url_argument(key, 'str')
         if delete != "":
             #Delete
             bibformatadminlib.remove_kb_mapping(kb_name, key)
         else:
             #Update
             new_key = wash_url_argument(mapFrom, 'str')
             new_value = wash_url_argument(mapTo, 'str')
             bibformatadminlib.update_kb_mapping(kb_name, key, new_key, new_value)
 
         redirect_to_url(req, "kb_show?ln=%(ln)s&kb=%(kb)s&sortby=%(sortby)s" % {'ln':ln, 'kb':kb_id, 'sortby':sortby})
     else:
         return page_not_authorized(req=req,
                                    text=auth_msg,
                                    navtrail=navtrail_previous_links)
 
 def kb_update_attributes(req, kb="", name="", description="", sortby="to",
                          ln=config.CFG_SITE_LANG, chosen_option=None, kb_type=None):
     """
     Update the attributes of the kb
 
     @param ln language
     @param kb the kb id to update
     @param sortby the sorting criteria ('from' or 'to')
     @param name the new name of the kn
     @param description the new description of the kb
     @param chosen_option set to dialog box value
     """
 
     ln = wash_language(ln)
     _ = gettext_set_language(ln)
 
     navtrail_previous_links = bibformatadminlib.getnavtrail(''' &gt; <a class="navtrail" href="%s/admin/bibformat/bibformatadmin.py/kb_manage?ln=%s">%s</a>''' % (config.CFG_SITE_URL, ln, _("Manage Knowledge Bases")))
 
     try:
         uid = getUid(req)
     except MySQLdb.Error, e:
         return error_page(req)
 
     (auth_code, auth_msg) = check_user(req, 'cfgbibformat')
     if not auth_code:
         kb_id = wash_url_argument(kb, 'int')
         if chosen_option is not None:
 	    # Update could not be performed.
 	    # Redirect to kb attributes page
             redirect_to_url(req, "kb_show_attributes?ln=%(ln)s&kb=%(kb)s&sortby=%(sortby)s&kb_type=%(kb_type)s" % {'ln':ln, 'kb':kb_id, 'sortby':sortby, 'kb_type':kb_type})
 
 
         kb_name = bibformatadminlib.get_kb_name(kb_id)
 
         if kb_name is None:
             return page(title=_("Unknown Knowledge Base"),
                         body = "",
                         language=ln,
                         navtrail = navtrail_previous_links,
                         errors = [("ERR_BIBFORMAT_KB_ID_UNKNOWN", kb)],
                         lastupdated=__lastupdated__,
                         req=req)
 
         new_name = wash_url_argument(name, 'str')
         if kb_name != new_name and bibformatadminlib.kb_exists(new_name):
 	    #A knowledge base with that name already exist
 	    #Do not update
             return dialog_box(req=req,
 			      ln=ln,
 			      title="Name already in use",
 			      message="""<i>%s</i> cannot be renamed to %s:
                               Another knowledge base already has that name.
                               <br/>Please choose another name.""" % (kb_name,
                                                                    new_name),
 			      navtrail=navtrail_previous_links,
 			      options=[ _("Ok")])
 
         new_desc = wash_url_argument(description, 'str')
         bibformatadminlib.update_kb_attributes(kb_name, new_name, new_desc)
         redirect_to_url(req, "kb_show?ln=%(ln)s&kb=%(kb)s&sortby=%(sortby)s" % {'ln':ln, 'kb':kb_id, 'sortby':sortby})
     else:
         return page_not_authorized(req=req,
                                    text=auth_msg,
                                    navtrail=navtrail_previous_links)
 
 def kb_export(req, kbname="", format="", ln=config.CFG_SITE_LANG):
     """
     Exports the given kb so that it is listed in stdout (the browser).
     """
     ln = wash_language(ln)
     _ = gettext_set_language(ln)
     webdir = config.CFG_WEBDIR
     names = ""
     errors = ""
     navtrail_previous_links = bibformatadminlib.getnavtrail(''' &gt; <a class="navtrail" href="%s/admin/bibformat/bibformatadmin.py/kb_manage?ln=%s">%s</a>''' % (config.CFG_SITE_URL, ln, _("Manage Knowledge Bases")))
     if not kbname:
         return page(title=_("Knowledge base name missing"),
                     body = """Required parameter kbname
                               is missing.""",
                     language=ln,
                     navtrail = navtrail_previous_links,
                     lastupdated=__lastupdated__,
                     req=req)
 
     #in order to make 'wget' downloads easy we do not require authorization
     #get the kb and print it
     mappings = bibformat_dblayer.get_kb_mappings(kbname)
     if not mappings:
         return page(title=_("No such knowledge base"),
                     body = "There is no knowledge base named "+kbname+" or it is empty",
                     language=ln,
                     navtrail = navtrail_previous_links,
                     lastupdated=__lastupdated__,
                     req=req)
 
     else:
+        seq = [] #sequence: right sides need to made unique
         for m in mappings:
             mkey = m['key']
             mvalue = m['value']
             if format == "right" or format == "kba":
-                req.write(mvalue+"\n")
+                seq.append(mvalue)
             else:
                 req.write(mkey+"---"+mvalue+"\n")
+        #make unique seq and print it
+        seqdict = {}
+        for s in seq:
+            seqdict[s] = 1
+        for s in sorted(seqdict.keys()):
+            req.write(s+"\n")
 
 def kb_add(req, ln=config.CFG_SITE_LANG, sortby="to", kbtype=""):
     """
     Adds a new kb
     """
     ln = wash_language(ln)
     _ = gettext_set_language(ln)
 
     navtrail_previous_links = bibformatadminlib.getnavtrail(''' &gt; <a class="navtrail" href="%s/admin/bibformat/bibformatadmin.py/kb_manage?ln=%s">%s</a>''' % (config.CFG_SITE_URL, ln, _("Manage Knowledge Bases")))
 
     try:
         uid = getUid(req)
     except MySQLdb.Error, e:
         return error_page(req)
 
     (auth_code, auth_msg) = check_user(req, 'cfgbibformat')
     if not auth_code:
         name = "Untitled"
         if kbtype:
             name = "Untitled Taxonomy"
         kb_id = bibformatadminlib.add_kb(kb_name=name, kb_type=kbtype)
         redirect_to_url(req, "kb_show_attributes?ln=%(ln)s&kb=%(kb)s" % {'ln':ln, 'kb':kb_id, 'sortby':sortby})
     else:
         navtrail_previous_links = bibformatadminlib.getnavtrail(''' &gt; <a class="navtrail" href="%s/admin/bibformat/bibformatadmin.py/kb_manage?ln=%s">%s</a>''' % (config.CFG_SITE_URL, ln, _("Manage Knowledge Bases")))
 
         return page_not_authorized(req=req,
                                    text=auth_msg,
                                    navtrail=navtrail_previous_links)
 
 
 def kb_delete(req, kb, ln=config.CFG_SITE_LANG, chosen_option="", sortby="to"):
     """
     Deletes an existing kb
 
     @param kb the kb id to delete
     """
     ln = wash_language(ln)
     _ = gettext_set_language(ln)
     navtrail_previous_links = bibformatadminlib.getnavtrail(''' &gt; <a class="navtrail" href="%s/admin/bibformat/bibformatadmin.py/kb_manage?ln=%s">%s</a> &gt; %s''' % (config.CFG_SITE_URL, ln, _("Manage Knowledge Bases"), _("Delete Knowledge Base")))
 
     try:
         uid = getUid(req)
     except MySQLdb.Error, e:
         return error_page(req)
 
     (auth_code, auth_msg) = check_user(req, 'cfgbibformat')
     if not auth_code:
         kb_id = wash_url_argument(kb, 'int')
         kb_name = bibformatadminlib.get_kb_name(kb_id)
         if kb_name is None:
             return page(title=_("Unknown Knowledge Base"),
                         body = "",
                         language=ln,
                         navtrail = navtrail_previous_links,
                         errors = [("ERR_BIBFORMAT_KB_ID_UNKNOWN", kb)],
                         lastupdated=__lastupdated__,
                         req=req)
 
         #Ask confirmation to user if not already done
         chosen_option = wash_url_argument(chosen_option, 'str')
         if chosen_option == "":
             return dialog_box(req=req,
                               ln=ln,
                               title="Delete %s" % kb_name,
                               message="""Are you sure you want to
                               delete knowledge base <i>%s</i>?""" % kb_name,
                               navtrail=navtrail_previous_links,
                               options=[_("Cancel"), _("Delete")])
 
         elif chosen_option==_("Delete"):
             bibformatadminlib.delete_kb(kb_name)
 
         redirect_to_url(req, "kb_manage?ln=%(ln)s" % {'ln':ln})
     else:
         navtrail_previous_links = bibformatadminlib.getnavtrail(''' &gt; <a class="navtrail" href="%s/admin/bibformat/bibformatadmin.py/kb_manage">%s</a>'''%(config.CFG_SITE_URL, _("Manage Knowledge Bases")))
 
         return page_not_authorized(req=req, text=auth_msg, navtrail=navtrail_previous_links)
 
 def validate_format(req, ln=config.CFG_SITE_LANG, bfo=None, bft=None, bfe=None):
     """
     Returns a page showing the status of an output format or format
     template or format element. This page is called from output
     formats management page or format template management page or
     format elements documentation.
 
     The page only shows the status of one of the format, depending on
     the specified one. If multiple are specified, shows the first one.
 
     @param ln language
     @param bfo an output format 6 chars code
     @param bft a format element filename
     @param bfe a format element name
     """
     ln = wash_language(ln)
     _ = gettext_set_language(ln)
 
 
     try:
         uid = getUid(req)
     except MySQLdb.Error, e:
         return error_page(req)
 
     (auth_code, auth_msg) = check_user(req, 'cfgbibformat')
     if not auth_code:
         if bfo is not None: #Output format validation
             bfo = wash_url_argument(bfo, 'str')
             navtrail_previous_links = bibformatadminlib.getnavtrail(''' &gt; <a class="navtrail" href="%s/admin/bibformat/bibformatadmin.py/output_formats_manage?ln=%s">%s</a>'''%(config.CFG_SITE_URL, ln, _("Manage Output Formats")))
 
             if not bibformatadminlib.can_read_output_format(bfo): #No read permission
                 return page(title=_("Restricted Output Format"),
                             body = """You don't have permission
                             to view this output format.""",
                             language=ln,
                             navtrail = navtrail_previous_links,
                             errors = [("ERR_BIBFORMAT_CANNOT_READ_OUTPUT_FILE",
                                        bfo ,
                                        "")],
                             lastupdated=__lastupdated__,
                             req=req)
 
             output_format = bibformat_engine.get_output_format(code=bfo,
                                                                with_attributes=True)
             name = output_format['attrs']['names']['generic']
             title = _("Validation of Output Format %s" % name)
 
         elif bft is not None: #Format template validation
             bft = wash_url_argument(bft, 'str')
             navtrail_previous_links = bibformatadminlib.getnavtrail(''' &gt; <a class="navtrail" href="%s/admin/bibformat/bibformatadmin.py/format_templates_manage?ln=%s">%s</a>''' % (config.CFG_SITE_URL, ln, _("Manage Format Templates")))
 
             if not bibformatadminlib.can_read_format_template(bft): #No read permission
                 return page(title=_("Restricted Format Template"),
                             body = """You don't have permission to
                             view this format template.""",
                             language=ln,
                             navtrail = navtrail_previous_links,
                             errors = [("ERR_BIBFORMAT_CANNOT_READ_TEMPLATE_FILE",
                                        bft ,
                                        "")],
                             lastupdated=__lastupdated__,
                             req=req)
             name = bibformat_engine.get_format_template_attrs(bft)['name']
             title = _("Validation of Format Template %s" % name)
 
         elif bfe is not None: #Format element validation
             bfe = wash_url_argument(bfe, 'str')
             navtrail_previous_links = bibformatadminlib.getnavtrail(''' &gt; <a class="navtrail" href="%s/admin/bibformat/bibformatadmin.py/format_elements_doc?ln=%s#%s">%s</a>''' % (config.CFG_SITE_URL, ln , bfe.upper() , _("Format Elements Documentation")))
 
             if not bibformatadminlib.can_read_format_element(bfe) and \
                    not bibformat_dblayer.tag_exists_for_name(bfe): #No read permission
                 return page(title=_("Restricted Format Element"),
                             body = """You don't have permission
                             to view this format element.""",
                             language=ln,
                             navtrail = navtrail_previous_links,
                             errors = [("ERR_BIBFORMAT_CANNOT_READ_ELEMENT_FILE", bfe ,"")],
                             lastupdated=__lastupdated__,
                             req=req)
             title = _("Validation of Format Element %s" % bfe)
 
         else: #No format specified
             return page(title=_("Format Validation"),
                         uid=uid,
                         language=ln,
                         errors = [("ERR_BIBFORMAT_VALIDATE_NO_FORMAT")],
                         navtrail = navtrail_previous_links,
                         lastupdated=__lastupdated__,
                         req=req)
 
         return page(title=title,
                     body=bibformatadminlib.perform_request_format_validate(ln=ln,
                                                                            bfo=bfo,
                                                                            bft=bft,
                                                                            bfe=bfe),
                     uid=uid,
                     language=ln,
                     navtrail = navtrail_previous_links,
                     lastupdated=__lastupdated__,
                     req=req)
 
     else:
         navtrail_previous_links = bibformatadminlib.getnavtrail(''' &gt; <a class="navtrail" href="%s/admin/bibformat/bibformatadmin.py/?ln=%s'''%(config.CFG_SITE_URL, ln))
 
         return page_not_authorized(req=req,
                                    text=auth_msg,
                                    navtrail=navtrail_previous_links)
 
 def download_dreamweaver_floater(req):
     """
     Trigger download of a BibFormat palette for Dreamweaver.
     """
     #bibformat_templates = invenio.template.load('bibformat')
     req.content_type = 'text/html'
     req.headers_out["Content-Disposition"] = "attachment; filename=BibFormat_floater.html"
     req.send_http_header()
     req.write(bibformatadminlib.perform_request_dreamweaver_floater())
 
 def dialog_box(req, url="", ln=config.CFG_SITE_LANG, navtrail="",
                title="", message="", options=[]):
     """
     Returns a dialog box with a given title, message and options.
     Used for asking confirmation on actions.
 
     The page that will receive the result must take 'chosen_option' as parameter.
 
     @param url the url used to submit the options chosen by the user
     @param options the list of labels for the buttons given as choice to user
     """
     import invenio
     bibformat_templates = invenio.template.load('bibformat')
 
     return page(title="",
                 body = bibformat_templates.tmpl_admin_dialog_box(url,
                                                                  ln,
                                                                  title,
                                                                  message,
                                                                  options),
                 language=ln,
                 lastupdated=__lastupdated__,
                 navtrail=navtrail,
                 req=req)
 
 def error_page(req):
     """
     Returns a default error page
     """
     return page(title="Internal Error",
                 body = create_error_box(req, ln=config.CFG_SITE_LANG),
                 description="%s - Internal Error" % config.CFG_SITE_NAME,
                 keywords="%s, Internal Error" % config.CFG_SITE_NAME,
                 language=config.CFG_SITE_LANG)