<?php
// $Id: biblio.module,v 1.123.2.42 2008/05/22 21:23:36 rjerome Exp $
/**
 *   biblio.module for Drupal
 *
 *   Copyright (C) 2006-2008  Ron Jerome
 *
 *   This program 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.
 *
 *   This program 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 this program; if not, write to the Free Software Foundation, Inc.,
 *   51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
 *
 */
function biblio_init() {
  drupal_add_css(drupal_get_path('module', 'biblio') .'/biblio.css');
}
function biblio_theme() {
  return array(
    'biblio_alpha_line' => array(
      'file' => 'biblio_theme.inc',
      'arguments' => array('type'),
    ),
    'biblio_admin_types_edit_form' => array(
      'file' => 'biblio_theme.inc',
      'arguments' => array('form'),
    ),
    'biblio_coin_button' => array(
      'file' => 'biblio_theme.inc',
      'arguments' => array('element'),
    ),
    'biblio_openurl' => array(
      'file' => 'biblio_theme.inc',
      'arguments' => array('openURL'),
    ),
    'biblio_export_links' => array(
      'file' => 'biblio_theme.inc',
      'arguments' => array('nid'),
    ),
    'biblio_short' => array(
      'file' => 'biblio_theme.inc',
      'arguments' => array(
        'node',
        'base' => 'biblio',
        'style_name' => 'classic',
        'inline' => FALSE
      ),

    ),
    'biblio_long' => array(
      'file' => 'biblio_theme.inc',
      'arguments' => array(
        'node',
        'base' => 'biblio',
        'style_name' => 'classic'
      ),

    ),
    'biblio_tabular' => array(
      'file' => 'biblio_theme.inc',
      'arguments' => array(
        'node',
        'base' => 'biblio',
        'teaser' => FALSE
      ),

    ),
    'biblio_list' => array(
      'file' => 'biblio_theme.inc',
      'arguments' => array(
        'node',
        'base' => 'biblio',
        'style_name' => 'classic',
        'inline' => FALSE
      ),

    ),
    'biblio_filters' => array(
      'file' => 'biblio_theme.inc',
      'arguments' => array('form'),
    ),
    'form_filter' => array(
      'file' => 'biblio_theme.inc',
      'arguments' => array('form'),
    ),
    'biblio_tagged_link' => array(
      'file' => 'biblio_theme.inc',
      'arguments' => array('base', 'node'),
    ),
    'biblio_xml_link' => array(
      'file' => 'biblio_theme.inc',
      'arguments' => array('base', 'node'),
    ),
    'biblio_bibtex_link' => array(
      'file' => 'biblio_theme.inc',
      'arguments' => array('base', 'node'),
    ),
    'biblio_contributors' => array(
      'file' => 'biblio_theme.inc',
      'arguments' => array('form'),
    ),
  );
}
function biblio_autocomplete($field, $string = '') {
  $matches = array();
  $result = db_query_range("SELECT %s FROM {biblio} WHERE LOWER(%s) LIKE LOWER('%s%%') ORDER BY %s ASC", array($field, $field, $string, $field) , 0, 10);
  while ($data = db_fetch_object($result)) {
    $matches[$data-> $field] = check_plain($data-> $field);
  }
  print drupal_to_js($matches);
  exit ();
}
function biblio_help_page() {
  $base = variable_get('biblio_base', 'biblio');
  $text .= "<h3>". t('General:') ."</h3>";
  $text .= "<p>". t('By default, the !url page will list all of the entries in the database sorted by Year in descending order. If you wish to sort by "Title" or "Type",  you may do so by clicking on the appropriate links at the top of the page.  To reverse the sort order, simply click the link a second time.', array(
    '!url' => l('',
    $base
  ))) ."</p>";
  $text .= "<h3>". t('Filtering Search Results:') ."</h3>";
  $text .= "<p>". t('If you wish to filter the results, click on the "Filter" tab at the top of the page.  To add a filter, click the radio button to the left of the filter type you wish to apply, then select the filter criteria from the drop down list on the right, then click the filter button.') ."</p>";
  $text .= "<p>". t('It is possible to create complex filters by returning to the <i>Filter</i> tab and adding additional filters.  Simply follow the steps outlined above and press the "Refine" button.') ."</p>";
  $text .= "<p>". t('All filters can be removed by clicking the <i>Clear All Filters</i> link at the top of the result page, or on the <i>Filter</i> tab they can be removed one at a time using the <i>Undo</i> button, or you can remove them all using the <i>Clear All</i> button.') ."</p>";
  $text .= "<p>". t('You may also construct URLs which filter.  For example, /biblio/year/2005 will show all of the entries for 2005.  /biblio/year/2005/author/smith will show all of entries from 2005 for smith.') ."</p>";
  $text .= "<h3>". t('Exporting Search Results:') ."</h3>";
  $text .= "<p>". t('Assuming this option has been enabled by the administrator, you can export search results directly into EndNote.  The link at the top of the result page will export all of the search results, and the links on individual entries will export the information related to that single entry.') ."</p>";
  $text .= "<p>". t('The information is exported in EndNote "Tagged" format similar to this...') ."<pre>". t('
                  %0  Book
                  %A  John Smith
                  %D  1959
                  %T  The Works of John Smith
                  ...') .'</pre></p>';
  $text .= "<p>". t('Clicking on one of the export links should cause your browser to ask you whether you want to Open, or Save To Disk, the file endnote.enw.  If you choose to open it, Endnote should start and ask you which library you would like store the results in.  Alternatively, you can save the file to disk and manually import it into EndNote.') ."</p>";
  return ($text);
}
/**
* Implementation of hook_help().
*
* Throughout Drupal, hook_help() is used to display help text at the top of
* pages. Some other parts of Drupal pages get explanatory text from these hooks
* as well. We use it here to provide a description of the module on the
* module administration page.
*/
function biblio_help($path, $arg) {
  switch ($path) {
    case 'admin/help#biblio' :
      return biblio_help_page();
    case 'admin/modules#description' :
      // This description is shown in the listing at admin/modules.
      return t('Manages a list of scholarly papers on your site');
    case 'node/add#biblio' :
      // This description shows up when users click "create content."
      return t('This allows you to add a bibliographic entry to the database');
  }
}
function biblio_node_info() {
  return array(
    'biblio' => array(
      'name' => t('Biblio'),
      'module' => 'biblio',
      'description' => t('Manages bibliographies')
    )
  );
}
/**
* Implementation of hook_access().
*
* Node modules may implement node_access() to determine the operations
* users may perform on nodes. This example uses a very common access pattern.
*/
function biblio_access($op, $node = '') {
  global $user;
  if ($op == 'admin') {
    return user_access('administer biblio');
  }
  if ($op == 'create') {
    // Only users with permission to do so may create this node type.
    return user_access('create biblio');
  }
  if ($op == 'import') {
    // Only users with permission to do so may import entries from file.
    return user_access('import from file');
  }
  if ($op == 'download') {
    // Only users with permission to do so may export entries from file.
    return user_access('show download links');
  }
  if ($op == 'export') {
    // Only users with permission to do so may export entries from file.
    return user_access('show export links');
  }
  if ($op == 'rss') {
    // Only users with permission to do so may export entries from file.
    return variable_get('biblio_rss', 0);
  }
  // Users who create a node may edit or delete it later, assuming they have the
  // necessary permissions.
  if ($op == 'update' || $op == 'delete') {
    if (user_access('edit own biblio entries') && ($user->uid == $node->uid)) {
      return true;
    }
    else
      if (user_access('edit all biblio entries')) {
        return true;
      }
      else {
        return false;
      }
  }
  if ($op == 'view') {
    if (variable_get('biblio_view_only_own', 0)) {
      if ($user->uid == $node->uid) {
        return true;
      }
      else {
        return false;
      }
    }
    else {
      return true;
    }
  }
}
/**
* Implementation of hook_perm().
*
* Since we are limiting the ability to create new nodes to certain users,
* we need to define what those permissions are here. We also define a permission
* to allow users to edit the nodes they created.
*/
function biblio_perm() {
  return array(
    'administer biblio',
    'create biblio',
    'edit all biblio entries',
    'edit own biblio entries',
    'import from file',
    'show export links',
    'show download links',
    'show filter tab',
    'show sort links',
    'view full text'
  );
}
/**
* Implementation of hook_link().
*
* This is implemented so that an edit link is displayed for users who have
* the rights to edit a node.
*/
function biblio_link($type, $node = NULL, $teaser = FALSE) {
  $links = array();
  if ($type == 'node' && $node->type == 'biblio') {
    // Don't display a redundant edit link if they are node administrators.
    if (biblio_access('update', $node) && !user_access('administer nodes')) {
      $links['biblio_edit'] = array(
        'title' => t('edit this entry'),
        'href' => "node/$node->nid/edit"
      );
      return $links;
    }
  }
  return;
}
/**
 * Implementation of hook_user().
 */
function biblio_user($type, & $edit, & $user, $category = NULL) {
  if ($type == 'form' && $category == 'account' && variable_get('biblio_show_user_profile_form', '1')) {
    $form = array();
    include_once drupal_get_path('module', 'biblio') .'/biblio.admin.inc';
    _biblio_get_user_profile_form($form, $user);
    return $form;
  }
  if ($type == 'validate' && $category == 'account') {
    if (($edit['biblio_profile_uid'] == 'lastname' || $edit['biblio_profile_uid'] == 'uid_lastname') && $edit['biblio_lastname'] == '') {
      $message = t('You did not supply a value in the "My last name" field of the "My publications" section.');
      form_set_error('category', $message);
    }
  }
  if ($type == 'after_update' && $category == 'account') {
    menu_rebuild();
  }
  if ($type == 'categories') {
    //  return array(array('name' => 'account', 'title' => t('Account settings'), 'weight' => 1));
  }
}
/**
* Implementation of hook_menu().
*
* Here we define some built in links for the biblio module, links exposed are:
*   /node/add/biblio      => to add a single entry
*   /biblio               => lists all entries in the biblio database
*   /biblio/list          => default local task for /biblio
*   /biblio/filter        => local task which allows users to add filters to their query
*   /biblio/filter/clear  => used internally to remove all filters
*   /biblio/help          => displays a help page
*   /biblio/export/endnote => used to export information in Endnote Tagged format
*   /biblio/import/form   => presents a form to allow the user to upload a file to import
*
*
*/
function biblio_menu() {
  global $user;
  $items = array();
  $base = variable_get('biblio_base', 'biblio');
  $items["$base"] = array(
    'title' => '',
    'page callback' => 'biblio_db_search',
    'access callback' => 'user_access',
    'access arguments' => array(
      'access content'
    ),
    'file' => 'biblio.pages.inc',
    'type' => MENU_CALLBACK
  );
  /*
    $items["$base/backup"] = array(
      'title' => '',
      'page callback' => 'biblio_backup',
      'access callback' => 'user_access',
      'access arguments' => array('access content'),
      'file' => 'biblio.import.export.inc',
      'type' => MENU_CALLBACK
    );
    $items["$base/pot"] = array(
      'title' => '',
      'page callback' => 'biblio_dump_db_data_for_pot',
      'access callback' => 'user_access',
      'access arguments' => array('access content'),
      'type' => MENU_CALLBACK
    );
  */
  if ($user->uid && variable_get('biblio_my_pubs_menu', '0') && ((isset($user->biblio_my_pubs_menu)) ? $user->biblio_my_pubs_menu : 0)) {
    $items["$base/user"] = array(
      'title' => 'My publications',
      'page callback' => 'biblio_get_user_pubs',
      'page arguments' => array($user),
      'access arguments' => array('access content'),
      'file' => 'biblio.pages.inc',
      'parent' => '',

    );
  }
  $items['user/%user/biblio'] = array(
    'title' => 'Publications',
    'page callback' => 'biblio_get_user_pubs',
    'page arguments' => array(1, 'profile'),
    'access callback' => 'user_view_access',
    'access arguments' => array(1),
    'file' => 'biblio.pages.inc',
    'type' => MENU_LOCAL_TASK
  );
  // The next two "LOCAL TASKS" are for the admin/settings/biblio page
  $items['admin/settings/biblio'] = array(
    'title' => 'Biblio settings',
    'description' => 'Configure default behavior of the biblio module.',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('biblio_admin_settings'),
    'access arguments' => array('administer biblio'),
    'file' => 'biblio.admin.inc',

  );
  $items['admin/settings/biblio/basic'] = array(
    'title' => 'Preferences',
    'type' => MENU_DEFAULT_LOCAL_TASK,
    'weight' => -10
  );
  $items['admin/settings/biblio/import'] = array(
    'title' => 'Import',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('biblio_import_form'),
    'access arguments' => array('administer biblio'),
    'file' => 'biblio.import.export.inc',
    'type' => MENU_LOCAL_TASK,
    'weight' => -7
  );
  $items['admin/settings/biblio/translate'] = array(
    'title' => 'Export',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('biblio_export_form'),
    'access arguments' => array('administer biblio'),
    'file' => 'biblio.import.export.inc',
    'type' => MENU_LOCAL_TASK,
    'weight' => -6
  );
  $items['admin/settings/biblio/types'] = array(
    'title' => 'Type Customization',
    'page callback' => 'biblio_admin_types_form',
    'access arguments' => array('administer biblio'),
    'file' => 'biblio.admin.inc',
    'type' => MENU_LOCAL_TASK,
    'weight' => -8
  );
  $items['admin/settings/biblio/defaults'] = array(
    'title' => 'Field Defaults',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('biblio_admin_types_edit_form'),
    'access arguments' => array('administer biblio'),
    'file' => 'biblio.admin.inc',
    'type' => MENU_LOCAL_TASK,
    'weight' => -9
  );
  $items['admin/settings/biblio/types/add'] = array(
    'title' => '',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('biblio_admin_types_add_form'),
    'access arguments' => array('administer biblio'),
    'file' => 'biblio.admin.inc',
    'type' => MENU_CALLBACK
  );
  $items['admin/settings/biblio/types/edit'] = array(
    'title' => '',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('biblio_admin_types_edit_form'),
    'access arguments' => array('administer biblio'),
    'file' => 'biblio.admin.inc',
    'type' => MENU_CALLBACK
  );
  $items['admin/settings/biblio/types/delete'] = array(
    'title' => '',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('biblio_admin_types_delete_form'),
    'access arguments' => array('administer biblio'),
    'file' => 'biblio.admin.inc',
    'type' => MENU_CALLBACK
  );
  $items['admin/settings/biblio/types/new'] = array(
    'title' => 'Add New Type',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('biblio_admin_types_add_form'),
    'access arguments' => array('administer biblio'),
    'file' => 'biblio.admin.inc',
    'type' => MENU_LOCAL_TASK,
    'weight' => -9
  );
  $items['admin/settings/biblio/types/reset'] = array(
    'title' => 'Reset all types to defaults ',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('biblio_admin_types_reset_form'),
    'access arguments' => array('administer biblio'),
    'file' => 'biblio.admin.inc',
    'type' => MENU_LOCAL_TASK
  );
  $items['admin/settings/biblio/types/hide'] = array(
    'title' => '',
    'page callback' => 'biblio_admin_types_hide',
    'access arguments' => array('administer biblio'),
    'file' => 'biblio.admin.inc',
    'type' => MENU_CALLBACK
  );
  $items['admin/settings/biblio/types/show'] = array(
    'title' => '',
    'page callback' => 'biblio_admin_types_show',
    'access arguments' => array('administer biblio'),
    'file' => 'biblio.admin.inc',
    'type' => MENU_CALLBACK
  );
  $items['biblio/autocomplete'] = array(
    'title' => 'Autocomplete ',
    'page callback' => 'biblio_autocomplete',
    'access callback' => 'user_access',
    'access arguments' => array('access content'),
    'type' => MENU_CALLBACK
  );
  $items['biblio/js'] = array(
    'title' => 'Javascript Contributors Form',
    'page callback' => 'biblio_contributors_js',
    'access arguments' => array('access content'),
    'type' => MENU_CALLBACK,

  );
  $items["$base/list"] = array(
    'title' => 'List',
    'type' => MENU_DEFAULT_LOCAL_TASK,
    'weight' => -10
  );
  $items["$base/filter"] = array(
    'title' => 'Filter',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('biblio_form_filter'),
    'access callback' => 'user_access',
    'access arguments' => array('show filter tab'),
    'type' => MENU_LOCAL_TASK,
    'file' => 'biblio.pages.inc',
    'weight' => -9
  );
  $items["$base/filter/clear"] = array(
    'title' => '',
    'page callback' => 'biblio_filter_clear',
    'access callback' => 'user_access',
    'access arguments' => array('access content'),
    'type' => MENU_CALLBACK
  );
  $items["$base/help"] = array(
    'title' => 'Help',
    'page callback' => 'biblio_help_page',
    'access callback' => 'user_access',
    'access arguments' => array('access content'),
    'type' => MENU_CALLBACK
  );
  $items["$base/import/form"] = array(
    'title' => '',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('biblio_import_form'),
    'file' => 'biblio.import.export.inc',
    'access callback' => 'user_access',
    'access arguments' => array('import from file'),
    'type' => MENU_CALLBACK
  );
  $items["$base/export"] = array(
    'title' => '',
    'page callback' => 'biblio_export',
    'access callback' => 'user_access',
    'access arguments' => array('show export links'),
    'file' => 'biblio.import.export.inc',
    'type' => MENU_CALLBACK
  );
  $items["$base/citekey"] = array(
    'title' => '',
    'page callback' => 'biblio_citekey_view',
    'access arguments' => array('access content'),
    'file' => 'biblio.pages.inc',
    'type' => MENU_CALLBACK
  );
  $items["$base/viewinline/%node". arg(2)] = array(
    'title' => '',
    'page callback' => 'biblio_view_inline',
    'page arguments' => array(1),
    'access callback' => 'node_access',
    'access arguments' => array('view', 1),
    'file' => 'biblio.pages.inc',
    'type' => MENU_CALLBACK
  );
  $items["$base/recent/rss.xml"] = array(
    'title' => 'RSS feed',
    'page callback' => 'biblio_recent_feed',
    'access callback' => 'biblio_access',
    'access arguments' => array('rss'),
    'type' => MENU_CALLBACK
  );
  return $items;
}
function biblio_filter_clear() {
  $_SESSION['biblio_filter'] = array();
  $base = variable_get('biblio_base', 'biblio');
  if (isset($_GET['sort'])) {
    $options .= "sort=". $_GET['sort'];
  }
  if (isset($_GET['order'])) {
    $options .= $options['query'] ? "&" : "";
    $options .= "order=". $_GET['order'];
  }
  drupal_goto($base, $options);
}
function biblio_nodeapi(& $node, $op, $teaser, $page) {
  switch ($op) {
    case 'delete revision' :
      db_query('DELETE FROM {biblio} WHERE vid = %d', $node->vid);
      db_query('DELETE FROM {biblio_contributor} WHERE nid = %d AND vid = %d', array($node->nid, $node->vid));
      break;
      /* 	case 'presave':
           if ($node->type == 'biblio')
           {
           //	$node->body = '';
           //	$node_clone = clone($node); // we need a clone since objects seem to get passed by reference regardless and we don't want to change the whole node object
           //	$node->body = theme('biblio_tabular', $node_clone, $base, $teaser);
            $style = variable_get('biblio_style', 'classic');
             $node->teaser = theme('biblio_short', $node_clone, $base, $style);
           }
           break;
      */
  }
}
function biblio_node_form_submit(& $node) {
  if (!is_numeric($node->biblio_year)) {
    if (drupal_strtoupper($node->biblio_year) == drupal_strtoupper(t("In Press"))) {
      $node->biblio_year = 9998;
    }
    if (drupal_strtoupper($node->biblio_year) == drupal_strtoupper(t("Submitted"))) {
      $node->biblio_year = 9999;
    }
  }
  if (variable_get('biblio_keyword_freetagging', 0) && variable_get('biblio_freetagging_vocab', 0)) {
    $vid = variable_get('biblio_freetagging_vocab', 0);
    $node->taxonomy['tags'][$vid] = $node->biblio_keywords;
  }
}
function biblio_form_alter(& $form, $form_state, $form_id) {
  if ($form_id == "biblio_node_form") {
    if (isset($form['menu']['#weight']) && $form['menu']['#weight'] < 20)
      $form['menu']['#weight'] = 20;
  }
  return $form;
}
/**
* Implementation of hook_form().
*
* Create the form for collecting the information
* specific to this node type. This hook requires us to return some HTML
* that will be later placed inside the form.
*/
function biblio_form($node, $form_state) {
  $output = '';
  $node_tid = $node->biblio_type;
  $form_state_tid = $form_state['values']['biblio_type'];
  $show_fields = FALSE;
  $tid = FALSE;
  $tid = (!empty($form_state_tid)) ? $form_state_tid : $node_tid;
  if (!empty($node->nid) || $tid)
    $show_fields = TRUE;
  $param['options'] = array(
    "enctype" => "multipart/form-data"
  );
  $result = db_query('SELECT t.* FROM {biblio_types} as t WHERE tid > -2 AND visible = 1');
  while ($option = db_fetch_object($result)) {
    $options["$option->tid"] = $option->name;
  }
  $form['#validate'][] = 'biblio_form_validate';
  //  $form['#submit'][] = 'biblio_form_submit';
  $form['#cache'] = TRUE;
  $form['biblio_type'] = array(
    '#type' => 'select',
    '#title' => t('Publication Type'),
    '#default_value' => $tid,
    '#options' => $options,
    '#description' => null,
    '#weight' => -5,
    '#attributes' => array(
      'onchange' => 'document.getElementById(\'node-form\').submit()'
    ),
    '#multiple' => false,
    '#required' => true
  );
  if ($show_fields) {
    $form['title'] = array(
      '#type' => 'textfield',
      '#title' => t('Title'),
      '#required' => TRUE,
      '#default_value' => $node->title,
      '#size' => 60,
      '#maxlength' => 255,
      '#weight' => -4
    );
    // Build the field array used to make the form
    $result = db_query("SELECT * FROM {biblio_fields} b, {biblio_field_type} bt, {biblio_field_type_data} btd
                        WHERE bt.fid=b.fid AND btd.ftdid=bt.ftdid
                        AND bt.tid=$tid
                        ORDER by btd.weight ASC ");
    while ($row = db_fetch_array($result)) {
      $fields[$row['name']] = $row;
    }
    $form['other_fields'] = array(
      '#type' => 'fieldset',
      '#collapsible' => TRUE,
      '#collapsed' => TRUE,
      '#title' => t('Other Biblio Fields'),
      '#description' => '',
      '#weight' => 19.5
    );
    foreach ($fields as $key => $fld) {
      if ($fld['common'] || $fld['visible']) {
        if ($fld['type'] == 'textarea') { /* wrap all textarea fields in collapsed field sets to save
                          * space on the page
                          */
          $colapse_field = $fld['name'] .'_field';
          $form[$colapse_field] = array(
            '#type' => 'fieldset',
            '#collapsible' => TRUE,
            '#collapsed' => TRUE,
            '#title' => $fld['title'],
            '#description' => '',
            '#weight' => $fld['weight'] / 10
          );
          $form[$colapse_field][$key] = array(
            '#default_value' => $node-> $key,
            '#type' => $fld['type'],
            '#title' => $fld['title'],
            '#size' => $fld['size'],
            '#required' => $fld['required'],
            '#maxlength' => $fld['maxsize'],
            '#weight' => $fld['weight'] / 10,
            '#autocomplete_path' => ($fld['autocomplete']) ? 'biblio/autocomplete/'. $fld['name'] : '',
            '#description' => $fld['hint']
          );
        }
        elseif ($fld['type'] == 'textfield') { // this is a regular textfield
          $form[$key] = array(
            '#default_value' => $node-> $key,
            '#type' => $fld['type'],
            '#title' => $fld['title'],
            '#size' => $fld['size'],
            '#required' => $fld['required'],
            '#maxlength' => $fld['maxsize'],
            '#weight' => $fld['weight'] / 10,
            '#autocomplete_path' => ($fld['autocomplete']) ? 'biblio/autocomplete/'. $fld['name'] : '',
            '#description' => $fld['hint']
          );
        }
        elseif ($fld['type'] == 'contrib_widget') {
          _biblio_contributor_widget($form, $node, $fld);
        }
      }
      else { /* add remaining which have not been specifcally associated with
                    * this type to the "Other Biblio Fields" fieldset
                    */
        if ($fld['type'] == 'contrib_widget') {
          _biblio_contributor_widget($form['other_fields'], $node, $fld);
        }
        else {
          $form['other_fields'][$key] = array(
            '#default_value' => $node-> $key,
            '#type' => $fld['type'],
            '#title' => $fld['title'],
            '#size' => $fld['size'],
            '#required' => $fld['required'],
            '#maxlength' => $fld['maxsize'],
            '#weight' => $fld['weight'] / 10,
            '#autocomplete_path' => ($fld['autocomplete']) ? 'biblio/autocomplete/'. $fld['name'] : '',
            '#description' => $fld['hint']
          );
        }
      }
    }
    if (isset($form_state['contributor_count'])) {
      $contributor_count = $form_state['contributor_count'];
    }
    else {
      $contributor_count = max(4, empty($node->contributors) ? 2 : count($node->contributors));
    }
    $form['body_field'] = array(
      '#type' => 'fieldset',
      '#collapsible' => TRUE,
      '#collapsed' => TRUE,
      '#title' => t('Full Text'),
      '#description' => '',
      '#weight' => 19
    );
    $form['body_field']['body'] = array(
      '#type' => 'textarea',
      '#title' => t('Full Text'),
      '#default_value' => $node->body,
      '#rows' => 10,
      '#required' => FALSE,
      '#description' => t('You may enter a full text or HTML version of the publication here.'),
      '#weight' => 19
    );
    $form['format'] = filter_form($node->format, 20);
  }
  return $form;
}
function _biblio_contributor_widget(& $form, $node, $fld) {
  $node = (array) $node;
  $type = str_replace('_', '-', $fld['name']);
  $contributor_count = max(4, count($node[$fld['name']]));
  $ctypes = db_query('SELECT * FROM {biblio_contributor_type} ORDER BY ctid ASC');
  while ($ctype = db_fetch_object($ctypes)) {
    $choice = new stdClass();
    $choice->option = array(
      $ctype->ctid => $ctype->type
    );
    $options[] = $choice;
  }
  $type_name = drupal_ucfirst(str_replace('_', ' ', $fld['type']));
  // Add a wrapper for the choices and more button.
  $form[$fld['name'] .'_wrapper'] = array(
    '#tree' => FALSE,
    '#type' => 'fieldset',
    '#collapsible' => TRUE,
    '#title' => $fld['title'],
    '#weight' => $fld['weight'],
    '#description' => t('Enter a single author per line using a format such as "Smith, John K" or "John K Smith" or "J.K. Smith"'),
    '#prefix' => '<div class="clear-block" id="'. $type .'-wrapper">',
    '#suffix' => '</div>'
  );
  // Container for just the contributors.
  $form[$fld['name'] .'_wrapper'][$fld['name']] = array(
    '#prefix' => '<div id="'. $type .'">',
    '#suffix' => '</div>',
    '#theme' => 'biblio_contributors',

  );
  // Add the current choices to the form.
  $fldname = $fld['name'];
  for ($delta = 0; $delta < $contributor_count; $delta++) {
    $name = isset($node[$fld['name']][$delta]) ? $node[$fld['name']][$delta]['name'] : '';
    $cid  = isset($node[$fld['name']][$delta]) ? $node[$fld['name']][$delta]['cid'] : '';
    $ctid = isset($node[$fld['name']][$delta]) ? $node[$fld['name']][$delta]['ctid'] : '';
    //  $type = isset($node->$fld['name'][$delta]['type']) ? $node->$fld['name'][$delta]['type'] : $type;
    $form[$fld['name'] .'_wrapper'][$fld['name']][$delta] = _biblio_contributor_form($delta, $fld['name'], $name, $cid, $ctid, $options);
  }
  // We name our button 'contrib_more' to avoid conflicts with other modules using
  // AHAH-enabled buttons with the id 'more'.
  $form[$fld['name'] .'_wrapper'][$fld['name'] .'_more'] = array(
    '#type' => 'submit',
    '#value' => t('More @title', array('@title' => $fld['title'])),
    '#description' => t("If the amount of boxes above isn't enough, click here to add more choices."),
    '#weight' => 1,
    '#submit' => array('biblio_more_contributors_submit'), // If no javascript action.
    '#ahah' => array(
      'path' => 'biblio/js/'. $fld['name'],
      'wrapper' => $type,
      'method' => 'replace',
      'effect' => 'fade'
    )
  );
  $node = (object)$node;
  return $form;
}
function _biblio_contributor_form($delta, $fld_name, $name = null, $cid = null, $ctid = null, $types = null) {
  $form = array(
    '#tree' => TRUE
  );
  // We'll manually set the #parents property of these fields so that
  // their values appear in the $form_state['values']['choice'] array.
  $form['name'] = array(
    '#type' => 'textfield',
    '#title' => t('Name'), // '#autocomplete_path' => 'biblio/autocomplete/contributor',
    '#default_value' => $name,
    '#parents' => array(
      $fld_name,
      $delta,
      'name'
     )
   );
  $form['ctid'] = array(
    '#type' => 'select',
    '#title' => t('Type'),
    '#default_value' => $ctid,
    '#options' => $types,
    '#multiple' => FALSE,
    '#parents' => array(
      $fld_name,
      $delta,
      'ctid'
    )
  );
  $form['cid'] = array(
    '#type' => 'hidden',
    '#value' => $cid,
    '#parents' => array(
      $fld_name,
      $delta,
      'cid'
    )
  );
  return $form;
}
function biblio_contributors_js($fld_name) {
  $delta = count($_POST[$fld_name]);
  // Build our new form element.
  $ctypes = db_query('SELECT * FROM {biblio_contributor_type} ORDER BY ctid ASC');
  while ($ctype = db_fetch_object($ctypes)) {
    $choice = new stdClass();
    $choice->option = array(
      $ctype->ctid => $ctype->type
    );
    $options[] = $choice;
  }
  $form_element = _biblio_contributor_form($delta, $fld_name, '', '', '', $options);
  drupal_alter('form', $form_element, array(), 'biblio_contributors_js');
  // Build the new form.
  $form_state = array(
    'submitted' => FALSE
  );
  $form_build_id = $_POST['form_build_id'];
  // Add the new element to the stored form. Without adding the element to the
  // form, Drupal is not aware of this new elements existence and will not
  // process it. We retreive the cached form, add the element, and resave.
  $form = form_get_cache($form_build_id, $form_state);
  $form[$fld_name .'_wrapper'][$fld_name][$delta] = $form_element;
  form_set_cache($form_build_id, $form, $form_state);
  $form += array(
    '#post' => $_POST,
    '#programmed' => FALSE
  );
  // Rebuild the form.
  $form = form_builder('biblio_node_form', $form, $form_state);
  // Render the new output.
  $contributor_form = $form[$fld_name .'_wrapper'][$fld_name];
  unset ($contributor_form['#prefix'], $contributor_form['#suffix']); // Prevent duplicate wrappers.
  $contributor_form[$delta]['#attributes']['class'] = empty($contributor_form[$delta]['#attributes']['class']) ? 'ahah-new-content' : $contributor_form[$delta]['#attributes']['class'] .' ahah-new-content';
  //$contributor_form[$delta]['type']['#value'] = 0;
  $output = theme('status_messages') . drupal_render($contributor_form);
  print drupal_json(array(
    'status' => TRUE,
    'data' => $output
  ));
  //print drupal_json(array('status' => TRUE, 'data' => '<pre>'.var_export($_POST[$fld_name], true).'</pre>'));
  exit();
}
/**
* Implementation of hook_validate().
*
*
* Errors should be signaled with form_set_error().
*/
function biblio_form_validate($form, & $form_state) {
  if ($form_state['storage'] == $form_state['values']['biblio_type'] || (!empty($form['#node']->biblio_type) && $form['#node']->biblio_type == $form_state['values']['biblio_type'])) {
    $form_state['storage'] = "";
    $form_state['rebuild'] = false;
  }
  else {
    $form_state['storage'] = $form_state['values']['biblio_type'];
    $form_state['rebuild'] = true;
    return;
  }
  if ($form_state['values']['biblio_type'] == 0) {
    form_set_error('biblio_type', t('You must select the type of publication'));
    return;
  }
  if (!isset($form_state['values']['biblio_year'])) {
    form_set_error('biblio_year', t('You must supply the year of publication'));
  }
  $today = getdate();
  if (!is_numeric($form_state['values']['biblio_year']) && $form_state['values']['biblio_year'] != t("In Press") && $form_state['values']['biblio_year'] != t("Submitted")) {
    form_set_error('biblio_year', t('Year of Publication must be a number between 1 and @thisyear or the words "In Press" or "Submitted" ', array(
      '@thisyear' => $today['year'] + 1
    )));
  }
  /*  if (!$node->biblio_secondary_title) {
    form_set_error('biblio_secondary_title', t('You must supply the Journal Title, Conference Name or Book Title'));
  }
  */
}
/**
* Implementation of hook_insert().
*
* As a new node is being inserted into the database, we need to do our own
* database inserts.
*/
function biblio_insert($node) {
  require_once(drupal_get_path('module', 'biblio') .'/biblio.contributors.inc');
  //$node->biblio_coins = biblio_coins($node);
  if (variable_get('biblio_auto_citekey', 1) && empty($node->biblio_citekey))
  $node->biblio_citekey = biblio_citekey_generate($node);
  $node->biblio_md5 = biblio_hash($node);
  drupal_write_record('biblio', $node);
  biblio_save_contributors($node);
}
/**
* Implementation of hook_update().
*
* As an existing node is being updated in the database, we need to do our own
* database updates.
*/
function biblio_update($node) {
  require_once(drupal_get_path('module', 'biblio') .'/biblio.contributors.inc');
  $node->biblio_coins = biblio_coins($node);
  $node->biblio_md5 = biblio_hash($node);
  if (!is_numeric($node->biblio_year)) {
    if (drupal_strtoupper($node->biblio_year) == drupal_strtoupper(t("In Press"))) {
      $node->biblio_year = 9998;
    }
    if (drupal_strtoupper($node->biblio_year) == drupal_strtoupper(t("Submitted"))) {
      $node->biblio_year = 9999;
    }
  }
  // Update the node in the database:
  //print_r($node);die;
  if ($node->revision) {
    drupal_write_record('biblio', $node);
  }
  else {
    drupal_write_record('biblio', $node, 'vid');
  }
  biblio_save_contributors($node, TRUE);
}
/**
* Implementation of hook_delete().
*
* When a node is deleted, we need to clean up related tables.
*/
function biblio_delete($node) {
  //first remove data from the biblio table
  db_query('DELETE FROM {biblio} WHERE nid = %d', $node->nid);
  //now remove the entries from the contributor linking table
  db_query('DELETE FROM {biblio_contributor} WHERE nid = %d', $node->nid);
  //now remove any orphaned contributors
  db_query('DELETE FROM {biblio_contributor_data}
            WHERE NOT EXISTS (SELECT * FROM {biblio_contributor}
            WHERE {biblio_contributor}.cid = {biblio_contributor_data}.cid)');
}
/**
* Implementation of hook_load().
*
* This hook is called
* every time a node is loaded, and allows us to do some loading of our own.
*
*/
function biblio_load($node) {
  require_once(drupal_get_path('module', 'biblio') .'/biblio.contributors.inc');
  $additions = db_fetch_object(db_query('SELECT b.*, bt.name as biblio_type_name
                                         FROM {biblio} b
                                         LEFT JOIN {biblio_types} bt on b.biblio_type = bt.tid
                                         WHERE b.vid = %d', $node->vid));
  if ($additions->biblio_year == 9998) {
    $additions->biblio_year = t("In Press");
  }
  if ($additions->biblio_year == 9999) {
    $additions->biblio_year = t("Submitted");
  }
  $additions->biblio_contributors = biblio_load_contributors($node->vid);
  return $additions;
}
function biblio_citekey_generate($node) {
  $prefix          = variable_get('biblio_citekey_prefix', '');
  $primary_field   = variable_get('biblio_citekey_field1', 'nid');
  $secondary_field = variable_get('biblio_citekey_field2', 'nid');
  $citekey = (!empty($node-> $primary_field)) ? $node-> $primary_field : (!empty($node-> $secondary_field)) ? $node-> $secondary_field : $node->nid;
  return $prefix . $citekey;
}
/**
* Implementation of hook_view().
*
*/
function biblio_view(& $node, $teaser = false, $page = false) {
  if (strlen(trim($node->body)))
    $node = node_prepare($node, $teaser);
  $style = variable_get('biblio_style', 'classic');
  $base  = variable_get('biblio_base', 'biblio');
  if ($teaser) {
    $node->content['teaser']['#value'] = theme('biblio_short', $node, $base, $style);
  }
  else {
    switch (variable_get('biblio_node_layout', '0')) {
      case 'orig' :
      case 'ft' :
        $node->content['body']['#value'] = theme('biblio_long', $node, $base, $style);
        break;
      case 'tabular' :
      default :
        $node->content['body']['#value'] = theme('biblio_tabular', $node, $base, $teaser);
        break;
    }
  }
  if ($page) {
    drupal_set_breadcrumb(array(l(t('Home'), NULL), l(drupal_ucfirst($base), $base)));
  }
  return $node;
}
/**
* Implementation of hook_block().
*
* Generates a block containing the latest poll.
*/
function biblio_block($op = 'list', $delta = 0) {
  if (user_access('access content')) {
    if ($op == 'list') {
      $blocks[0]['info'] = t('Most recent publications');
      return $blocks;
    }
    else
      if ($op == 'view') {
        // Retrieve the latest pubs
        $num_in_block = variable_get('biblio_rowsperblock', 4);
        $block_order = variable_get('biblio_block_order', 'n.created');
        $query = "SELECT COUNT(*)
                  FROM {node} n
                  LEFT JOIN {biblio} b  on n.vid=b.vid
                  WHERE n.type = 'biblio' AND n.status=1
                  ORDER BY $block_order DESC";
        $num_rows = db_result(db_query_range(db_rewrite_sql($query), 0, $num_in_block));
        if ($num_rows) {
          $query = "SELECT n.nid, n.title, n.status, b.biblio_year
                    FROM {node} n
                    LEFT JOIN {biblio} b  on n.vid=b.vid
                    WHERE n.type = 'biblio' AND n.status=1
                    ORDER BY $block_order DESC";
          $result = db_query_range(db_rewrite_sql($query), 0, $num_in_block);
          $base = variable_get('biblio_base', 'biblio');
          $block['subject'] = t(variable_get('biblio_block_title', 'Recently Added Publications'));
          $block['content'] .= '<div class="item-list"><ul>';
          while ($pub = db_fetch_object($result)) {
            $block['content'] .= '<li >'. l("$pub->title", "node/$pub->nid") .'</li>';
          }
          $block['content'] .= '</ul>';
          if (variable_get('biblio_rss', 0)) {
            $block['content'] .= theme('feed_icon', url("$base/recent/rss.xml", array(
              'absolute' => TRUE
            )), t('Recently Added Publications'));
          }
          $block['content'] .= '</div>';
        }
        return $block;
      }
  }
}
function biblio_recent_feed() {
  $query = "SELECT *
            FROM {node} AS n
            WHERE n.type = 'biblio' AND n.status=1
            ORDER BY n.created DESC";
  $numberInFeed = variable_get('biblio_rss_number_of_entries', 10);
  $siteName = variable_get('site_name', 'Drupal');
  $base = variable_get('biblio_base', 'biblio');
  $result = db_query_range(db_rewrite_sql($query), 0, $numberInFeed);
  $channel['title'] = $siteName .' - '. t("Recently Added Publications");
  $channel['link'] = url($base, array('absolute' => TRUE));
  $channel['description'] = t("This feed lists the %num most recently added publications on %site", array('%num' => $numberInFeed, '%site' => $siteName));
  $nids = array();
  while ($row = db_fetch_object($result)) {
    $nids[] = $row->nid;
  }
  node_feed($nids, $channel);
}
/**
 * This function creates a feed from a filter type query (i.e. biblio/author/jones)
 *
 * @param $query
 *    the SQL string to be used in the call to db_query
 * @param $terms
 *    the terms that are used to replace any place holders in the query
 * @param $title
 *    the channel tile displayed on the rss feed
 * @param $description
 *    the description printed under the channel tile
 * @param $link
 *    the portion of the url that comes after http://example.com/biblio/, will default to biblio
 */
function biblio_filter_feed($query, $terms = NULL, $title = NULL, $description = NULL, $link = NULL) {
  $base = variable_get('biblio_base', 'biblio');
  $result = db_query(db_rewrite_sql($query));
  $channel['title'] = $title;
  $channel['link'] = url($base . $link, array('absolute' => TRUE));
  $channel['description'] = $description;
  $nids = array();
  $result = db_query($query, $terms);
  while ($row = db_fetch_object($result)) {
    $nids[] = $row->nid;
  }
  node_feed($nids, $channel);
}
function biblio_get_db_fields() {
  $fields = array();
  $fields[] = 'nid';
  $fields[] = 'vid';
  $fields[] = 'biblio_type';
  $result = db_query('SELECT name FROM {biblio_fields} ');
  while ($field = db_fetch_array($result)) {
    $fields[] = $field['name'];
  }
  return $fields;
}
function _parse_author_array($authorArray) {
  //	$input = trim($input);
  // split on ' and '
  //	$authorArray = preg_split("/\s(and)\s/i", $input);
  // check if there's anything that looks like et. al
  $count = 1;
  foreach ($authorArray as $value) {
    $appellation = $prefix = $surname = $firstname = $initials = '';
    $author = explode(",", preg_replace("/\s{2,}/", ' ', trim($value)));
    $size = sizeof($author);
    // No commas therefore something like Mark Grimshaw, Mark Nicholas Grimshaw, M N Grimshaw, Mark N. Grimshaw
    if ($size == 1) {
      $author = split(" ", $value);
      // last of array is surname (no prefix if entered correctly)
      $surname = array_pop($author);
    }
    // Something like Grimshaw, Mark or Grimshaw, Mark Nicholas  or Grimshaw, M N or Grimshaw, Mark N.
    else
      if ($size == 2) {
        // first of array is surname (perhaps with prefix)
        list ($surname, $prefix) = _grabSurname(array_shift($author));
      }
    // If $size is > 2, we're looking at something like Bush, George W, III
    else {
      // last of array is 'Jr.', 'IV' etc.
      $appellation = array_pop($author);
      // first of array is surname (perhaps with prefix)
      list ($surname, $prefix) = _grabSurname(array_shift($author));
    }
    $remainder = join(" ", $author);
    list ($firstname, $initials) = _grabFirstnameInitials_old($remainder);
    $surname = $surname .' '. $appellation;
    $creators[] = array(
      'first_name' => trim("$firstname"
    ), 'initials' => trim("$initials"), 'last_name' => trim("$surname"), 'prefix' => trim("$prefix"), 'order' => "$count");
    $count++;
  }
  if (isset($creators))
    return $creators;
  return FALSE;
}
// grab firstname and initials which may be of form "A.B.C." or "A. B. C." or " A B C " etc.
/*
function biblio_views_tables() {

  $table = views_new_table('biblio', 'internal', 'node', 'vid', 'vid');
  $result = db_query('SELECT name,title FROM {biblio_fields} ');
  while ($field = db_fetch_array($result)) {
    views_table_add_field($table, $field['name'], "Biblio: ".$field['title'], "", array(
      'sortable' => true,
      'notafield' => false,
    ));
  }

  $tables['biblio'] = $table;
  $table = views_new_table('biblio_types', 'internal', 'biblio', 'tid', 'tid');
  $tables['biblio_types'] = $table;
  return $tables;
}
function biblio_views_default_views() {
  $view = new stdClass();
  $view->name = 'biblioview';
  $view->description = 'Shows a summary view of biblio entries';
  $view->access = array();
  $view->view_args_php = '';
  $view->page = TRUE;
  $view->page_title = 'Biblio';
  $view->page_header = '';
  $view->page_header_format = '1';
  $view->page_footer = '';
  $view->page_footer_format = '1';
  $view->page_empty = '';
  $view->page_empty_format = '1';
  $view->page_type = 'table';
  $view->url = 'biblioview';
  $view->use_pager = TRUE;
  $view->nodes_per_page = '10';
  $view->sort = array();
  $view->argument = array(
    array(
      'type' => 'nodetype',
      'argdefault' => '2',
      'title' => '',
      'options' => '',
      'wildcard' => 'biblio',
      'wildcard_substitution' => '',
    ),
  );
  $view->field = array(
    array(
      'tablename' => 'biblio',
      'field' => 'biblio_year',
      'label' => 'Year',
      'sortable' => '1',
      'defaultsort' => 'DESC',
    ),
    array(
      'tablename' => 'biblio',
      'field' => 'biblio_authors',
      'sortable' => '1',
      'label' => 'Author',
    ),
    array(
      'tablename' => 'node',
      'field' => 'title',
      'label' => 'Title',
      'handler' => 'views_handler_field_nodelink',
       'sortable' => '1',
     'options' => 'link',
    ),
  );
  $view->filter = array();
  $view->exposed_filter = array();
  $view->requires = array(biblio, node);
  $views[$view->name] = $view;
  return $views;
}
*/
/*******************************************
 * Filter
 * Largely inspired from the footnote module
 *
*******************************************/
function _biblio_citekey_print($citekey) {
  $nid = db_fetch_object(db_query("SELECT nid FROM {biblio} WHERE biblio_citekey = '%s' ORDER BY vid DESC", $citekey));
  if ($nid->nid > 0) {
    $style = variable_get('biblio_style', 'classic');
    $base = variable_get('biblio_base', 'biblio');
    $node = node_load($nid->nid);
    return theme('biblio_short', $node, $base, $style);
  }
  else {
    return t("Citekey @cite not found", array('@cite' => $citekey));
  }
}
/**
 * Implementation of hook_filter_tips().
 *
 * This hook allows filters to provide help text to users during the content
 * editing process. Short tips are provided on the content editing screen, while
 * long tips are provided on a separate linked page. Short tips are optional,
 * but long tips are highly recommended.
 */
function biblio_filter_tips($delta, $format, $long = FALSE) {
  switch ($delta) {
    case 0 :
      if ($long) {
        return t('You can cite references directly into texts with <code>&lt;bib&gt;citekey&lt;/bib&gt;</code>. This will be replaced with a running number (the publication reference) and the publication referenced by the citekey within the &lt;bib&gt; tags will be print to the bottom of the page (the reference).');
      }
      else {
        return t('Use &lt;bib&gt;...&lt;/bib&gt; to insert automatically numbered references.');
      }
      break;
  }
}
/**
 * Implementation of hook_filter().
 *
 * The bulk of filtering work is done here. This hook is quite complicated, so
 * we'll discuss each operation it defines.
 */
function biblio_filter($op, $delta = 0, $format = -1, $text = '') {
  // The "list" operation provides the module an opportunity to declare both how
  // many filters it defines and a human-readable name for each filter. Note that
  // the returned name should be passed through t() for translation.
  if ($op == 'list') {
    return array(
      0 => t('References &lt;bib&gt;')
    );
  }
  if ($op == 'no cache') {
    return true;
  }
  // All operations besides "list" provide a $delta argument so we know which
  // filter they refer to. We'll switch on that argument now so that we can
  // discuss each filter in turn.
  switch ($delta) {
    // First is the html footnotes filter
    case 0 :
      switch ($op) {
        // This description is shown in the administrative interface, unlike the
        // filter tips which are shown in the content editing interface.
        case 'description' :
          return t('Use &lt;bib&gt;...&lt;/bib&gt; to insert automatically numbered references.');
          // We don't need the "prepare" operation for this filter, but it's required
          // to at least return the input text as-is.
          //TODO: May need to escape <fn> if we use HTML filter too, but Footnotes could be first
        case 'prepare' :
          return $text;
          // The actual filtering is performed here. The supplied text should be
          // returned, once any necessary substitutions have taken place.
        case 'process' :
          if (variable_get('biblio_footnotes_integration', 0) && module_exists('footnotes')) { // this is used with footnote module integration to replace the <bib> tags with <fn> tags
            $text = preg_replace_callback('|<bib>(.*?)</bib>|s', '_biblio_filter_footnote_callback', $text);
            return $text;
          }
          else {
            $text = preg_replace_callback('|<bib>(.*?)</bib>|s', '_biblio_filter_replace_callback', $text);
            //Replace tag <footnotes> with the list of footnotes.
            //If tag is not present, by default add the footnotes at the end.
            //Thanks to acp on drupal.org for this idea. see http://drupal.org/node/87226
            $footer = '';
            $footer = _biblio_filter_replace_callback(NULL, 'output footer');
            if (preg_match('/<bibliography(\/( )?)?>/', $text) > 0) {
              $text = preg_replace('/<bibliography(\/( )?)?>/', $footer, $text, 1);
              return $text;
            }
            else {
              return $text ."\n\n". $footer;
            }
          }
      }
      break;
  }
}
function _biblio_filter_footnote_callback($matches) {
  $text = '<fn>'. _biblio_citekey_print($matches[1]) ."</fn>";
  return $text;
}
/**
 * Helper function called from preg_replace_callback() above
 *
 * Uses static vars to temporarily store footnotes found.
 * In my understanding, this is not threadsafe?!
 */
function _biblio_filter_replace_callback($matches, $op = '') {
  static $n = 0;
  static $store_matches = array();
  $str = '';
  if ($op == 'output footer') {
    if ($n > 0) {
      $str = '<p><hr /><p><h3>'. t('References') .'</h3></p>';
      $str .= '<div class="references"><ol>';
      for ($m = 1; $m <= $n; $m++) {
        $str .= '<li id="reference'. $m .'">'. _biblio_citekey_print($store_matches[$m -1]) ." </li>\n\n";
      }
      $str .= '</ol></div>';
    }
    $n = 0;
    $store_matches = array();
    return $str;
  }
  //default op: act as called by preg_replace_callback()
  array_push($store_matches, $matches[1]);
  $n++;
  $allowed_tags = array();
  $title = filter_xss($matches[1], $allowed_tags);
  //html attribute cannot contain quotes
  $title = str_replace('"', "&quot;", $title);
  //remove newlines. Browsers don't support them anyway and they'll confuse line break converter in filter.module
  $title = str_replace("\n", " ", $title);
  $title = str_replace("\r", "", $title);
  //return '<sup class="see_reference" title="'. $title .'"><a href="#reference'. $n .'">'. $n .'</a></sup>';
  //$text = '<span><a href="#reference'. $n .'">['. $n .']</a> </span>';
  //$text = '<span>['. $n .']</span>';
  //$text .= '<span class="hovertip">'._biblio_citekey_print($title) .'</span>';
  $text = '<span hovertip="reference'. $n .'">['. $n .']</span>';
  if (module_exists('hovertip')) {
    $text .= '<div id="reference'. $n .'" class="hovertip"><h1>Reference</h1>'. _biblio_citekey_print($title) .'</div>';
  }
  return $text;
}
function biblio_taxonomy($op, $type, $array = NULL) {
  if ($op == 'delete' && $term['vid'] == variable_get('biblio_freetagging_vocab', 0)) {
    switch ($type) {
      case 'term' :
        break;
      case 'vocabulary' :
        variable_del('biblio_keyword_freetagging');
        variable_del('biblio_freetagging_vocab');
        break;
    }
  }
}
function biblio_coins_generate(& $node) {
  if ($node) {
    $node->biblio_coins = biblio_coins($node);
    db_query("UPDATE {biblio}
              SET biblio_coins = '%s'
              WHERE vid = %d", $node->biblio_coins, $node->vid);
  }
  else {
    $result = db_query("SELECT nr.*, b.*
                        FROM {node} AS n
                        LEFT JOIN {node_revisions}  AS nr ON n.vid = nr.vid LEFT JOIN {biblio} AS b ON n.vid = b.vid
                        WHERE n.type = 'biblio'  ");
    while ($node = db_fetch_object($result)) {
      $node->biblio_coins = biblio_coins($node);
      db_query("UPDATE {biblio}
                SET biblio_coins = '%s'
                WHERE vid = %d", $node->biblio_coins, $node->vid);
    }
    drupal_goto('');
  }
}
function biblio_coins($node) {
  // Copyright:          Matthias Steffens <mailto:refbase@extracts.de> and the file's
  //                     original author.
  // Original Author:    Richard Karnesky <mailto:karnesky@gmail.com>  //
  // Adapted for biblio: Ron Jerome
  // fmt_info (type)
  $fmt = "info:ofi/fmt:kev:mtx:";
  // 'dissertation' is compatible with the 1.0 spec, but not the 0.1 spec
  if ($node->biblio_type == 108)
    $fmt .= "dissertation";
  elseif ($node->biblio_type == 102) $fmt .= "journal";
  elseif ($node->biblio_type == 100 || $node->biblio_type == 101) $fmt .= "book";
  // 'dc' (dublin core) is compatible with the 1.0 spec, but not the 0.1 spec.
  // We default to this, as it is the most generic type.
  else
    $fmt .= "dc";
  $co = biblio_contextObject($node);
  $coins = "ctx_ver=Z39.88-2004&amp;rft_val_fmt=". urlencode($fmt);
  foreach ($co as $coKey => $coValue) {
    // 'urlencode()' differs from 'rawurlencode() (i.e., RFC1738 encoding)
    // in that spaces are encoded as plus (+) signs
    $coKey = ereg_replace("au[0-9]*", "au", $coKey);
    $coins .= "&amp;". $coKey ."=". urlencode($coValue);
  }
  $coinsSpan = "<span class=\"Z3988\" title=\"". $coins ."\"></span>";
  return $coinsSpan;
}
function biblio_contextObject($node) {
  // Copyright:          Matthias Steffens <mailto:refbase@extracts.de> and the file's
  //                     original author.
  // Original Author:    Richard Karnesky <mailto:karnesky@gmail.com>  //
  // Adapted for biblio: Ron Jerome
  global $base_url;
  // $openurl_base = variable_get('biblio_baseopenurl', '');
  $co = array();
  // rfr_id
  $co["rfr_id"] = "info:sid/". ereg_replace("http://", "", $base_url);
  // genre (type)
  if (isset($node->biblio_type)) {
    if ($node->biblio_type == 102)
      $co["rft.genre"] = "article";
    elseif ($node->biblio_type == 101) $co["rft.genre"] = "bookitem";
    elseif ($node->biblio_type == 100) $co["rft.genre"] = "book";
    elseif ($node->biblio_type == "Journal") $co["rft.genre"] = "journal";
  }
  // atitle, btitle, title (title, publication)
  if (($node->biblio_type == 102) || ($node->biblio_type == 101)) {
    if (!empty($node->title))
      $co["rft.atitle"] = $node->title;
    if (!empty($node->biblio_secondary_title)) {
      $co["rft.title"] = $node->biblio_secondary_title;
      if ($node->biblio_type == 101)
        $co["rft.btitle"] = $node->biblio_secondary_title;
    }
  }
  elseif (!empty($node->title)) $co["rft.title"] = $node->title;
  if (($node->biblio_type == 100) && (!empty($node->title)))
    $co["rft.btitle"] = $node->title;
  // stitle (abbrev_journal)
  if (!empty($node->biblio_short_title))
    $co["rft.stitle"] = $node->biblio_short_title;
  // series (series_title)
  if (!empty($node->biblio_tertiary_title))
    $co["rft.series"] = $node->biblio_tertiary_title;
  // issn
  if (!empty($node->biblio_issn))
    $co["rft.issn"] = $node->biblio_issn;
  // isbn
  if (!empty($node->biblio_isbn))
    $co["rft.isbn"] = $node->biblio_isbn;
  // date (year)
  if (!empty($node->biblio_year))
    $co["rft.date"] = $node->biblio_year;
  // volume
  if (!empty($node->biblio_volume))
    $co["rft.volume"] = $node->biblio_volume;
  // issue
  if (!empty($node->biblio_issue))
    $co["rft.issue"] = $node->biblio_issue;
  // spage, epage, tpages (pages)
  // NOTE: lifted from modsxml.inc.php--should throw some into a new include file
  if (!empty($node->biblio_pages)) {
    if (ereg("[0-9] *- *[0-9]", $node->biblio_pages)) {
      list ($pagestart, $pageend) = preg_split('/\s*[-]\s*/', $node->biblio_pages);
      if ($pagestart < $pageend) {
        $co["rft.spage"] = $pagestart;
        $co["rft.epage"] = $pageend;
      }
    }
    elseif ($node->biblio_type == 100) { //"Book Whole") {
      $pagetotal = preg_replace('/^(\d+)\s*pp?\.?$/', "\\1", $node->biblio_pages);
      $co["rft.tpages"] = $pagetotal;
    }
    else
      $co["rft.spage"] = $node->biblio_pages;
  }
  // aulast, aufirst, author (author)
  if (!empty($node->biblio_contributors)) {
    if (!empty($node->biblio_contributors[0]['lastname']))
      $co["rft.aulast"] = $node->biblio_contributors[0]['lastname'];
    if (!empty($node->biblio_contributors[0]['firstname'])) {
      $co["rft.aufirst"] = $node->biblio_contributors[0]['firstname'];
    }
    elseif (!empty($node->biblio_contributors[0]['initials'])) {
      $co["rft.aufirst"] = $node->biblio_contributors[0]['initials'];
    }
    // TODO: cleanup and put this function in include.inc.php?
    $authorcount = count($node->biblio_contributors);
    for ($i = 1; $i < $authorcount; $i++) {
      if (!empty($node->biblio_contributors[$i]['lastname'])) {
        $au = $node->biblio_contributors[$i]['lastname'];
        if (!empty($node->biblio_contributors[$i]['firstname']) || !empty($node->biblio_contributors[$i]['initials']))
          $au .= ", ";
      }
      if (!empty($node->biblio_contributors[$i]['firstname'])) {
        $au .= $node->biblio_contributors[$i]['firstname'];
      }
      elseif (!empty($node->biblio_contributors[$i]['initials'])) {
        $au .= $node->biblio_contributors[$i]['initials'];
      }
      if (!empty($au))
        $co["rft.au". $i] = $au;
    }
  }
  // pub (publisher)
  if (!empty($node->biblio_publisher))
    $co["rft.pub"] = $node->biblio_publisher;
  // place
  if (!empty($node->biblio_place_published))
    $co["rft.place"] = $node->biblio_place_published;
  // id (doi, url)
  if (!empty($node->biblio_doi))
    $co["rft_id"] = "info:doi/". $node->biblio_doi;
  elseif (!empty($node->biblio_url)) $co["rft_id"] = $node->biblio_url;
  return $co;
}
function biblio_hash($node) {
  $hash_string = str_replace(' ', '', drupal_strtolower($node->title));
  $hash_string .= str_replace(' ', '', drupal_strtolower($node->biblio_contributors[0]['lastname']));
  $hash_string .= $node->biblio_year;
  return md5($hash_string);
}
function biblio_dump_db_data_for_pot() {
  $query = "SELECT name, description FROM {biblio_types} ";
  $result = db_query($query);
  while ($type = db_fetch_object($result)) {
    $output .= "msgid \"$type->name\"\nmsgstr \"\"\n\n";
    if (!empty($type->description))
      $output .= "msgid \"$type->description\"\nmsgstr \"\"\n\n";
  }
  $query = "SELECT title, hint FROM {biblio_field_type_data} ";
  $result = db_query($query);
  while ($type_data = db_fetch_object($result)) {
    $output .= "msgid \"$type_data->title\"\nmsgstr \"\"\n\n";
    if (!empty($type_data->hint))
      $output .= "msgid \"$type_data->hint\"\nmsgstr \"\"\n\n";
  }
  drupal_set_header('Content-Type: text/plain; charset=utf-8');
  drupal_set_header('Content-Disposition: attachment; filename=biblio_db_values.pot');
  print $output;
}