Sfoglia il codice sorgente

API: Removed duplicate files

Lacey Sanderson 11 anni fa
parent
commit
fbeffa7b9b

+ 0 - 602
tripal_core/api/tripal_core.database_references.api.inc

@@ -1,602 +0,0 @@
-<?php
-
-/**
- * @file
- * API to manage the chado _dbxref table for various Tripal Node Types
- *
- * How To Use:
- * @code
-
-  function chado_example_form($form, $form_state) {
-
-    // Default values for form elements can come in the following ways:
-    //
-    // 1) as elements of the $node object.  This occurs when editing an existing node
-    // 2) in the $form_state['values'] array which occurs on a failed validation or
-    //    ajax callbacks when the ajax call originates from non-submit fields other
-    //    than button
-    // 3) in the $form_state['input'] array which occurs on ajax callbacks from submit
-    //    form elements (e.g. buttons) and the form is being rebuilt but has not yet
-    //    been validated
-    //
-    // The reference elements added by this function do use AJAX calls from buttons,
-    // therefore, it is important to check for form values in the $form_state['values']
-    // for case #2 above, and in the $form_state['input'] for case #3.
-    // See the chado analysis node form for an example.
-
-
-    // Next, add in all the form array definition particular to your node type
-
-    // To add in the additional database reference form elements, you first need to prepare the arguments
-    // for the function call.
-
-    $details = array(
-      'linking_table' => 'example_dbxref',         // the name of the table linking additional dbxrefs to this node
-      'base_foreign_key' => 'example_id',          // key to link to the chado content created by this node
-      'base_key_value' => $example_id,             // the value of the above key
-      'fieldset_title' => 'Additional References', // the non-translated title for this fieldset
-      'additional_instructions' => ''              // a non-stranslated string providing additional instructions
-    );
-
-    // Finally, and add the additional form elements to the form
-    tripal_core_additional_dbxrefs_form($form, $form_state, $details);
-
-    return $form;
-  }
-
-  function chado_example_insert($node) {
-
-    // if there is an example_id in the $node object then this must be a sync so
-    // we can skip adding the chado_example as it is already there, although
-    // we do need to proceed with the rest of the insert
-    if (!property_exists($node, 'example_id')) {
-
-      // Add record to chado example table
-
-      // Add to any other tables needed
-
-      // Add all additional database references
-      // This function will create new database references as needed and select existing ones.
-      // Existing _dbxref links will be cleared and then re-added
-      tripal_core_additional_dbxrefs_form_update_dbxrefs(
-        $node,              // the node object passed in via hook_insert()
-        'example_dbxref',   // the name of the _dbxref linking table
-        'example_id',       // key to link to the chado content created by this node
-        $node->example_id   // value of the above key
-      );
-    }
-
-    // Add record to chado_example linking example_id to new node
-
-  }
-
-  function chado_example_update($node) {
-
-
-      // Update record in chado example table
-
-      // Update any other tables needed
-
-      // Update all additional database references
-      // This function will create new database references as needed and select existing ones.
-      // Existing _dbxref links will be cleared and then re-added
-      tripal_core_additional_dbxrefs_form_update_dbxrefs(
-        $node,              // the node object passed in via hook_insert()
-        'example_dbxref',   // the name of the _dbxref linking table
-        'example_id',       // key to link to the chado content created by this node
-        $node->example_id   // value of the above key
-      );
-
-    // Don't need to update chado_example linking table since niether example_id or nid can be changed in update
-
-  }
-
- * @endcode
- */
-
-/**
- * @section
- * Additional Database References Form to be added to node forms
- */
-
-/**
- * Provides a form for adding to BASE_dbxref and dbxref tables
- *
- * @param $form
- *   The Drupal form array into which the dbxref elements will be added
- * @param $form_state
- *   The corresponding form_state array for the form
- * @param $details
- *   An array defining details needed by this form. Required Keys are:
- *     - linking_table: the name of the dbxref linking table (ie: feature_dbxref)
- *     - base_foreign_key: the name of the foreign key linking this table to the non-dbxref table (ie: feature_id)
- *     - base_key_value: the value of the base_foreign_key for the current form (ie: 999 if the feature_id=999)
- *   Optional keys include:
- *     - fieldset_title: the non-translated title for this fieldset
- *     - additional_instructions: a non-translated string providing additional instructions
- */
-function tripal_core_additional_dbxrefs_form(&$form, &$form_state, $details) {
-
-  // Set Defaults for optional fields
-  $details['fieldset_title'] = 'Additional Database References';
-  $details['additional_instructions'] = '';
-
-  // the fieldset of the dbxref elements
-  $form['addtl_dbxrefs'] = array(
-    '#type' => 'fieldset',
-    '#title' => t($details['fieldset_title']),
-    '#description' => t('You may add additional database references by
-      selecting a database reference type from the dropdown and adding text.  You may add
-      as many database references as desired by clicking the add button on the right.  To
-      remove a database reference, click the remove button. ' . $details['additional_instructions']),
-    '#prefix' => "<div id='addtl-dbxrefs-fieldset'>",
-    '#suffix' => '</div>'
-  );
-
-  // this form element is a tree, so that we don't puke all of the values into then node variable
-  // it is set as a tree, and keeps them in the $form_state['values']['dbxref_table'] heading.
-  $form['addtl_dbxrefs']['dbxref_table'] = array(
-    '#type' => 'markup',
-    '#tree' => TRUE,
-    '#prefix' => '<div id="tripal-generic-edit-addtl_dbxrefs-table">',
-    '#suffix' => '</div>',
-    '#theme' => 'tripal_core_additional_dbxrefs_form_table'
-  );
-
-  /* DBxrefs can come to us in two ways:
-   *
-   * 1) In the form state in the $form_state['chado_additional_dbxrefs']. Data is in this field
-   *    when an AJAX call updates the form state or a validation error.
-   *
-   * 2) Directly from the database if the record already has dbxref's associated.  This
-   *    data is only used the first time the form is loaded. On AJAX calls or validation
-   *    errors the fields on the form are populated from the $form_state['chado_additional_dbxrefs']
-   *    entry.
-   */
-  if (isset($form_state['chado_additional_dbxrefs'])) {
-    $existing_dbxrefs = $form_state['chado_additional_dbxrefs'];
-  }
-  else {
-    $existing_dbxrefs = chado_query(
-      "SELECT dbxref.dbxref_id, db.name as db_name, db.db_id as db_id, dbxref.accession as accession, dbxref.description as description, dbxref.version
-        FROM {dbxref} dbxref
-        LEFT JOIN {db} db ON db.db_id = dbxref.db_id
-        LEFT JOIN {".$details['linking_table']."} linking_table ON linking_table.dbxref_id = dbxref.dbxref_id
-       WHERE linking_table.".$details['base_foreign_key']."= :base_key_value
-       ORDER BY db.name ASC, dbxref.version ASC",
-       array(':base_key_value' => $details['base_key_value'])
-    );
-  }
-
-  /* The format of the $existing_dbxref's array is either:
-   *
-   * From the chado_additional_dbxrefs array:
-   * $form_state['chado_additional_dbxrefs'] = array(
-   *   '[db_id]-[version]' => array(
-   *     'db_id' => [the db.db_id value]
-   *     'db_name' => [the db.name value]
-   *     'dbxref_id' => [the dbxref.dbxref_id value, or NULL if it doesn't yet exists],
-   *     'version' => [the dbxref.version value],
-   *     'accession' => [the dbxref.accession value],
-   *   ),
-   * );
-   *
-   * OR
-   * Populated from the database:
-   * $existing_dbxref = array(
-   *   0 => array(
-   *     'dbxref_id' => [the dbxref.dbxref_id value],
-   *     'db_name' => [the db.name value],
-   *     'db_id' => [the db.db_id value],
-   *     'accession' => [the dbxref.accession value],
-   *     'description' => [the dbxref.description value],
-   *     'version' => [the dbxref.versiion value],
-   *   ),
-   * );
-   *
-   * NOTE: The main difference is the key
-   *
-   * Loop on the array elements of the $existing_dbxrefs array and add
-   * an element to the form for each one.
-   */
-  foreach ($existing_dbxrefs as $dbxref) {
-
-    // Since the version is part of the key, when it is '' we need to use something
-    // in the key to indicate this case. Otherwise, you wouldn't be able to select
-    // those elements from the array (ie: $form['addtl_dbxrefs']['dbxref_table'][9999]['']
-    // doesn't work as expected whereas $form['addtl_dbxrefs']['dbxref_table'][9999][NONE]
-    // is much better)
-    $version = (!empty($dbxref->version)) ? $dbxref->version : 'NONE';
-
-    $form['addtl_dbxrefs']['dbxref_table'][$dbxref->db_id] = array(
-      '#type' => 'markup',
-      '#value' => ''
-    );
-
-    $form['addtl_dbxrefs']['dbxref_table'][$dbxref->db_id][$version] = array(
-      '#type' => 'markup',
-      '#value' => ''
-    );
-
-    $form['addtl_dbxrefs']['dbxref_table'][$dbxref->db_id][$version]['db_id'] = array(
-      '#type' => 'hidden',
-      '#value' => $dbxref->db_id
-    );
-
-    $form['addtl_dbxrefs']['dbxref_table'][$dbxref->db_id][$version]['accession'] = array(
-      '#type' => 'hidden',
-      '#value' => $dbxref->accession
-    );
-
-    $form['addtl_dbxrefs']['dbxref_table'][$dbxref->db_id][$version]['dbxref_id'] = array(
-      '#type' => 'hidden',
-      '#value' => $dbxref->dbxref_id
-    );
-
-    $form['addtl_dbxrefs']['dbxref_table'][$dbxref->db_id][$version]['db'] = array(
-      '#type' => 'markup',
-      '#markup' => $dbxref->db_name
-    );
-
-    $form['addtl_dbxrefs']['dbxref_table'][$dbxref->db_id][$version]['dbxref_version'] = array(
-      '#type' => 'markup',
-      '#markup' => $dbxref->version
-    );
-
-    $form['addtl_dbxrefs']['dbxref_table'][$dbxref->db_id][$version]['dbxref_accession'] = array(
-      '#type' => 'markup',
-      '#markup' => $dbxref->accession
-    );
-    // remove button
-    $form['addtl_dbxrefs']['dbxref_table'][$dbxref->db_id][$version]['dbxref_action'] = array(
-      '#type' => 'submit',
-      '#value' => t('Remove'),
-      '#name' => "dbxref_remove-".$dbxref->db_id.'-'.$version,
-      '#ajax' => array(
-        'callback' => "tripal_core_additional_dbxrefs_form_ajax_update",
-        'wrapper' => 'tripal-generic-edit-addtl_dbxrefs-table',
-        'effect'   => 'fade',
-        'method'   => 'replace',
-        'prevent'  => 'click'
-      ),
-      // When this button is clicked, the form will be validated and submitted.
-      // Therefore, we set custom submit and validate functions to override the
-      // default node form submit.  In the validate function we validate only the
-      // additional dbxref fields and in the submit we remove the indicated dbxref
-      // from the chado_additional_dbxrefs array. In order to keep validate errors
-      // from the node form validate and Drupal required errors for non-dbxref fields
-      // preventing the user from removing dbxrefs we set the #limit_validation_errors below
-      '#validate' => array('tripal_core_additional_dbxrefs_form_remove_button_validate'),
-      '#submit' => array('tripal_core_additional_dbxrefs_form_remove_button_submit'),
-      // Limit the validation of the form upon clicking this button to the dbxref_table tree
-      // No other fields will be validated (ie: no fields from the main form or any other api
-      // added form).
-      '#limit_validation_errors' => array(
-        array('dbxref_table')  // Validate all fields within $form_state['values']['dbxref_table']
-      )
-    );
-  }
-
-  // Form elements for adding a new dbxref
-  //---------------------------------------------
-  $form['addtl_dbxrefs']['dbxref_table']['new'] = array(
-    '#type' => 'markup',
-    '#prefix' => '<span class="addtl-dbxrefs-add-new-dbxref">',
-    '#suffix' => '</span>'
-  );
-
-  // add in the existing databases
-  $db_options = array(0 => 'Select a Database');
-  $select = tripal_core_chado_select('db', array('db_id','name'), array(), array('order_by' => array('name' => 'ASC')));
-  foreach($select as $db) {
-    $db_options[$db->db_id] = $db->name;
-  }
-  $form['addtl_dbxrefs']['dbxref_table']['new']['db'] = array(
-    '#type' => 'select',
-    '#options' => $db_options,
-  );
-
-  $form['addtl_dbxrefs']['dbxref_table']['new']['dbxref_accession'] = array(
-    '#type' => 'textfield',
-  );
-
-  $form['addtl_dbxrefs']['dbxref_table']['new']['dbxref_version'] = array(
-    '#type' => 'textfield',
-  );
-
-  // add button
-  $form['addtl_dbxrefs']['dbxref_table']['new']['dbxref_action'] = array(
-    '#type' => 'submit',
-    '#value' => t('Add'),
-    '#name' => "dbxref-add",
-    '#ajax' => array(
-      'callback' => "tripal_core_additional_dbxrefs_form_ajax_update",
-      'wrapper' => 'tripal-generic-edit-addtl_dbxrefs-table',
-      'effect'   => 'fade',
-      'method'   => 'replace',
-      'prevent'  => 'click'
-    ),
-    // When this button is clicked, the form will be validated and submitted.
-    // Therefore, we set custom submit and validate functions to override the
-    // default node form submit.  In the validate function we validate only the
-    // additional dbxref fields and in the submit we add them to the chado_additional_dbxrefs
-    // array. In order to keep validate errors from the node form validate and Drupal
-    // required errors for non-dbxref fields preventing the user from adding dbxrefs we
-    // set the #limit_validation_errors below
-    '#validate' => array('tripal_core_additional_dbxrefs_form_add_button_validate'),
-    '#submit' => array('tripal_core_additional_dbxrefs_form_add_button_submit'),
-    // Limit the validation of the form upon clicking this button to the dbxref_table tree
-    // No other fields will be validated (ie: no fields from the main form or any other api
-    // added form).
-    '#limit_validation_errors' => array(
-      array('dbxref_table')  // Validate all fields within $form_state['values']['dbxref_table']
-    )
-  );
-
-}
-
-/**
- * Validate the user input for creating a new dbxref
- * Called by the add button in tripal_core_additional_dbxrefs_form
- */
-function tripal_core_additional_dbxrefs_form_add_button_validate($form, &$form_state) {
-
-  // Ensure the db_id is supplied & Valid
-  $db = tripal_core_chado_select(
-    'db',
-    array('db_id', 'name'),
-    array('db_id' => $form_state['values']['dbxref_table']['new']['db'])
-  );
-  if (!isset($db[0])) {
-    form_set_error('dbxref_table][new][db', 'Please select a database before attempting to add a new database reference.');
-  }
-  else {
-    $form_state['values']['dbxref_table']['new']['db_name'] = $db[0]->name;
-  }
-
-  // Ensure accession is supplied
-  if (empty($form_state['values']['dbxref_table']['new']['dbxref_accession'])) {
-    form_set_error('dbxref_table][new][dbxref_accession','You must enter the accession before attempting to add a new database reference.');
-  }
-}
-
-/**
- * Called by the add button in tripal_core_additional_dbxrefs_form
- *
- * Create an array of additional dbxrefs in the form state. This array will then be
- * used to rebuild the form in subsequent builds
- */
-function tripal_core_additional_dbxrefs_form_add_button_submit(&$form, &$form_state) {
-
-  // if the chado_additional_dbxrefs array is not set then this is the first time modifying the
-  // dbxref table. this means we need to include all the dbxrefs from the db
-  if (!isset($form_state['chado_additional_dbxrefs'])) {
-    tripal_core_additional_dbxrefs_form_create_dbxref_formstate_array($form, $form_state);
-  }
-
-  // get details for the new dbxref
-  $dbxref = array(
-    'db_id' => $form_state['values']['dbxref_table']['new']['db'],
-    'db_name' => $form_state['values']['dbxref_table']['new']['db_name'],
-    'dbxref_id' => NULL,
-    'version' => $form_state['values']['dbxref_table']['new']['dbxref_version'],
-    'accession' => $form_state['values']['dbxref_table']['new']['dbxref_accession'],
-  );
-  $version = (!empty($dbxref['version'])) ? $dbxref['version'] : 'NONE';
-  $key = $dbxref['db_id'] . '-' . $version;
-  $form_state['chado_additional_dbxrefs'][$key] = (object) $dbxref;
-
-  $form_state['rebuild'] = TRUE;
-}
-
-/**
- * There is no user input for the remove buttons so there is no need to validate
- * However, both a submit & validate need to be specified so this is just a placeholder
- *
- * Called by the many remove buttons in tripal_core_additional_dbxrefs_form
- */
-function tripal_core_additional_dbxrefs_form_remove_button_validate($form, $form_state) {
-  // No Validation needed for remove
-}
-
-/**
- * Remove the correct dbxref from the form
- * Called by the many remove buttons in tripal_core_additional_dbxrefs_form
- */
-function tripal_core_additional_dbxrefs_form_remove_button_submit(&$form, &$form_state) {
-
-  // if the chado_additional_dbxrefs array is not set then this is the first time modifying the
-  // dbxref table. this means we need to include all the dbxrefs from the db
-  if (!isset($form_state['chado_additional_dbxrefs'])) {
-    tripal_core_additional_dbxrefs_form_create_dbxref_formstate_array($form, $form_state);
-  }
-
-  // remove the specified dbxref from the form dbxref table
-  if(preg_match('/dbxref_remove-([^-]+-[^-]+)/',$form_state['triggering_element']['#name'],$match)) {
-    $key = $match[1];
-    if (array_key_exists($key, $form_state['chado_additional_dbxrefs'])) {
-      unset($form_state['chado_additional_dbxrefs'][$key]);
-    }
-  }
-
-  $form_state['rebuild'] = TRUE;
-}
-
-/**
- * Ajax function which returns the section of the form to be re-rendered
- */
-function tripal_core_additional_dbxrefs_form_ajax_update($form, $form_state) {
-  return $form['addtl_dbxrefs']['dbxref_table'];
-}
-
-/**
- * Creates an array in form_state containing the existing addtl_dbxrefs. This array is
- * then modified by the add/remove buttons and used as a source for rebuilding the form.
- * This function get's called at each button (add and remove) button submits the first
- * time one of the button's is clicked to instantiates the $form_state['chado_additional_dbxrefs'] array
- *
- * $form_state['chado_additional_dbxrefs'] = array(
- *   '[db_id]-[version]' => array(
- *     'db_id' => [the db.db_id value]
- *     'db_name' => [the db.name value]
- *     'dbxref_id' => [the dbxref.dbxref_id value, or NULL if it doesn't yet exists],
- *     'version' => [the dbxref.version value],
- *     'accession' => [the dbxref.accession value],
- *   ),
- * );
- */
-function tripal_core_additional_dbxrefs_form_create_dbxref_formstate_array($form, &$form_state) {
-
-  $form_state['chado_additional_dbxrefs'] = array();
-
-  foreach (element_children($form['addtl_dbxrefs']['dbxref_table']) as $db_id) {
-    if ($db_id != 'new') {
-      foreach (element_children($form['addtl_dbxrefs']['dbxref_table'][$db_id]) as $version) {
-          $element = $form['addtl_dbxrefs']['dbxref_table'][$db_id][$version];
-          $dbxref = array(
-            'db_id' => $element['db_id']['#value'],
-            'db_name' => $element['db']['#markup'],
-            'dbxref_id' => $element['dbxref_id']['#value'],
-            'version' => $element['dbxref_version']['#markup'],
-            'accession' => $element['dbxref_accession']['#markup'],
-          );
-          $version = (!empty($dbxref['version'])) ? $dbxref['version'] : 'NONE';
-          $key = $dbxref['db_id'] . '-' . $version;
-          $form_state['chado_additional_dbxrefs'][$key] = (object) $dbxref;
-      }
-    }
-  }
-}
-
-/**
- * Function to theme the add/remove dbxrefs form into a table
- */
-function theme_tripal_core_additional_dbxrefs_form_table($variables) {
-  $element = $variables['element'];
-
-  $header = array(
-    'db' => t('Database'),
-    'dbxref_accession' => t('Accession'),
-    'dbxref_version' => t('Version'),
-    'dbxref_action' => t('Actions'),
-  );
-
-  $rows = array();
-  foreach (element_children($element) as $db_id) {
-    if ($db_id == 'new') {
-      $row = array();
-
-        $row['data'] = array();
-        foreach ($header as $fieldname => $title) {
-          $row['data'][] = drupal_render($element[$db_id][$fieldname]);
-        }
-        $rows[] = $row;
-    }
-    else {
-      foreach (element_children($element[$db_id]) as $version) {
-        $row = array();
-
-        $row['data'] = array();
-        foreach ($header as $fieldname => $title) {
-          $row['data'][] = drupal_render($element[$db_id][$version][$fieldname]);
-        }
-        $rows[] = $row;
-      }
-    }
-  }
-
-  return theme('table', array(
-    'header' => $header,
-    'rows' => $rows
-  ));
-}
-
-/**
- * This function is used in a hook_insert, hook_update for a node form
- * when the additional_dbxrefs form has been added to the form.  It retrieves all of the dbxrefs
- * and returns them in an array of the format:
- *
- *   $dbxefs[<db_id>][<version>][<dbxref_id>] = <accession>
- *
- * This array can then be used for inserting or updating dbxrefs using the API call
- * tripal_hook_insert_dbxref()
- *
- * @param $node
- *
- * @return
- *   A dbxref array
- *
- * @ingroup tripal_databaserefernce_api
- */
-function tripal_core_additional_dbxrefs_form_retreive($node) {
-  $dbxrefs = array();
-
-  if (isset($node->dbxref_table)) {
-    foreach ($node->dbxref_table as $db_id => $elements) {
-      if ($db_id != 'new') {
-        foreach ($elements as $version => $dbxref) {
-          $dbxref_id = (!empty($dbxref['dbxref_id'])) ? $dbxref['dbxref_id'] : 'NONE';
-          $dbxrefs[$db_id][$version][$dbxref_id] = $dbxref['accession'];
-        }
-      }
-    }
-  }
-
-  return $dbxrefs;
-}
-
-/**
- * This function is used in hook_insert or hook_update and handles inserting of any new
- * dbxrefs and creation of links between those dbxrefs and node content
- *
- * @param $node
- *    The node passed into hook_insert & hook_update
- * @param $linking_table
- *    The name of the _dbxref linking table (ie: feature_dbxref)
- * @param $foreignkey_name
- *    The name of the foreign key used to link to the node content (ie: feature_id)
- * @param $foreignkey_value
- *    The value of the foreign key (ie: 445, if there exists a feature where feature_id=445)
- */
-function tripal_core_additional_dbxrefs_form_update_dbxrefs($node, $linking_table, $foreignkey_name, $foreignkey_value) {
-
-  if (isset($node->dbxref_table) AND ($foreignkey_value > 0)) {
-    // First remove existing dbxref links
-    tripal_core_chado_delete($linking_table, array($foreignkey_name => $foreignkey_value));
-
-    // Add back in dbxref links and insert dbxrefs as needed
-    $dbxrefs = tripal_core_additional_dbxrefs_form_retreive($node);
-    foreach ($dbxrefs as $db_id => $versions) {
-      foreach ($versions as $version => $elements) {
-        foreach ($elements as $dbxref_id => $accession) {
-          // If there is no dbxref then we have to create that first
-          if ($dbxref_id == 'NONE') {
-            $version = ($version == 'NONE') ? '' : $version;
-            $success = tripal_db_add_dbxref(
-              $db_id,
-              $accession,
-              $version,
-              NULL
-            );
-            if ($success) {
-              $dbxref_id = $success->dbxref_id;
-            }
-            else {
-              $dbxref_id = FALSE;
-            }
-          }
-
-          // add _dbxref linker
-          if ($dbxref_id) {
-            $success_link = tripal_db_add_dbxref_link(
-              $linking_table,
-              $dbxref_id,
-              $foreignkey_name,
-              $foreignkey_value
-            );
-          }
-        }
-      }
-    }
-  }
-}

+ 0 - 251
tripal_core/api/tripal_core.general_chado.api.inc

@@ -1,251 +0,0 @@
-<?php
-
-require_once "tripal_core.schema_v1.2.api.inc";
-require_once "tripal_core.schema_v1.11.api.inc";
-
-// Globals used by Tripals Error catching functions
-// Should match those defined by watchdog
-define('TRIPAL_CRITICAL',2);
-define('TRIPAL_ERROR',3);
-define('TRIPAL_WARNING',4);
-define('TRIPAL_NOTICE',5);
-define('TRIPAL_INFO',6);
-define('TRIPAL_DEBUG',7);
-
-
-/**
- * This function is used to set the global Chado variables
- */
-function tripal_core_set_globals() {
-  // these global variables are meant to be accessed by all Tripal
-  // modules to find the chado version installed and if Chado is local.
-  // these variables are stored as globals rather than using the drupal_set_variable
-  // functions because the Drupal functions make databaes queries and for long
-  // running loaders we don't want those queries repeatedly.
-  $GLOBALS["chado_is_installed"]  = tripal_core_is_chado_installed();
-  if ($GLOBALS["chado_is_installed"]) {
-    $GLOBALS["chado_is_local"]      = tripal_core_is_chado_local();
-    $GLOBALS["chado_version"]       = tripal_core_get_chado_version();
-    $GLOBALS["exact_chado_version"] = tripal_core_get_chado_version(TRUE);
-  }
-}
-
-/**
- * Provide better error notice for Tripal
- * @param $type
- *   The catagory to which this message belongs. Can be any string, but the general
- *   practice is to use the name of the module.
- * @param $message
- *   The message to store in the log. Keep $message translatable by not concatenating
- *   dynamic values into it! Variables in the message should be added by using placeholder
- *   strings alongside the variables argument to declare the value of the placeholders.
- *   See t() for documentation on how $message and $variables interact.
- * @param $variables
- *   Array of variables to replace in the message on display or NULL if message is
- *   already translated or not possible to translate.
- * @param $severity
- *   The severity of the message; one of the following values:
- *     - TRIPAL_CRITICAL: Critical conditions.
- *     - TRIPAL_ERROR: Error conditions.
- *     - TRIPAL_WARNING: Warning conditions.
- *     - TRIPAL_NOTICE: (default) Normal but significant conditions.
- *     - TRIPAL_INFO: Informational messages.
- *     - TRIPAL_DEBUG: Debug-level messages.
- * @param $options
- *   An array of options. Some available options include:
- *     - print: prints the error message to the screen. Useful when display is the command-line
- */
-function tripal_core_report_error($type, $severity, $message, $variables = array(), $options = array()) {
-
-  // Get human-readable severity string
-  $severity_string = '';
-  switch ($severity) {
-    case TRIPAL_CRITICAL:
-      $severity_string = 'CRITICAL';
-      break;
-    case TRIPAL_ERROR:
-      $severity_string = 'ERROR';
-      break;
-    case TRIPAL_WARNING:
-      $severity_string = 'WARNING';
-      break;
-    case TRIPAL_NOTICE:
-      $severity_string = 'NOTICE';
-      break;
-    case TRIPAL_INFO:
-      $severity_string = 'INFO';
-      break;
-    case TRIPAL_DEBUG:
-      $severity_string = 'DEBUG';
-      break;
-  }
-
-  // Send to watchdog
-  try {
-    watchdog($type, $message, $variables, $severity);
-  }
-  catch (Exception $e) {
-    print "CRITICAL (TRIPAL_CORE): Unable to register error message with watchdog";
-    $options['print'] = TRUE;
-  }
-
-  // If print option supplied then print directly to the screen
-  if (isset($options['print'])) {
-    if (sizeof($variables) > 0) {
-      $message = str_replace(array_keys($variables), $variables, $message);
-    }
-    print $severity_string . ' (' . strtoupper($type) . '):' . $message . "\n";
-  }
-}
-
-/**
- * @file
- * The Tripal Core API
- *
- * This file provides the API needed for all other Tripal and Tripal dependent
- * modules.
- *
- *
- * @defgroup tripal_chado_api Chado API
- * @ingroup tripal_core_api
- * @{
- * Provides an application programming interface (API) to manage data withing the Chado database.
- * This includes functions for selecting, inserting, updating and deleting records
- * in Chado tables.  The functions will ensure proper integrity contraints are met
- * for inserts and updates.
- *
- * Also, a set of functions is provided for creating template variables.  First,
- * is the tripal_core_generate_chado_vars which is used to select one ore more
- * records from a table and return an array with foreign key relationships fully
- * populated.  For example, if selecting a feature, the organism_id and type_id
- * would be present in the returned array as a nested array with their respective
- * foreign keys also nested.  The only fields that are not included are text
- * fields (which may be very large) or many-to-many foreign key relationships.
- * However, these fields and relationships can be expanded using the
- * tripal_core_expand_chado_vars.
- *
- * When a row from a chado table is selected using these two functions, it provides
- * a way for users who want to cutomize Drupal template files to access all data
- * associate with a specific record.
- *
- * Finally, the property tables in Chado generally follow the same format.  Therefore
- * there is a set of functions for inserting, updating and deleting properties for
- * any table.  This provides quick lookup of properties (provided the CV term is
- * known).
- *
- * @}
- *
- */
-
-/**
- * Get chado id for a node. E.g, if you want to get 'analysis_id' from the
- * 'analysis' table for a synced 'chado_analysis' node, (the same for
- * organisms and features):
- * $analysis_id = chado_get_id_for_node ('analysis', $node->nid)
- * $organism_id = chado_get_id_for_node ('organism', $node->nid)
- * $feature_id  = chado_get_id_for_node ('feature', $node->nid)
- *
- * @param $table
- * @param $nid
- *
- * @ingroup tripal_chado_api
- */
-function chado_get_id_for_node($table, $nid) {
-  $sql = "SELECT " . $table . "_id as id FROM {chado_$table} WHERE nid = :nid";
-  return db_query($sql, array(':nid' => $nid))->fetchField();
-}
-
-/**
- *  Get node id for a chado feature/organism/analysis. E.g, if you want to
- *  get the node id for an analysis, use:
- *  $nid = chado_get_node_id ('analysis', $analysis_id)
- *  Likewise,
- *  $nid = chado_get_node_id ('organism', $organism_id)
- *  $nid = chado_get_node_id ('feature', $feature_id)
- *
- *  @ingroup tripal_chado_api
- */
-function chado_get_node_id($table, $id) {
-  $sql = "SELECT nid FROM {chado_$table} WHERE " . $table . "_id = :" . $table . "_id";
-  return db_query($sql, array(":" . $table . "_id" => $id))->fetchField();
-}
-
-/**
- * Set the Tripal Database
- *
- * The tripal_db_set_active function is used to prevent namespace collisions
- * when chado and drupal are installed in the same database but in different
- * schemas.  It is also used for backwards compatibility with older versions
- * of tripal or in cases where chado is located outside of the Drupal database.
- * or when using Drupal functions such as db_table_exists()
- *
- * @ingroup tripal_chado_api
- */
-function tripal_db_set_active($dbname  = 'default') {
-  global $databases, $active_db;
-
-  if ($dbname ) {
-    if ($dbname == 'chado') {
-      db_query('set search_path to chado,public');
-      return 'default';
-    }
-    else {
-      db_query('set search_path to public');
-      return 'chado';
-    }
-  }
-  // if the 'chado' database is in the $db_url variable then chado is
-  // not in the same Drupal database, so we don't need to set any
-  // search_path and can just change the database
-  elseif (array_key_exists($dbname, $databases)) {
-    return db_set_active($dbname);
-  }
-}
-
-/**
- * Get max rank for a given set of criteria
- * This function was developed with the many property tables in chado in mind but will
- * work for any table with a rank
- *
- * @params tablename: the name of the chado table you want to select the max rank from
- *    this table must contain a rank column of type integer
- * @params where_options: array(
- *                          <column_name> => array(
- *                            'type' => <type of column: INT/STRING>,
- *                            'value' => <the value you want to filter on>,
- *                            'exact' => <if TRUE use =; if FALSE use ~>,
- *                          )
- *        )
- *     where options should include the id and type for that table to correctly
- *     group a set of records together where the only difference are the value and rank
- * @return the maximum rank
- *
- */
-function tripal_core_get_max_chado_rank($tablename, $where_options) {
-
-  $where_clauses = array();
-  $where_args = array();
-
-  //generate the where clause from supplied options
-  // the key is the column name
-  $i = 0;
-  $sql = "
-    SELECT max(rank) as max_rank, count(rank) as count
-    FROM {".$tablename."}
-    WHERE
-  ";
-  foreach ($where_options as $key => $value) {
-    $where_clauses[] = "$key = :$key";
-    $where_args[":$key"] = $value;
-  }
-  $sql .= implode($where_clauses, ' AND ');
-
-  $result = chado_query($sql, $where_args)->fetchObject();
-  if ($result->count > 0) {
-    return $result->max_rank;
-  }
-  else {
-    return -1;
-  }
-
-}

+ 0 - 1344
tripal_core/api/tripal_core.generic_query.api.inc

@@ -1,1344 +0,0 @@
-<?php
-
-/**
- * @file
- * Provides an API for querying of chado
- */
-
-/**
- * Provides a generic routine for inserting into any Chado table
- *
- * Use this function to insert a record into any Chado table.  The first
- * argument specifies the table for inserting and the second is an array
- * of values to be inserted.  The array is mutli-dimensional such that
- * foreign key lookup values can be specified.
- *
- * @param $table
- *  The name of the chado table for inserting
- * @param $values
- *  An associative array containing the values for inserting.
- * @param $options
- *  An array of options such as:
- *  - skip_validation: TRUE or FALSE. If TRUE will skip all the validation steps and
- *     just try to insert as is. This is much faster but results in unhandled
- *     non user-friendly errors if the insert fails.
- *  - return_record: by default, the function will return the record but with
- *     the primary keys added after insertion.  To simply return TRUE on success
- *     set this option to FALSE
- *
- * @return
- *  On success this function returns the inserted record with the new primary keys
- *  added to the returned array. On failure, it returns FALSE.
- *
- * Example usage:
- * @code
- *   $values =  array(
- *     'organism_id' => array(
- *         'genus' => 'Citrus',
- *         'species' => 'sinensis',
- *      ),
- *     'name' => 'orange1.1g000034m.g',
- *     'uniquename' => 'orange1.1g000034m.g',
- *     'type_id' => array (
- *         'cv_id' => array (
- *            'name' => 'sequence',
- *         ),
- *         'name' => 'gene',
- *         'is_obsolete' => 0
- *      ),
- *   );
- *   $result = tripal_core_chado_insert('feature',$values);
- * @endcode
- * The above code inserts a record into the feature table.  The $values array is
- * nested such that the organism is selected by way of the organism_id foreign
- * key constraint by specifying the genus and species.  The cvterm is also
- * specified using its foreign key and the cv_id for the cvterm is nested as
- * well.
- *
- * @ingroup tripal_chado_api
- */
-function tripal_core_chado_insert($table, $values, $options = array()) {
-
-  $print_errors = (isset($options['print_errors'])) ? $options['print_errors'] : FALSE;
-
-  if (!is_array($values)) {
-    tripal_core_report_error(
-      'tripal_core',
-      TRIPAL_ERROR,
-      'Cannot pass non array as values for inserting.',
-      array(),
-      array('print' => $print_errors)
-    );
-    return FALSE;
-  }
-  if (count($values)==0) {
-    tripal_core_report_error(
-      'tripal_core',
-      TRIPAL_ERROR,
-      'Cannot pass an empty array as values for inserting.',
-      array(),
-      array('print' => $print_errors)
-    );
-    return FALSE;
-  }
-
-  // set defaults for options. If we don't set defaults then
-  // we get memory leaks when we try to access the elements
-  if (!is_array($options)) {
-    $options = array();
-  }
-
-  if (!array_key_exists('skip_validation', $options)) {
-    $options['skip_validation'] = FALSE;
-  }
-  if (!array_key_exists('return_record', $options)) {
-    $options['return_record'] = TRUE;
-  }
-
-  $insert_values = array();
-
-  if (array_key_exists('skip_validation', $options)) {
-    $validate = !$options['skip_validation'];
-  }
-  else {
-    $validate = TRUE;
-  }
-
-  // get the table description
-  $table_desc = tripal_core_get_chado_table_schema($table);
-  if (empty($table_desc)) {
-    tripal_core_report_error('tripal_core', TRIPAL_WARNING,
-      'tripal_core_chado_insert; There is no table description for !table_name',
-      array('!table_name' => $table), array('print' => $print_errors)
-    );
-  }
-
-  // iterate through the values array and create a new 'insert_values' array
-  // that has all the values needed for insert with all foreign relationsihps
-  // resolved.
-  foreach ($values as $field => $value) {
-    // make sure the field is in the table description. If not then return an error
-    // message
-    if (!array_key_exists($field, $table_desc['fields'])) {
-      tripal_core_report_error(
-        'tripal_core',
-        TRIPAL_ERROR,
-        "tripal_core_chado_insert; The field '%field' does not exist " .
-          "for the table '%table'.  Cannot perform insert. Values: %array",
-        array('%field' => $field, '%table' => $table, '%array' => print_r($values, 1)),
-        array('print' => $print_errors)
-      );
-      return FALSE;
-    }
-
-    if (is_array($value)) {
-      // select the value from the foreign key relationship for this value
-      $results = tripal_core_chado_get_foreign_key($table_desc, $field, $value);
-
-      if (sizeof($results) > 1) {
-        tripal_core_report_error(
-          'tripal_core',
-          TRIPAL_ERROR,
-          'tripal_core_chado_insert: Too many records match the criteria supplied for !foreign_key foreign key constraint (!criteria)',
-          array('!foreign_key' => $field, '!criteria' => print_r($value, TRUE)),
-          array('print' => $print_errors)
-        );
-      }
-      elseif (sizeof($results) < 1) {
-        tripal_core_report_error(
-          'tripal_core',
-          TRIPAL_DEBUG,
-          'tripal_core_chado_insert: no record matches criteria supplied for !foreign_key foreign key constraint (!criteria)',
-          array('!foreign_key' => $field, '!criteria' => print_r($value, TRUE)),
-          array('print' => $print_errors)
-        );
-      }
-      else {
-        $insert_values[$field] = $results[0];
-      }
-    }
-    else {
-      $insert_values[$field] = $value;
-    }
-  }
-
-  if ($validate) {
-
-    // check for violation of any unique constraints
-    $ukeys = array();
-    if (array_key_exists('unique keys', $table_desc)) {
-      $ukeys = $table_desc['unique keys'];
-    }
-    $ukselect_cols = array();
-    $ukselect_vals = array();
-    if ($ukeys) {
-      foreach ($ukeys as $name => $fields) {
-        foreach ($fields as $index => $field) {
-          // build the arrays for performing a select that will check the contraint
-          $ukselect_cols[] = $field;
-          if (!array_key_exists($field, $insert_values)) {
-            if (array_key_exists('default', $table_desc['fields'][$field])) {
-              $ukselect_vals[$field] = $table_desc['fields'][$field]['default'];
-            }
-          }
-          else {
-            $ukselect_vals[$field] = $insert_values[$field];
-          }
-        }
-        // now check the constraint
-        if (tripal_core_chado_select($table, $ukselect_cols, $ukselect_vals)) {
-          tripal_core_report_error('tripal_core', TRIPAL_ERROR,
-            "tripal_core_chado_insert; Cannot insert duplicate record into $table table: !values",
-            array('!values' => print_r($values, TRUE)), array('print' => $print_errors)
-          );
-          return FALSE;
-        }
-      }
-    }
-
-    // if trying to insert a field that is the primary key, make sure it also is unique
-    if (array_key_exists('primary key', $table_desc)) {
-      $pkey = $table_desc['primary key'][0];
-      if (array_key_exists($pkey, $insert_values)) {
-        $coptions = array();
-        if (tripal_core_chado_select($table, array($pkey), array($pkey => $insert_values[$pkey]), $coptions)) {
-          tripal_core_report_error('tripal_core', TRIPAL_ERROR,
-            'tripal_core_chado_insert; Cannot insert duplicate primary key into !table table: !values',
-            array('!table' => $table, '!values' => print_r($values, TRUE)),
-            array('print' => $print_errors)
-          );
-          return FALSE;
-        }
-      }
-    }
-
-    // make sure required fields have a value
-    if (!is_array($table_desc['fields'])) {
-      $table_desc['fields'] = array();
-      tripal_core_report_error(
-        'tripal_core',
-        TRIPAL_WARNING,
-        "tripal_core_chado_insert; %table missing fields: \n %schema",
-        array('%table' => $table, '%schema' => print_r($table_desc, 1)),
-        array('print' => $print_errors)
-      );
-    }
-    foreach ($table_desc['fields'] as $field => $def) {
-      // a field is considered missing if it cannot be NULL and there is no default
-      // value for it or it is of type 'serial'
-      if (array_key_exists('NOT NULL', $def) and
-          !array_key_exists($field, $insert_values) and
-          !array_key_exists('default', $def) and
-          strcmp($def['type'], serial) != 0) {
-        tripal_core_report_error(
-          'tripal_core',
-          TRIPAL_ERROR,
-          "tripal_core_chado_insert; Field %table.%field cannot be NULL: %values",
-          array('%table' => $table, '%field' => $field, '%values' => print_r($values, 1)),
-          array('print' => $print_errors)
-        );
-        return FALSE;
-      }
-    }
-  } //end of validation
-
-  // Now build the insert SQL statement
-  $ifields = array();       // contains the names of the fields
-  $itypes  = array();       // contains placeholders for the sql query
-  $ivalues = array();       // contains the values of the fields
-  $i = 1;
-  foreach ($insert_values as $field => $value) {
-    $ifields[] = $field;
-    $ivalues[":$field"] = $value;
-    $i++;
-    if (strcmp($value, '__NULL__')==0) {
-      $itypes[] = "NULL";
-    }
-    else {
-      $itypes[] = ":$field";
-    }
-  }
-
-  // create the SQL
-  $sql = 'INSERT INTO {' . $table . '} (' . implode(", ", $ifields) . ") VALUES (" . implode(", ", $itypes) . ")";
-  $result = chado_query($sql, $ivalues);
-
-  // if we have a result then add primary keys to return array
-  if ($options['return_record'] == TRUE and $result) {
-    if (array_key_exists('primary key', $table_desc) and is_array($table_desc['primary key'])) {
-      foreach ($table_desc['primary key'] as $field) {
-        $sql = "SELECT CURRVAL('{" . $table . "_" . $field . "_seq}')";
-        $results = chado_query($sql);
-        $value = $results->fetchField();
-        if (!$value) {
-          tripal_core_report_error(
-            'tripal_core',
-            TRIPAL_ERROR,
-            "tripal_core_chado_insert; not able to retrieve primary key after insert: %sql",
-            array('%sql' => $sql),
-            array('print' => $print_errors)
-          );
-          return FALSE;
-        }
-        $values[$field] = $value;
-      }
-    }
-    return $values;
-  }
-  elseif ($options['return_record'] == FALSE and $result) {
-    return TRUE;
-  }
-  else {
-    tripal_core_report_error(
-      'tripal_core',
-      TRIPAL_ERROR,
-      'tripal_core_chado_insert; Cannot insert record into "%table": %values',
-      array('%table' => $table, '%values' => print_r($values, 1)),
-      array('print' => $print_errors)
-    );
-    return FALSE;
-  }
-
-  return FALSE;
-
-}
-
-/**
- * Provides a generic routine for updating into any Chado table
- *
- * Use this function to update a record in any Chado table.  The first
- * argument specifies the table for inserting, the second is an array
- * of values to matched for locating the record for updating, and the third
- * argument give the values to update.  The arrays are mutli-dimensional such
- * that foreign key lookup values can be specified.
- *
- * @param $table
- *  The name of the chado table for inserting
- * @param $match
- *  An associative array containing the values for locating a record to update.
- * @param $values
- *  An associative array containing the values for updating.
- * @param $options
- *  An array of options such as:
- *  - return_record: by default, the function will return the TRUE if the record
- *     was succesfully updated.  However, set this option to TRUE to return the
- *     record that was updated.  The returned record will have the fields provided
- *     but the primary key (if available for the table) will be added to the record.
- * @return
- *  On success this function returns TRUE. On failure, it returns FALSE.
- *
- * Example usage:
- * @code
- $umatch = array(
-   'organism_id' => array(
-     'genus' => 'Citrus',
-     'species' => 'sinensis',
-   ),
-   'uniquename' => 'orange1.1g000034m.g7',
-   'type_id' => array (
-     'cv_id' => array (
-       'name' => 'sequence',
-     ),
-     'name' => 'gene',
-     'is_obsolete' => 0
-   ),
- );
- $uvalues = array(
-   'name' => 'orange1.1g000034m.g',
-   'type_id' => array (
-     'cv_id' => array (
-       'name' => 'sequence',
-     ),
-     'name' => 'mRNA',
-     'is_obsolete' => 0
-   ),
- );
- *   $result = tripal_core_chado_update('feature',$umatch,$uvalues);
- * @endcode
- * The above code species that a feature with a given uniquename, organism_id,
- * and type_id (the unique constraint for the feature table) will be updated.
- * The organism_id is specified as a nested array that uses the organism_id
- * foreign key constraint to lookup the specified values to find the exact
- * organism_id. The same nested struture is also used for specifying the
- * values to update.  The function will find the record that matches the
- * columns specified and update the record with the avlues in the $uvalues array.
- *
- * @ingroup tripal_chado_api
- */
-function tripal_core_chado_update($table, $match, $values, $options = NULL) {
-
-  $print_errors = (isset($options['print_errors'])) ? $options['print_errors'] : FALSE;
-
-  if (!is_array($values)) {
-    tripal_core_report_error(
-      'tripal_core',
-      TRIPAL_ERROR,
-      'Cannot pass non array as values for updating.',
-      array(),
-      array('print' => $print_errors)
-    );
-    return FALSE;
-  }
-  if (count($values)==0) {
-    tripal_core_report_error(
-      'tripal_core',
-      TRIPAL_ERROR,
-      'Cannot pass an empty array as values for updating.',
-      array(),
-      array('print' => $print_errors)
-    );
-    return FALSE;
-  }
-
-  if (!is_array($match)) {
-    tripal_core_report_error(
-      'tripal_core',
-      TRIPAL_ERROR,
-      'Cannot pass non array as values for matching.',
-      array(),
-      array('print' => $print_errors)
-    );
-    return FALSE;
-  }
-  if (count($match)==0) {
-    tripal_core_report_error(
-      'tripal_core',
-      TRIPAL_ERROR,
-      'Cannot pass an empty array as values for matching.',
-      array(),
-      array('print' => $print_errors)
-    );
-    return FALSE;
-  }
-
-  // set defaults for options. If we don't set defaults then
-  // we get memory leaks when we try to access the elements
-  if (!is_array($options)) {
-    $options = array();
-  }
-
-  if (!array_key_exists('return_record', $options)) {
-    $options['return_record'] = FALSE;
-  }
-
-  $update_values = array();   // contains the values to be updated
-  $update_matches = array();  // contains the values for the where clause
-
-
-  // get the table description
-  $table_desc = tripal_core_get_chado_table_schema($table);
-
-  // if the user wants us to return the record then we need to get the
-  // unique primary key if one exists.  That way we can add it to the
-  // values that get returned at the end of the function
-  $pkeys = array();
-  if ($options['return_record'] == TRUE) {
-    if (array_key_exists('primary key', $table_desc) and is_array($table_desc['primary key'])) {
-      $columns = array();
-      $stmt_suffix = '';
-      foreach ($table_desc['primary key'] as $field) {
-        $columns[] = $field;
-        $stmt_suffix .= substr($field, 0, 2);
-      }
-      $options2 = array();
-      $results = tripal_core_chado_select($table, $columns, $match, $options2);
-      if (count($results) > 0) {
-        foreach ($results as $index => $pkey) {
-          $pkeys[] = $pkey;
-        }
-      }
-    }
-  }
-
-  // get the values needed for matching in the SQL statement
-  foreach ($match as $field => $value) {
-    if (is_array($value)) {
-      $results = tripal_core_chado_get_foreign_key($table_desc, $field, $value);
-      if (sizeof($results) > 1) {
-        tripal_core_report_error('tripal_core', TRIPAL_ERROR,
-          'tripal_core_chado_update: When trying to find record to update, too many records match the criteria supplied for !foreign_key foreign key constraint (!criteria)',
-          array('!foreign_key' => $field, '!criteria' => print_r($value, TRUE)),
-          array('print' => $print_errors)
-        );
-      }
-      elseif (sizeof($results) < 1) {
-        tripal_core_report_error('tripal_core',TRIPAL_DEBUG,
-          'tripal_core_chado_update: When trying to find record to update, no record matches criteria supplied for !foreign_key foreign key constraint (!criteria)',
-          array('!foreign_key' => $field, '!criteria' => print_r($value, TRUE)),
-          array('print' => $print_errors)
-        );
-      }
-      else {
-        $update_matches[$field] = $results[0];
-      }
-    }
-    else {
-      $update_matches[$field] = $value;
-    }
-  }
-
-  // get the values used for updating
-  foreach ($values as $field => $value) {
-    if (is_array($value)) {
-      $foreign_options = array();
-      // select the value from the foreign key relationship for this value
-      $results = tripal_core_chado_get_foreign_key($table_desc, $field, $value, $foreign_options);
-      if (sizeof($results) > 1) {
-        tripal_core_report_error(
-          'tripal_core',
-          TRIPAL_ERROR,
-          'tripal_core_chado_update: When trying to find update values, too many records match the criteria supplied for !foreign_key foreign key constraint (!criteria)',
-          array('!foreign_key' => $field, '!criteria' => print_r($value, TRUE)),
-          array('print' => $print_errors)
-        );
-      }
-      elseif (sizeof($results) < 1) {
-        tripal_core_report_error(
-          'tripal_core',
-          TRIPAL_DEBUG,
-          'tripal_core_chado_update: When trying to find update values, no record matches criteria supplied for !foreign_key foreign key constraint (!criteria)',
-          array('!foreign_key' => $field, '!criteria' => print_r($value,TRUE)),
-          array('print' => $print_errors)
-        );
-      }
-      else {
-        $update_values[$field] = $results[0];
-      }
-    }
-    else {
-      $update_values[$field] = $value;
-    }
-  }
-
-  // now build the SQL statement
-  $sql  = 'UPDATE {' . $table . '} SET ';
-  $args = array();        // arguments passed to chado_query
-  foreach ($update_values as $field => $value) {
-    if (strcmp($value, '__NULL__') == 0) {
-      $sql .= " $field = NULL, ";
-    }
-    else {
-      $sql .= " $field = :$field, ";
-      $args[":$field"] = $value;
-    }
-  }
-  $sql = drupal_substr($sql, 0, -2);  // get rid of the trailing comma & space
-
-  $sql .= " WHERE ";
-  foreach ($update_matches as $field => $value) {
-    if (strcmp($value, '__NULL__')==0) {
-      $sql .= " $field = NULL AND ";
-    }
-    else {
-      $sql .= " $field = :$field AND ";
-      $args[":$field"] = $value;
-    }
-  }
-  $sql = drupal_substr($sql, 0, -4);  // get rid of the trailing 'AND'
-
-  $result = chado_query($sql, $args);
-
-  // if we have a result then add primary keys to return array
-  if ($options['return_record'] == TRUE and $result) {
-    // only if we have a single result do we want to add the primary keys to the values
-    // array.  If the update matched many records we can't add the pkeys
-
-    if (count($pkeys) == 1) {
-      foreach ($pkeys as $index => $pkey) {
-        foreach ($pkey as $field => $fvalue) {
-          $values[$field] = $fvalue;
-        }
-      }
-    }
-    return $values;
-  }
-  elseif ($options['return_record'] == FALSE and $result) {
-    return TRUE;
-  }
-  else {
-    tripal_core_report_error(
-      'tripal_core',
-      TRIPAL_ERROR,
-      "tripal_core_chado_update: Cannot update record in %table table.  \nMatch: %match \nValues: %values",
-      array('%table' => table, '%match' => print_r($match,TRUE), '%values' => print_r($values, 1)),
-      array('print' => $print_errors)
-    );
-    return FALSE;
-  }
-
-  return FALSE;
-}
-
-/**
- * Provides a generic function for deleting a record(s) from any chado table
- *
- * Use this function to delete a record(s) in any Chado table.  The first
- * argument specifies the table to delete from and the second is an array
- * of values to match for locating the record(s) to be deleted.  The arrays
- * are mutli-dimensional such that foreign key lookup values can be specified.
- *
- * @param $table
- *  The name of the chado table for inserting
- * @param $match
- *  An associative array containing the values for locating a record to update.
- * @param $options
- *  Currently there are no options
- * @return
- *   On success this function returns TRUE. On failure, it returns FALSE.
- *
- * Example usage:
- * @code
- $umatch = array(
-   'organism_id' => array(
-     'genus' => 'Citrus',
-     'species' => 'sinensis',
-   ),
-   'uniquename' => 'orange1.1g000034m.g7',
-   'type_id' => array (
-     'cv_id' => array (
-       'name' => 'sequence',
-     ),
-     'name' => 'gene',
-     'is_obsolete' => 0
-   ),
- );
- $uvalues = array(
-   'name' => 'orange1.1g000034m.g',
-   'type_id' => array (
-     'cv_id' => array (
-       'name' => 'sequence',
-     ),
-     'name' => 'mRNA',
-     'is_obsolete' => 0
-   ),
- );
- *   $result = tripal_core_chado_update('feature', $umatch, $uvalues);
- * @endcode
- * The above code species that a feature with a given uniquename, organism_id,
- * and type_id (the unique constraint for the feature table) will be deleted.
- * The organism_id is specified as a nested array that uses the organism_id
- * foreign key constraint to lookup the specified values to find the exact
- * organism_id. The same nested struture is also used for specifying the
- * values to update.  The function will find all records that match the
- * columns specified and delete them.
- *
- * @ingroup tripal_chado_api
- */
-function tripal_core_chado_delete($table, $match, $options = NULL) {
-
-  if (!is_array($match)) {
-    watchdog('tripal_core', 'Cannot pass non array as values for matching.', array(),
-      WATCHDOG_ERROR);
-    return FALSE;
-  }
-  if (count($match)==0) {
-    watchdog('tripal_core', 'Cannot pass an empty array as values for matching.', array(),
-      WATCHDOG_ERROR);
-    return FALSE;
-  }
-
-  // set defaults for options. If we don't set defaults then
-  // we get memory leaks when we try to access the elements
-  if (!is_array($options)) {
-    $options = array();
-  }
-
-  $delete_matches = array();  // contains the values for the where clause
-
-  // get the table description
-  $table_desc = tripal_core_get_chado_table_schema($table);
-  $fields = $table_desc['fields'];
-
-  // get the values needed for matching in the SQL statement
-  foreach ($match as $field => $value) {
-    if (is_array($value)) {
-      // if the user has specified an array of values to delete rather than
-      // FK relationships the keep those in our match
-      if (array_values($value) === $value) {
-        $delete_matches[$field] = $value;
-      }
-      else {
-        $results = tripal_core_chado_get_foreign_key($table_desc, $field, $value);
-        if (sizeof($results) > 1) {
-          watchdog('tripal_core', 'tripal_core_chado_delete: When trying to find record to delete, too many records match the criteria supplied for !foreign_key foreign key constraint (!criteria)', array('!foreign_key' => $field, '!criteria' => print_r($value, TRUE)), WATCHDOG_ERROR);
-        }
-        elseif (sizeof($results) < 1) {
-          //watchdog('tripal_core', 'tripal_core_chado_delete: When trying to find record to delete, no record matches criteria supplied for !foreign_key foreign key constraint (!criteria)', array('!foreign_key' => $field, '!criteria' => print_r($value,TRUE)), WATCHDOG_ERROR);
-        }
-        else {
-          $delete_matches[$field] = $results[0];
-        }
-      }
-    }
-    else {
-      $delete_matches[$field] = $value;
-    }
-  }
-
-  // now build the SQL statement
-  $sql = 'DELETE FROM {' . $table . '} WHERE ';
-  $args = array();
-  foreach ($delete_matches as $field => $value) {
-    // if we have an array values then this is an "IN" clasue.
-    // we cannot use prepared statements with these
-
-    if (count($value) > 1) {
-      $sql .= "$field IN (";
-      $index = 0;
-      foreach ($value as $v) {
-        $sql .= ":$field" . $index . ", ";
-        $args[":$field" . $index] = $v;
-        $index++;
-      }
-      $sql = drupal_substr($sql, 0, -2); // get rid of trailing ', '
-      $sql .= ") AND ";
-    }
-    else {
-      if (strcmp($value, '__NULL__') == 0) {
-        $sql .= " $field = NULL AND ";
-      }
-      else {
-        $sql .= " $field = :$field AND ";
-        $args[":$field"] = $value;
-      }
-    }
-  }
-  $sql = drupal_substr($sql, 0, -4);  // get rid of the trailing 'AND'
-
-  // finally perform the delete.  If successful, return the updated record
-  $result = chado_query($sql, $args);
-  if ($result) {
-    return TRUE;
-  }
-  else {
-    watchdog('tripal_core', "Cannot delete record in $table table.  Match:" . print_r($match, 1) . ". Values: " . print_r($values, 1), array(), 'WATCHDOG_ERROR');
-    return FALSE;
-  }
-  return FALSE;
-}
-
-/**
- * Provides a generic routine for selecting data from a Chado table
- *
- * Use this function to perform a simple select from any Chado table.
- *
- * @param $table
- *  The name of the chado table for inserting
- * @param $columns
- *  An array of column names
- * @param $values
- *  An associative array containing the values for filtering the results. In the
- *  case where multiple values for the same time are to be selected an additional
- *  entry for the field should appear for each value
- * @param $options
- *  An associative array of additional options where the key is the option
- *  and the value is the value of that option.
- *
- * Additional Options Include:
- *  - has_record
- *     Set this argument to 'TRUE' to have this function return a numeric
- *     value for the number of recrods rather than the array of records.  this
- *     can be useful in 'if' statements to check the presence of particula records.
- *  - return_sql
- *     Set this to 'TRUE' to have this function return an array where the first
- *     element is the sql that would have been run and the second is an array of
- *     arguments.
- *  - case_insensitive_columns
- *     An array of columns to do a case insensitive search on.
- *  - regex_columns
- *     An array of columns where the value passed in should be treated as a regular expression
- *  - order_by
- *     An associative array containing the column names of the table as keys
- *     and the type of sort (i.e. ASC, DESC) as the values.  The results in the
- *     query will be sorted by the key values in the direction listed by the value
- *  - is_duplicate: TRUE or FALSE.  Checks the values submited to see if
- *     they violate any of the unique constraints. If so, the record
- *     is returned, if not, FALSE is returned.
- *  - pager:  Use this option if it is desired to return only a subset of results
- *     so that they may be shown with in a Drupal-style pager. This should be
- *     an array with two keys: 'limit' and 'element'.  The value of 'limit'
- *     should specify the number of records to return and 'element' is a
- *     unique integer to differentiate between pagers when more than one
- *     appear on a page.  The 'element' should start with zero and increment by
- *     one for each pager.
- *
- * @return
- *  An array of results, FALSE if the query was not executed
- *  correctly, an empty array if no records were matched, or the number of records
- *  in the dataset if $has_record is set.
- *  If the option 'is_duplicate' is provided and the record is a duplicate it
- *  will return the duplicated record.  If the 'has_record' option is provided
- *  a value of TRUE will be returned if a record exists and FALSE will bee
- *  returned if there are not records.
- *
- * Example usage:
- * @code
- *   $columns = array('feature_id', 'name');
- *   $values =  array(
- *     'organism_id' => array(
- *         'genus' => 'Citrus',
- *         'species' => array('sinensis', 'clementina'),
- *      ),
- *     'uniquename' => 'orange1.1g000034m.g',
- *     'type_id' => array (
- *         'cv_id' => array (
- *            'name' => 'sequence',
- *         ),
- *         'name' => 'gene',
- *         'is_obsolete' => 0
- *      ),
- *   );
- *   $options = array(
- *     'order_by' => array(
- *        'name' => 'ASC'
- *     ),
- *   );
- *   $result = tripal_core_chado_select('feature',$columns,$values,$options);
- * @endcode
- * The above code selects a record from the feature table using the three fields
- * that uniquely identify a feature.  The $columns array simply lists the columns
- * to select. The $values array is nested such that the organism is identified by
- * way of the organism_id foreign key constraint by specifying the genus and
- * species.  The cvterm is also specified using its foreign key and the cv_id
- * for the cvterm is nested as well.  In the example above, two different species
- * are allowed to match
- *
- * @ingroup tripal_chado_api
- */
-function tripal_core_chado_select($table, $columns, $values, $options = NULL) {
-
-  $print_errors = (isset($options['print_errors'])) ? $options['print_errors'] : FALSE;
-
-  if (!is_array($values)) {
-    tripal_core_report_error('tripal_core', TRIPAL_ERROR, 'Cannot pass non array as values for selecting.',
-      array(), array('print' => $print_errors)
-    );
-    return FALSE;
-  }
-  if (!is_array($columns)) {
-    tripal_core_report_error('tripal_core', TRIPAL_ERROR, 'Cannot pass non array as columns for selecting.',
-      array(), array('print' => $print_errors)
-    );
-    return FALSE;
-  }
-  if (count($columns)==0) {
-    tripal_core_report_error('tripal_core', TRIPAL_ERROR, 'Cannot pass an empty array as columns for selecting.',
-      array(), array('print' => $print_errors)
-    );
-    return FALSE;
-  }
-
-  // set defaults for options. If we don't set defaults then
-  // we get memory leaks when we try to access the elements
-  if (!is_array($options)) {
-    $options = array();
-  }
-  if (!array_key_exists('case_insensitive_columns', $options)) {
-    $options['case_insensitive_columns'] = array();
-  }
-  if (!array_key_exists('regex_columns', $options)) {
-    $options['regex_columns'] = array();
-  }
-  if (!array_key_exists('order_by', $options)) {
-    $options['order_by'] = array();
-  }
-  if (!array_key_exists('return_sql', $options)) {
-    $options['return_sql'] = FALSE;
-  }
-  if (!array_key_exists('has_record', $options)) {
-    $options['has_record'] = FALSE;
-  }
-  if (!array_key_exists('is_duplicate', $options)) {
-    $options['is_duplicate'] = FALSE;
-  }
-  $pager = array();
-  if (array_key_exists('pager', $options)) {
-    $pager = $options['pager'];
-  }
-
-  // check that our columns and values arguments are proper arrays
-  if (!is_array($columns)) {
-    tripal_core_report_error(
-      'tripal_core',
-      TRIPAL_ERROR,
-      'tripal_core_chado_select; the $columns argument must be an array. Columns:%columns',
-      array('%columns' => print_r($columns, TRUE)),
-      array('print' => $print_errors)
-    );
-    return FALSE;
-  }
-  if (!is_array($values)) {
-    tripal_core_report_error(
-      'tripal_core',
-      TRIPAL_ERROR,
-      'tripal_core_chado_select; the $values argument must be an array. Values:%values',
-      array('%values' => print_r($values, TRUE)),
-      array('print' => $print_errors)
-    );
-    return FALSE;
-  }
-
-  // get the table description
-  $table_desc = tripal_core_get_chado_table_schema($table);
-  $select = '';
-  $from = '';
-  $where = array();
-  $args = array();
-
-  // if the 'use_unique' option is turned on then we want
-  // to remove all but unique keys
-  if ($options['is_duplicate'] and array_key_exists('unique keys', $table_desc)) {
-    $ukeys = $table_desc['unique keys'];
-    $has_results = 0;
-
-    // iterate through the unique constraints and reset the values and columns
-    // arrays to only include these fields
-    foreach ($ukeys as $cname => $fields) {
-      if ($has_results) {
-         continue;
-      }
-      $new_values = array();
-      $new_columns = array();
-      $new_options = array();
-      $uq_sname = "uq_" . $table . "_";
-      $has_pkey = 0;
-
-
-      // include the primary key in the results returned
-      if (array_key_exists('primary key', $table_desc)) {
-        $has_pkey = 1;
-        $pkeys = $table_desc['primary key'];
-        foreach ($pkeys as $index => $key) {
-          array_push($new_columns, $key);
-        }
-      }
-
-      // recreate the $values and $columns arrays
-      foreach ($fields as $field) {
-        if (array_key_exists($field, $values)) {
-          $new_values[$field] = $values[$field];
-          $uq_sname .= substr($field, 0, 2);
-          // if there is no primary key then use the unique contraint fields
-          if (!$has_pkey) {
-            array_push($new_columns, $field);
-          }
-        }
-        // if the field doesn't exist in the values array then
-        // substitute any default values
-        elseif (array_key_exists('default', $table_desc['fields'][$field])) {
-          $new_values[$field] = $table_desc['fields'][$field]['default'];
-          $uq_sname .= substr($field, 0, 2);
-          if (!$has_pkey) {
-            array_push($new_columns, $field);
-          }
-        }
-        // if there is no value (default or otherwise) check if this field is
-        // allowed to be null
-        elseif (!$table_desc['fields'][$field]['not null']) {
-          $new_values[$field] = NULL;
-          $uq_sname .= "n" . substr($field, 0, 2);
-          if (!$has_pkey) {
-            array_push($new_columns, $field);
-          }
-        }
-        // if the array key doesn't exist in the values given by the caller
-        // and there is no default value then we cannot check if the record
-        // is a duplicate so return FALSE
-        else {
-          tripal_core_report_error('tripal_core', TRIPAL_ERROR,
-            'tripal_core_chado_select: There is no value for %field thus we cannot check if this record is unique',
-            array('%field' => $field), array('print' => $print_errors));
-          return FALSE;
-        }
-      }
-
-      $results = tripal_core_chado_select($table, $new_columns, $new_values, $new_options);
-      // if we have a duplicate record then return the results
-      if (count($results) > 0) {
-        $has_results = 1;
-      }
-      unset($new_columns);
-      unset($new_values);
-      unset($new_options);
-    }
-    if ($options['has_record'] and $has_results) {
-      return TRUE;
-    }
-    else {
-      return $results;
-    }
-  }
-
-  foreach ($values as $field => $value) {
-    // make sure the field is in the table description. If not then return an error
-    // message
-    if (!array_key_exists($field, $table_desc['fields'])) {
-      tripal_core_report_error('tripal_core', TRIPAL_ERROR,
-        'tripal_core_chado_select: The field "%field" does not exist for the table "%table".  Cannot perform query. Values: %array',
-        array('%field' => $field, '%table' => $table, '%array' => print_r($values, 1)),
-        array('print' => $print_errors)
-      );
-      return array();
-    }
-
-    $select[] = $field;
-    if (is_array($value)) {
-      // if the user has specified multiple values for matching then this we
-      // want to catch that and save them in our $where array, otherwise
-      // we'll descend for a foreign key relationship
-      if (array_values($value) === $value) {
-        $where[$field] = $value;
-      }
-      else {
-        // select the value from the foreign key relationship for this value
-        $foreign_options = array(
-          'regex_columns' => $options['regex_columns'],
-        );
-
-        $results = tripal_core_chado_get_foreign_key($table_desc, $field, $value, $foreign_options);
-        if (!$results or count($results)==0) {
-          return array();
-        }
-        else {
-          $where[$field] = $results;
-        }
-      }
-    }
-    else {
-      // need to catch a 0 and make int if integer field
-      // but we don't want to catch a NULL
-      if ($value === NULL) {
-        $where[$field] = NULL;
-      }
-      elseif ($table_desc['fields'][$field]['type'] == 'int') {
-        $where[$field][] = (int) $value;
-      }
-      else {
-        $where[$field][] = $value;
-      }
-    }
-  }
-
-
-  // now build the SQL and prepared SQL statements. We may not use
-  // the prepared statement if it wasn't requested in the options or if the
-  // argument in a where statement has multiple values.
-  if (empty($where)) {
-    // sometimes want to select everything
-    $sql  = "SELECT " . implode(', ', $columns) . " ";
-    $sql .= 'FROM {' . $table . '} ';
-    // we don't prepare a statement if there is no where clause
-    $prepared = FALSE;
-  }
-  else {
-    $sql  = "SELECT " . implode(', ', $columns) . " ";
-    $sql .= 'FROM {' . $table . '} ';
-
-    // if $values is empty then we want all results so no where clause
-    if (!empty($values)) {
-      $sql .= "WHERE ";
-    }
-    foreach ($where as $field => $value) {
-
-      // if we have multiple values returned then we need an 'IN' statement
-      // in our where statement
-      if (count($value) > 1) {
-        $sql .= "$field IN (";
-        $index = 0;
-        foreach ($value as $v) {
-          $sql .= ":$field" . $index . ', ';
-          $args[":$field" . $index] = $v;
-          $index++;
-        }
-        $sql = drupal_substr($sql, 0, -2); // remove trailing ', '
-        $sql .= ") AND ";
-      }
-      // if we have a null value then we need an IS NULL in our where statement
-      elseif ($value === NULL) {
-        $sql .= "$field IS NULL AND ";
-        // Need to remove one from the argument count b/c nulls don't add an argument
-      }
-      // if we have a single value then we need an = in our where statement
-      else {
-        $operator = '=';
-        if (in_array($field, $options['regex_columns'])) {
-          $operator = '~*';
-        }
-        if (in_array($field, $options['case_insensitive_columns'])) {
-          $sql .= "lower($field) $operator lower(:$field) AND ";
-          $args[":$field"] = $value[0];
-        }
-        else {
-          $sql .= "$field $operator :$field AND ";
-          $args[":$field"] = $value[0];
-        }
-      }
-    } // end foreach item in where clause
-    $sql = drupal_substr($sql, 0, -4);  // get rid of the trailing 'AND '
-  } // end if (empty($where)){ } else {
-
-  // finally add any ordering of the results to the SQL statement
-  if (count($options['order_by']) > 0) {
-    $sql .= " ORDER BY ";
-    foreach ($options['order_by'] as $field => $dir) {
-      $sql .= "$field $dir, ";
-    }
-    $sql = drupal_substr($sql, 0, -2);  // get rid of the trailing ', '
-  }
-
-  // if the caller has requested the SQL rather than the results then do so
-  if ($options['return_sql'] == TRUE) {
-    return array('sql' => $sql, 'args' => $args);
-  }
-  if (array_key_exists('limit', $pager)) {
-    $total_records = 0;
-    $resource = chado_pager_query($sql, $args, $pager['limit'], $pager['element'], NULL, $total_records);
-  }
-  else {
-    $resource = chado_query($sql, $args);
-  }
-
-  // format results into an array
-  $results = array();
-  foreach ($resource as $r) {
-    $results[] = $r;
-  }
-  if ($options['has_record']) {
-    return count($results);
-  }
-  return $results;
-}
-
-/**
- * Use this function instead of db_query() to avoid switching databases
- * when making query to the chado database
- *
- * Will use a chado persistent connection if it already exists
- *
- * @param $sql
- *   The sql statement to execute
- *
- * @param $args
- *   The array of arguments, with the same structure as passed to
- *   the db_query() function of Drupal.
- *
- * @return
- *   DatabaseStatementInterface A prepared statement object, already executed.
- *
- * @ingroup tripal_chado_api
- */
-function chado_query($sql, $args = array()) {
-  $is_local = $GLOBALS["chado_is_local"];
-
-  // Args should be an array
-  if (!is_array($args)) {
-    tripal_core_report_error('tripal_core', TRIPAL_ERROR,
-      'chado_query; Need to pass an array to chado_query, "%value" passed instead. Query: %query',
-      array('%value' => $args, '%query' => $sql)
-    );
-    $args = array($args);
-    return FALSE;
-  }
-
-  // if Chado is local to the database then prefix the Chado table
-  // names with 'chado'.
-  if ($is_local) {
-    $sql = preg_replace('/\n/', '', $sql);  // remove carriage returns
-    $sql = preg_replace('/\{(.*?)\}/', 'chado.$1', $sql);
-
-    // the featureloc table has some indexes that use function that call other functions
-    // and those calls do not reference a schema, therefore, any tables with featureloc
-    // must automaticaly have the chado schema set as active to find
-    if(preg_match('/chado.featureloc/i', $sql)) {
-      $previous_db = tripal_db_set_active('chado') ;
-      $results = db_query($sql, $args);
-      tripal_db_set_active($previous_db);
-    }
-    // for all other tables we should have everything in scope so just run the query
-    else {
-      $results = db_query($sql, $args);
-    }
-  }
-  // if Chado is not local to the Drupal database then we have to
-  // switch to another database
-  else {
-    $previous_db = tripal_db_set_active('chado') ;
-    $results = db_query($sql, $args);
-    tripal_db_set_active($previous_db);
-  }
-
-  return $results;
-}
-
-/**
- * Use this function instead of pager_query() when selecting a
- * subset of records from a Chado table.
- *
- * @param $query
- *   The SQL statement to execute, this is followed by a variable number of args
- *   used as substitution values in the SQL statement.
- * @param $args
- *   The array of arguments for the query. They keys are the placeholders
- * @param $limit
- *   The number of query results to display per page.
- * @param $element
- *   An optional integer to distinguish between multiple pagers on one page.
- * @param $count_query
- *   An SQL query used to count matching records.
- *
- * @returns
- *   A database query result resource or FALSE if the query was not
- *   executed correctly
- *
- * @ingroup tripal_chado_api
- */
-function chado_pager_query($query, $args, $limit, $element, $count_query = '') {
-
-  // get the page and offset for the pager
-  $page = isset($_GET['page']) ? $_GET['page'] : '0';
-  $offset = $limit * $page;
-
-  // Construct a count query if none was given.
-  if (!isset($count_query)) {
-    $count_query = preg_replace(array('/SELECT.*?FROM /As', '/ORDER BY .*/'),
-      array('SELECT COUNT(*) FROM ', ''), $query);
-  }
-
-  // We calculate the total of pages as ceil(items / limit).
-  $results = chado_query($count_query, $args);
-  if (!$results) {
-    tripal_core_report_error('tripal_core', TRIPAL_ERROR,
-      "chado_pager_query(): Query failed: %cq", array('%cq' => $count_query));
-    return;
-  }
-  $total_records = $results->fetchField();
-
-  // set a session variable for storing the total number of records
-  $_SESSION['chado_pager'][$element]['total_records'] = $total_records;
-
-  pager_default_initialize($total_records, $limit, $element);
-
-  $query .= ' LIMIT ' . (int) $limit . ' OFFSET ' . (int) $offset;
-  $results = chado_query($query, $args);
-  return $results;
-}
-
-/**
- * Gets the value of a foreign key relationship
- *
- * This function is used by tripal_core_chado_select, tripal_core_chado_insert,
- * and tripal_core_chado_update to iterate through the associate array of
- * values that gets passed to each of those routines.  The values array
- * is nested where foreign key contraints are used to specify a value that.  See
- * documentation for any of those functions for further information.
- *
- * @param $table_desc
- *  A table description for the table with the foreign key relationship to be identified generated by
- *  hook_chado_<table name>_schema()
- * @param $field
- *  The field in the table that is the foreign key.
- * @param $values
- *  An associative array containing the values
- * @param $options
- *  An associative array of additional options where the key is the option
- *  and the value is the value of that option. These options are passed on to tripal_core_chado_select.
- *
- * Additional Options Include:
- *  - case_insensitive_columns
- *     An array of columns to do a case insensitive search on.
- *  - regex_columns
- *     An array of columns where the value passed in should be treated as a regular expression
- *
- * @return
- *  A string containg the results of the foreign key lookup, or FALSE if failed.
- *
- * Example usage:
- * @code
- *
- *   $values = array(
- *     'genus' => 'Citrus',
- *     'species' => 'sinensis',
- *   );
- *   $value = tripal_core_chado_get_foreign_key('feature', 'organism_id',$values);
- *
- * @endcode
- * The above code selects a record from the feature table using the three fields
- * that uniquely identify a feature.  The $columns array simply lists the columns
- * to select. The $values array is nested such that the organism is identified by
- * way of the organism_id foreign key constraint by specifying the genus and
- * species.  The cvterm is also specified using its foreign key and the cv_id
- * for the cvterm is nested as well.
- *
- * @ingroup tripal_chado_api
- */
-function tripal_core_chado_get_foreign_key($table_desc, $field, $values, $options = NULL) {
-
-  // set defaults for options. If we don't set defaults then
-  // we get memory leaks when we try to access the elements
-  if (!is_array($options)) {
-    $options = array();
-  }
-  if (!array_key_exists('case_insensitive_columns', $options)) {
-    $options['case_insensitive_columns'] = array();
-  }
-  if (!array_key_exists('regex_columns', $options)) {
-    $options['regex_columns'] = array();
-  }
-
-  // get the list of foreign keys for this table description and
-  // iterate through those until we find the one we're looking for
-  $fkeys = '';
-  if (array_key_exists('foreign keys', $table_desc)) {
-    $fkeys = $table_desc['foreign keys'];
-  }
-  if ($fkeys) {
-    foreach ($fkeys as $name => $def) {
-      if (is_array($def['table'])) {
-        //foreign key was described 2X
-        $message = "The foreign key " . $name . " was defined twice. Please check modules "
-          . "to determine if hook_chado_schema_<version>_" . $table_desc['table'] . "() was "
-          . "implemented and defined this foreign key when it wasn't supposed to. Modules "
-          . "this hook was implemented in: " . implode(', ',
-        module_implements("chado_" . $table_desc['table'] . "_schema")) . ".";
-        watchdog('tripal_core', $message);
-        drupal_set_message(check_plain($message), 'error');
-        continue;
-      }
-      $table = $def['table'];
-      $columns = $def['columns'];
-
-      // iterate through the columns of the foreign key relationship
-      foreach ($columns as $left => $right) {
-        // does the left column in the relationship match our field?
-        if (strcmp($field, $left) == 0) {
-          // the column name of the foreign key matches the field we want
-          // so this is the right relationship.  Now we want to select
-          $select_cols = array($right);
-          $result = tripal_core_chado_select($table, $select_cols, $values, $options);
-          $fields = array();
-          if ($result and count($result) > 0) {
-            foreach ($result as $obj) {
-              $fields[] = $obj->$right;
-            }
-            return $fields;
-          }
-        }
-      }
-    }
-  }
-  else {
-    // @todo: what do we do if we get to this point and we have a fk
-    // relationship expected but we don't have any definition for one in the
-    // table schema??
-    $version = $GLOBALS["chado_version"];
-    $message = t("There is no foreign key relationship defined for " . $field . " .
-       To define a foreign key relationship, determine the table this foreign
-       key referrs to (<foreign table>) and then implement
-       hook_chado_chado_schema_v<version>_<foreign table>(). See
-       tripal_feature_chado_v1_2_schema_feature for an example. Chado version: $version");
-    watchdog('tripal_core', $message);
-    drupal_set_message(check_plain($message), 'error');
-  }
-
-  return array();
-}

+ 0 - 987
tripal_core/api/tripal_core.properties.api.inc

@@ -1,987 +0,0 @@
-<?php
-
-/**
- * @file
- * API to manage the chado prop table for various Tripal Node Types
- *
- * How To Use:
- * @code
-
-  function chado_example_form($form, $form_state) {
-
-    // Default values for form elements can come in the following ways:
-    //
-    // 1) as elements of the $node object.  This occurs when editing an existing node
-    // 2) in the $form_state['values'] array which occurs on a failed validation or
-    //    ajax callbacks when the ajax call originates from non-submit fields other
-    //    than button
-    // 3) in the $form_state['input'] array which occurs on ajax callbacks from submit
-    //    form elements (e.g. buttons) and the form is being rebuilt but has not yet
-    //    been validated
-    //
-    // The reference elements added by this function do use AJAX calls from buttons,
-    // therefore, it is important to check for form values in the $form_state['values']
-    // for case #2 above, and in the $form_state['input'] for case #3.
-    // See the chado analysis node form for an example.
-
-
-    // Next, add in all the form array definition particular to your node type
-
-    // To add in the chado properties form elements, you first need to prepare the arguments
-    // for the function call.
-
-    $details = array(
-      'property_table' => 'example_property',      // the name of the table linking additional properties to this node
-      'base_foreign_key' => 'example_id',          // key to link to the chado content created by this node
-      'base_key_value' => $example_id,             // the value of the above key
-      'cv_name' => 'example_prop_cv',              // the name of the cv governing the _prop.type_id
-      'fieldset_title' => 'Additional References', // the non-translated title for this fieldset
-      'additional_instructions' => ''              // a non-stranslated string providing additional instructions
-    );
-
-    // Finally, and add the additional form elements to the form
-    chado_node_properties_form($form, $form_state, $details);
-
-    return $form;
-  }
-
-  function chado_example_insert($node) {
-
-    // if there is an example_id in the $node object then this must be a sync so
-    // we can skip adding the chado_example as it is already there, although
-    // we do need to proceed with the rest of the insert
-    if (!property_exists($node, 'example_id')) {
-
-      // Add record to chado example table
-
-      // Add to any other tables needed
-
-      // Add all properties
-      // Existing _property links will be cleared and then re-added
-      tripal_api_chado_node_properties_form_update_properties(
-        $node,                // the node object passed in via hook_insert()
-        'example_property',   // the name of the _property linking table
-        'example',            // the name of the base chado table for the node
-        'example_id',         // key to link to the chado content created by this node
-        $node->example_id     // value of the above key
-      );
-    }
-
-    // Add record to chado_example linking example_id to new node
-
-  }
-
-  function chado_example_update($node) {
-
-
-      // Update record in chado example table
-
-      // Update any other tables needed
-
-      // Update all properties
-      // Existing _property links will be cleared and then re-added
-      tripal_api_chado_node_properties_form_update_properties(
-        $node,                // the node object passed in via hook_insert()
-        'example_property',   // the name of the _property linking table
-        'example',            // the name of the base chado table for the node
-        'example_id',         // key to link to the chado content created by this node
-        $node->example_id     // value of the above key
-      );
-
-    // Don't need to update chado_example linking table since niether example_id or nid can be changed in update
-
-  }
-
- * @endcode
- */
-
-/**
- * Retrieve a property for a given base table record
- *
- * @param $basetable
- *   The base table for which the property should be retrieved. Thus to retrieve a property
- *   for a feature the basetable=feature and property is retrieved from featureprop
- * @param $record_id
- *   The foriegn key field of the base table. This should be in integer.
- * @param $property
- *   The cvterm name describing the type of properties to be retrieved
- * @param $cv_name
- *   The name of the cv that the above cvterm is part of
- *
- * @return
- *   An array in the same format as that generated by the function
- *   tripal_core_generate_chado_var().  If only one record is returned it
- *   is a single object.  If more than one record is returned then it is an array
- *   of objects
- *
- * @ingroup tripal_properties_api
- */
-function tripal_core_get_property($basetable, $record_id, $property, $cv_name) {
-  // get the foreign key for this property table
-  $table_desc = tripal_core_get_chado_table_schema($basetable . 'prop');
-  $fkcol = key($table_desc['foreign keys'][$basetable]['columns']);
-
-  // construct the array of values to be selected
-  $values = array(
-    $fkcol => $record_id,
-    'type_id' => array(
-      'cv_id' => array(
-        'name' => $cv_name,
-      ),
-      'name' => $property,
-      'is_obsolete' => 0
-    ),
-  );
-  $results = tripal_core_generate_chado_var($basetable . 'prop', $values);
-  if ($results) {
-    $results = tripal_core_expand_chado_vars($results, 'field', $basetable . 'prop.value');
-  }
-
-  return $results;
-}
-
-/**
- * Insert a property for a given base table.  By default if the property already
- * exists a new property is added with the next available rank.  If
- * $update_if_present argument is specified then the record will be updated if it
- * exists rather than adding a new property.
- *
- * @param $basetable
- *   The base table for which the property should be inserted. Thus to insert a property
- *   for a feature the basetable=feature and property is inserted into featureprop
- * @param $record_id
- *   The foriegn key value of the base table. This should be in integer.
- * @param $property
- *   The cvterm name describing the type of properties to be inserted
- * @param $cv_name
- *   The name of the cv that the above cvterm is part of
- * @param $value
- *   The value of the property to be inserted (can be empty)
- * @param $update_if_present
- *   A boolean indicating whether an existing record should be updated. If the
- *   property already exists and this value is not specified or is zero then
- *   a new property will be added with the next largest rank.
- *
- * @return
- *   Return True on Insert/Update and False otherwise
- *
- * @ingroup tripal_properties_api
- */
-function tripal_core_insert_property($basetable, $record_id, $property,
-$cv_name, $value, $update_if_present = 0) {
-
-  // first see if the property already exists, if the user want's to update
-  // then we can do that, but otherwise we want to increment the rank and
-  // insert
-  $props = tripal_core_get_property($basetable, $record_id, $property, $cv_name);
-  if (!is_array($props) and $props) {
-    $props = array($props);
-  }
-
-  $rank = 0;
-  if (count($props) > 0) {
-    if ($update_if_present) {
-      return tripal_core_update_property($basetable, $record_id, $property, $cv_name, $value);
-    }
-    else {
-      // iterate through the properties returned and check to see if the
-      // property with this value already exists if not, get the largest rank
-      // and insert the same property but with this new value
-      foreach ($props as $p) {
-        if ($p->rank > $rank) {
-          $rank = $p->rank;
-        }
-        if (strcmp($p->value, $value) == 0) {
-          return TRUE;
-        }
-      }
-      // now add 1 to the rank
-      $rank++;
-    }
-  }
-
-  // make sure the cvterm exists.  Otherwise we'll get an error with
-  // prepared statements not matching
-  $values = array(
-    'cv_id' => array(
-      'name' => $cv_name,
-    ),
-    'name' => $property,
-  );
-
-  $options = array();
-  $term = tripal_core_chado_select('cvterm', array('cvterm_id'), $values, $options);
-  if (!$term or count($term) == 0) {
-    watchdog('tripal_core', "Cannot find property '%prop_name' in vocabulary '%cvname'.",
-    array('%prop_name' => $property, '%cvname' => $cv_name), WATCHDOG_ERROR);
-    return FALSE;
-  }
-
-  // get the foreign key for this property table
-  $table_desc = tripal_core_get_chado_table_schema($basetable . 'prop');
-  $fkcol = key($table_desc['foreign keys'][$basetable]['columns']);
-
-  // construct the array of values to be inserted
-  $values = array(
-    $fkcol => $record_id,
-    'type_id' => array(
-      'cv_id' => array(
-        'name' => $cv_name,
-      ),
-      'name' => $property,
-    ),
-    'value' => $value,
-    'rank' => $rank,
-  );
-
-  $options = array();
-  $result = tripal_core_chado_insert($basetable . 'prop', $values, $options);
-  return $result;
-}
-
-/**
- * Update a property for a given base table record and property name.  This
- * function should be used only if one record of the property will be present.
- * If the property name can have multiple entries (with increasing rank) then
- * use the function named tripal_core_update_property_by_id
- *
- * @param $basetable
- *   The base table for which the property should be updated. The property table
- *   is constructed using  a combination of the base table name and the suffix
- *   'prop' (e.g. basetable = feature then property tabie is featureprop).
- * @param $record_id
- *   The foreign key of the basetable to update a property for. This should be in integer.
- *   For example, if the basetable is 'feature' then the $record_id should be the feature_id
- * @param $property
- *   The cvterm name of property to be updated
- * @param $cv_name
- *   The name of the cv that the above cvterm is part of
- * @param $value
- *   The value of the property to be inserted (can be empty)
- * @param $insert_if_missing
- *   A boolean indicating whether a record should be inserted if one doesn't exist to update
- *
- * Note: The property to be updated is select via the unique combination of $record_id and
- * $property and then it is updated with the supplied value
- *
- * @return
- *   Return True on Update/Insert and False otherwise
- *
- * @ingroup tripal_properties_api
- */
-function tripal_core_update_property($basetable, $record_id, $property,
-$cv_name, $value, $insert_if_missing = 0) {
-
-  // first see if the property is missing (we can't update a missing property
-  $prop = tripal_core_get_property($basetable, $record_id, $property, $cv_name);
-  if (count($prop)==0) {
-    if ($insert_if_missing) {
-      return tripal_core_insert_property($basetable, $record_id, $property, $cv_name, $value);
-    }
-    else {
-      return FALSE;
-    }
-  }
-
-  // get the foreign key for this property table
-  $table_desc = tripal_core_get_chado_table_schema($basetable . 'prop');
-  $fkcol = key($table_desc['foreign keys'][$basetable]['columns']);
-
-  // construct the array that will match the exact record to update
-  $match = array(
-    $fkcol => $record_id,
-    'type_id' => array(
-      'cv_id' => array(
-        'name' => $cv_name,
-      ),
-      'name' => $property,
-    ),
-  );
-
-  // construct the array of values to be updated
-  $values = array(
-    'value' => $value,
-  );
-
-  return tripal_core_chado_update($basetable . 'prop', $match, $values);
-}
-
-/**
- * Update a property for a given base table record.  This function should be
- * used if multiple records of the same property will be present. Also, use this
- * function to change the property name of an existing property.
- *
- * @param $basetable
- *   The base table for which the property should be updated. The property table
- *   is constructed using  a combination of the base table name and the suffix
- *   'prop' (e.g. basetable = feature then property tabie is featureprop).
- * @param $record_id
- *   The primary key of the base table. This should be in integer.
- *   For example, if the basetable is 'feature' then the $record_id should be the featureprop_id
- * @param $property
- *   The cvterm name of property to be updated
- * @param $cv_name
- *   The name of the cv that the above cvterm is part of
- * @param $value
- *   The value of the property to be inserted (can be empty)
- *
- * @return
- *   Return True on Update/Insert and False otherwise
- *
- * @ingroup tripal_properties_api
- */
-function tripal_core_update_property_by_id($basetable, $record_id, $property,
-$cv_name, $value) {
-
-  // get the primary key for this property table
-  $table_desc = tripal_core_get_chado_table_schema($basetable . 'prop');
-  $pkcol = $table_desc['primary key'][0];
-
-  // construct the array that will match the exact record to update
-  $match = array(
-    $pkcol => $record_id,
-  );
-
-  // construct the array of values to be updated
-  $values = array(
-    'type_id' => array(
-      'cv_id' => array(
-        'name' => $cv_name,
-      ),
-      'name' => $property,
-    ),
-    'value' => $value,
-  );
-
-  return tripal_core_chado_update($basetable . 'prop', $match, $values);
-}
-
-/**
- * Deletes a property for a given base table record using the property name
- *
- * @param $basetable
- *   The base table for which the property should be deleted. Thus to deleted a property
- *   for a feature the basetable=feature and property is deleted from featureprop
- * @param $record_id
- *   The primary key of the basetable to delete a property for. This should be in integer.
- * @param $property
- *   The cvterm name describing the type of property to be deleted
- * @param $cv_name
- *   The name of the cv that the above cvterm is part of
- *
- * Note: The property to be deleted is select via the unique combination of $record_id and $property
- *
- * @return
- *   Return True on Delete and False otherwise
- *
- * @ingroup tripal_properties_api
- */
-function tripal_core_delete_property($basetable, $record_id, $property, $cv_name) {
-
-  // get the foreign key for this property table
-  $table_desc = tripal_core_get_chado_table_schema($basetable . 'prop');
-  $fkcol = key($table_desc['foreign keys'][$basetable]['columns']);
-
-  // construct the array that will match the exact record to update
-  $match = array(
-    $fkcol => $record_id,
-    'type_id' => array(
-      'cv_id' => array(
-        'name' => $cv_name,
-      ),
-      'name' => $property,
-    ),
-  );
-
-  return tripal_core_chado_delete($basetable . 'prop', $match);
-}
-
-/**
- * Deletes a property using the property ID
- *
- * @param $basetable
- *   The base table for which the property should be deleted. Thus to deleted a property
- *   for a feature the basetable=feature and property is deleted from featureprop
- * @param $record_id
- *   The primary key of the basetable to delete a property for. This should be in integer.
- *
- * @return
- *   Return True on Delete and False otherwise
- *
- * @ingroup tripal_properties_api
- */
-function tripal_core_delete_property_by_id($basetable, $record_id) {
-
-  // get the foreign key for this property table
-  $table_desc = tripal_core_get_chado_table_schema($basetable . 'prop');
-  $pkcol = $table_desc['primary key'][0];
-
-  // construct the array that will match the exact record to update
-  $match = array(
-    $pkcol => $record_id,
-  );
-
-  return tripal_core_chado_delete($basetable . 'prop', $match);
-}
-
-/**
- * @section
- * Properties Form to be added to node forms
- */
-
-/**
- * Provides a form for adding to BASEprop table
- *
- * @param $form
- *   The Drupal form array into which the property form elements will be added
- * @param $form_state
- *   The corresponding form_state array for the form
- * @param $details
- *   An array defining details needed by this form. Required Keys are:
- *     - property_table: the name of the property linking table (ie: featureprop)
- *     - base_foreign_key: the name of the foreign key linking this table to the non-property table (ie: feature_id)
- *     - base_key_value: the value of the base_foreign_key for the current form (ie: 999 if the feature_id=999)
- *   Require ONE of the following:
- *     The controlled vocabulary governing the property types
- *       -cv_id: the unique key from the cv table
- *       -cv_name: the cv.name field uniquely identifying the controlled vocab
- *   Optional keys include:
- *     - fieldset_title: the non-translated title for this fieldset
- *     - additional_instructions: a non-translated string providing additional instructions
- *     - select_options: must be an array where the [key] is a valid cvterm_id and
- *       the [value] is the human-readable name of the option. This is generated from the cv_name/id by default
- */
-function chado_node_properties_form(&$form, &$form_state, $details) {
-
-  // Set Defaults for optional fields
-  $details['fieldset_title'] = 'Properties';
-  $details['additional_instructions'] = '';
-
-  // Get Property Types for the Select List
-  if (isset($details['select_options'])) {
-    $property_options = $details['select_options'];
-  }
-  else {
-    if (isset($details['cv_name'])) {
-      $property_options = array();
-      $property_options[] = 'Select a Property';
-      $sql = "
-        SELECT DISTINCT CVT.cvterm_id, CVT.name, CVT.definition
-        FROM  {cvterm} CVT
-          INNER JOIN {cv} CV ON CVT.cv_id = CV.cv_id
-        WHERE
-          CV.name = :cv_name AND
-          NOT CVT.is_obsolete = 1
-        ORDER BY CVT.name ASC
-      ";
-      $prop_types = chado_query($sql, array(':cv_name' => $details['cv_name']));
-      while ($prop = $prop_types->fetchObject()) {
-        $property_options[$prop->cvterm_id] = $prop->name;
-      }
-    } elseif (isset($details['cv_id'])) {
-      $property_options = array();
-      $property_options[] = 'Select a Property';
-      $sql = "
-        SELECT DISTINCT CVT.cvterm_id, CVT.name, CVT.definition
-        FROM  {cvterm} CVT
-          INNER JOIN {cv} CV ON CVT.cv_id = CV.cv_id
-        WHERE
-          CV.cv_id = :cv_id AND
-          NOT CVT.is_obsolete = 1
-        ORDER BY CVT.name ASC
-      ";
-      $prop_types = chado_query($sql, array(':cv_id' => $details['cv_id']));
-      while ($prop = $prop_types->fetchObject()) {
-        $property_options[$prop->cvterm_id] = $prop->name;
-      }
-    }
-  }
-
-  // the fieldset of the property elements
-  $form['properties'] = array(
-    '#type' => 'fieldset',
-    '#title' => t($details['fieldset_title']),
-    '#description' => t('You may add additional properties by selecting a property type
-      from the dropdown and adding text. You may add as many properties as desired by
-      clicking the add button on the right. To remove a property, click the remove button.
-      To add additional properties to the drop down. ' . $details['additional_instructions']),
-    '#prefix' => "<div id='properties-fieldset'>",
-    '#suffix' => '</div>'
-  );
-
-  // this form element is a tree, so that we don't puke all of the values into then node variable
-  // it is set as a tree, and keeps them in the $form_state['values']['property_table'] heading.
-  $form['properties']['property_table'] = array(
-    '#type' => 'markup',
-    '#tree' => TRUE,
-    '#prefix' => '<div id="tripal-generic-edit-properties-table">',
-    '#suffix' => '</div>',
-    '#theme' => 'chado_node_properties_form_table'
-  );
-
-  // Add defaults into form_state to be used elsewhere
-  $form['properties']['property_table']['details'] = array(
-    '#type' => 'hidden',
-    '#value' => serialize($details)
-  );
-
-  /* Properties can come to us in two ways:
-   *
-   * 1) In the form state in the $form_state['chado_properties']. Data is in this field
-   *    when an AJAX call updates the form state or a validation error.
-   *
-   * 2) Directly from the database if the record already has properties associated.  This
-   *    data is only used the first time the form is loaded. On AJAX calls or validation
-   *    errors the fields on the form are populated from the $form_state['chado_properties']
-   *    entry.
-   */
-  if (isset($form_state['chado_properties'])) {
-    $existing_properties = $form_state['chado_properties'];
-  }
-  else {
-    if (isset($details['cv_name'])) {
-      $existing_properties = chado_query(
-        "SELECT PP.".$details['property_table']."_id property_id, CVT.cvterm_id as type_id, CVT.name as type_name, CVT.definition, PP.value, PP.rank
-        FROM {" . $details['property_table'] . "} PP
-        INNER JOIN {cvterm} CVT ON CVT.cvterm_id = PP.type_id
-        INNER JOIN {cv} CV      ON CVT.cv_id     = CV.cv_id
-        WHERE
-        PP." . $details['base_foreign_key'] . " = :base_key_value AND
-        CV.name = '" .$details['cv_name']. "'
-        ORDER BY CVT.name, PP.rank",
-         array(':base_key_value' => $details['base_key_value'])
-      );
-    } elseif (isset($details['cv_id'])) {
-      $existing_properties = chado_query(
-        "SELECT PP.".$details['property_table']."_id property_id, CVT.cvterm_id as type_id, CVT.name as type_name, CVT.definition, PP.value, PP.rank
-        FROM {" . $details['property_table'] . "} PP
-        INNER JOIN {cvterm} CVT ON CVT.cvterm_id = PP.type_id
-        INNER JOIN {cv} CV      ON CVT.cv_id     = CV.cv_id
-        WHERE
-        PP." . $details['base_foreign_key'] . " = :base_key_value AND
-        CV.cv_id = '" .$details['cv_id']. "'
-        ORDER BY CVT.name, PP.rank",
-         array(':base_key_value' => $details['base_key_value'])
-      );
-    }
-  }
-
-  /* The format of the $existing_properties array is either:
-   *
-   * From the chado_properties array:
-   * $form_state['chado_properties'] = array(
-   *   '[type_id]-[rank]' => array(
-   *     'type_id' => [the cvterm.cvterm_id value]
-   *     'type_name' => [the cvterm.name value]
-   *     'property_id' => [the property.property_id value, or NULL if it doesn't yet exist],
-   *     'value' => [the BASEprop.value value],
-   *     'rank' => [the BASEprop.rank value],
-   *   ),
-   * );
-   *
-   * OR
-   * Populated from the database:
-   * $existing_property = array(
-   *   0 => array(
-   *     'property_id' => [the property.property_id value, or NULL if it doesn't yet exist],
-   *     'type_id' => [the cvterm.cvterm_id value]
-   *     'type_name' => [the cvterm.name value]
-   *     'value' => [the BASEprop.value value],
-   *     'rank' => [the BASEprop.rank value],
-   *   ),
-   * );
-   *
-   * NOTE: The main difference is the key
-   *
-   * Loop on the array elements of the $existing_properties array and add
-   * an element to the form for each one.
-   */
-  foreach ($existing_properties as $property) {
-
-    $form['properties']['property_table'][$property->type_id]['#type'] = 'markup';
-    $form['properties']['property_table'][$property->type_id]['#value'] = '';
-
-    $form['properties']['property_table'][$property->type_id][$property->rank]['#type'] = 'markup';
-    $form['properties']['property_table'][$property->type_id][$property->rank]['#value'] = '';
-
-    $form['properties']['property_table'][$property->type_id][$property->rank]['prop_type_id'] = array(
-      '#type' => 'hidden',
-      '#value' => $property->type_id
-    );
-
-    $form['properties']['property_table'][$property->type_id][$property->rank]['prop_value'] = array(
-      '#type' => 'hidden',
-      '#value' => $property->value
-    );
-
-    $form['properties']['property_table'][$property->type_id][$property->rank]['property_id'] = array(
-      '#type' => 'hidden',
-      '#value' => $property->property_id
-    );
-
-    $form['properties']['property_table'][$property->type_id][$property->rank]['type'] = array(
-      '#type' => 'markup',
-      '#markup' => $property->type_name
-    );
-
-    $form['properties']['property_table'][$property->type_id][$property->rank]['value'] = array(
-      '#type' => 'markup',
-      '#markup' => $property->value
-    );
-
-    $form['properties']['property_table'][$property->type_id][$property->rank]['rank'] = array(
-      '#type' => 'markup',
-      '#markup' => $property->rank
-    );
-    // remove button
-    $form['properties']['property_table'][$property->type_id][$property->rank]['property_action'] = array(
-      '#type' => 'submit',
-      '#value' => t('Remove'),
-      '#name' => "property_remove-".$property->type_id.'-'.$property->rank,
-      '#ajax' => array(
-        'callback' => "chado_node_properties_form_ajax_update",
-        'wrapper' => 'tripal-generic-edit-properties-table',
-        'effect'   => 'fade',
-        'method'   => 'replace',
-        'prevent'  => 'click'
-      ),
-      // When this button is clicked, the form will be validated and submitted.
-      // Therefore, we set custom submit and validate functions to override the
-      // default node form submit.  In the validate function we validate only the
-      // property fields and in the submit we remove the indicated property
-      // from the chado_properties array. In order to keep validate errors
-      // from the node form validate and Drupal required errors for non-property fields
-      // preventing the user from removing properties we set the #limit_validation_errors below
-      '#validate' => array('chado_node_properties_form_remove_button_validate'),
-      '#submit' => array('chado_node_properties_form_remove_button_submit'),
-      // Limit the validation of the form upon clicking this button to the property_table tree
-      // No other fields will be validated (ie: no fields from the main form or any other api
-      // added form).
-      '#limit_validation_errors' => array(
-        array('property_table')  // Validate all fields within $form_state['values']['property_table']
-      )
-    );
-  }
-
-  // Form elements for adding a new property
-  //---------------------------------------------
-  $form['properties']['property_table']['new'] = array(
-    '#type' => 'markup',
-    '#prefix' => '<span class="addtl-properties-add-new-property">',
-    '#suffix' => '</span>'
-  );
-
-  $form['properties']['property_table']['new']['type'] = array(
-    '#type' => 'select',
-    '#options' => $property_options, // Set at top of form
-  );
-
-  $form['properties']['property_table']['new']['value'] = array(
-    '#type' => 'textfield',
-  );
-
-  // add button
-  $form['properties']['property_table']['new']['property_action'] = array(
-    '#type' => 'submit',
-    '#value' => t('Add'),
-    '#name' => "property-add",
-    '#ajax' => array(
-      'callback' => "chado_node_properties_form_ajax_update",
-      'wrapper' => 'tripal-generic-edit-properties-table',
-      'effect'   => 'fade',
-      'method'   => 'replace',
-      'prevent'  => 'click'
-    ),
-    // When this button is clicked, the form will be validated and submitted.
-    // Therefore, we set custom submit and validate functions to override the
-    // default node form submit.  In the validate function we validate only the
-    // additional property fields and in the submit we add them to the chado_properties
-    // array. In order to keep validate errors from the node form validate and Drupal
-    // required errors for non-property fields preventing the user from adding properties we
-    // set the #limit_validation_errors below
-    '#validate' => array('chado_node_properties_form_add_button_validate'),
-    '#submit' => array('chado_node_properties_form_add_button_submit'),
-    // Limit the validation of the form upon clicking this button to the property_table tree
-    // No other fields will be validated (ie: no fields from the main form or any other api
-    // added form).
-    '#limit_validation_errors' => array(
-      array('property_table')  // Validate all fields within $form_state['values']['property_table']
-    )
-  );
-}
-
-/**
- * Validate the user input for creating a new property
- * Called by the add button in chado_node_properties_form
- */
-function chado_node_properties_form_add_button_validate($form, &$form_state) {
-
-  // Ensure the type_id is supplied & Valid
-  $cvterm = tripal_core_chado_select(
-    'cvterm',
-    array('cvterm_id', 'name'),
-    array('cvterm_id' => $form_state['values']['property_table']['new']['type'])
-  );
-  if (!isset($cvterm[0])) {
-    form_set_error('property_table][new][cvterm', 'Please select a property type before attempting to add a new property.');
-  }
-  else {
-    $form_state['values']['property_table']['new']['type_name'] = $cvterm[0]->name;
-  }
-
-  // Ensure value is supplied
-  if (empty($form_state['values']['property_table']['new']['value'])) {
-    form_set_error('property_table][new][value','You must enter the property value before attempting to add a new property.');
-  }
-}
-
-/**
- * Called by the add button in chado_node_properties_form
- *
- * Create an array of properties in the form state. This array will then be
- * used to rebuild the form in subsequent builds
- */
-function chado_node_properties_form_add_button_submit(&$form, &$form_state) {
-
-  $details = unserialize($form_state['values']['property_table']['details']);
-
-  // if the chado_additional_properties array is not set then this is the first time modifying the
-  // property table. this means we need to include all the properties from the db
-  if (!isset($form_state['chado_properties'])) {
-    chado_node_properties_form_create_property_formstate_array($form, $form_state);
-  }
-
-  // get details for the new property
-  $property = array(
-    'type_id' => $form_state['values']['property_table']['new']['type'],
-    'type_name' => $form_state['values']['property_table']['new']['type_name'],
-    'property_id' => NULL,
-    'value' => $form_state['values']['property_table']['new']['value'],
-    'rank' => '0',
-  );
-
-  // get max rank
-  $rank = tripal_core_get_max_chado_rank(
-    $details['property_table'],
-    array(
-      $details['base_foreign_key'] => $details['base_key_value'],
-      'type_id' => $property['type_id']
-    )
-  );
-  $property['rank'] = strval($rank + 1);
-
-  $key = $property['type_id'] . '-' . $property['rank'];
-  $form_state['chado_properties'][$key] = (object) $property;
-
-  $form_state['rebuild'] = TRUE;
-}
-
-/**
- * There is no user input for the remove buttons so there is no need to validate
- * However, both a submit & validate need to be specified so this is just a placeholder
- *
- * Called by the many remove buttons in chado_node_properties_form
- */
-function chado_node_properties_form_remove_button_validate($form, $form_state) {
-  // No Validation needed for remove
-}
-
-/**
- * Remove the correct property from the form
- * Called by the many remove buttons in chado_node_properties_form
- */
-function chado_node_properties_form_remove_button_submit(&$form, &$form_state) {
-
-  // if the chado_properties array is not set then this is the first time modifying the
-  // property table. this means we need to include all the properties from the db
-  if (!isset($form_state['chado_properties'])) {
-    chado_node_properties_form_create_property_formstate_array($form, $form_state);
-  }
-
-  // remove the specified property from the form property table
-  if(preg_match('/property_remove-([^-]+-[^-]+)/',$form_state['triggering_element']['#name'],$match)) {
-    $key = $match[1];
-    if (array_key_exists($key, $form_state['chado_properties'])) {
-      unset($form_state['chado_properties'][$key]);
-    }
-  }
-
-  $form_state['rebuild'] = TRUE;
-}
-
-/**
- * Ajax function which returns the section of the form to be re-rendered
- */
-function chado_node_properties_form_ajax_update($form, $form_state) {
-  return $form['properties']['property_table'];
-}
-
-/**
- * Creates an array in form_state containing the existing properties. This array is
- * then modified by the add/remove buttons and used as a source for rebuilding the form.
- * This function get's called at each button (add and remove) button submits the first
- * time one of the button's is clicked to instantiates the $form_state['chado_properties'] array
- *
- * $form_state['chado_properties'] = array(
- *   '[type_id]-[rank]' => array(
- *     'type_id' => [the cvterm.cvterm_id value]
- *     'type_name' => [the cvterm.name value]
- *     'property_id' => [the property.property_id value, or NULL if it doesn't yet exist],
- *     'value' => [the BASEprop.value value],
- *     'rank' => [the BASEprop.rank value],
- *   ),
- * );
- */
-function chado_node_properties_form_create_property_formstate_array($form, &$form_state) {
-
-  $form_state['chado_properties'] = array();
-
-  foreach (element_children($form['properties']['property_table']) as $type_id) {
-    if ($type_id != 'new') {
-      foreach (element_children($form['properties']['property_table'][$type_id]) as $rank) {
-          $element = $form['properties']['property_table'][$type_id][$rank];
-          $property = array(
-            'type_id' => $element['prop_type_id']['#value'],
-            'type_name' => $element['type']['#markup'],
-            'property_id' => $element['property_id']['#value'],
-            'value' => $element['value']['#markup'],
-            'rank' => $element['rank']['#markup']
-          );
-          $key = $property['type_id'] . '-' . $property['rank'];
-          $form_state['chado_properties'][$key] = (object) $property;
-      }
-    }
-  }
-}
-
-/**
- * Function to theme the add/remove properties form into a table
- */
-function theme_chado_node_properties_form_table($variables) {
-  $element = $variables['element'];
-
-  $header = array(
-    'type' => t('Type'),
-    'value' => t('Value'),
-    'rank' => t('Rank'),
-    'property_action' => t('Actions'),
-  );
-
-  $rows = array();
-  foreach (element_children($element) as $type_id) {
-    if ($type_id == 'new') {
-      $row = array();
-
-        $row['data'] = array();
-        foreach ($header as $fieldname => $title) {
-          $row['data'][] = drupal_render($element[$type_id][$fieldname]);
-        }
-        $rows[] = $row;
-    }
-    else {
-      foreach (element_children($element[$type_id]) as $version) {
-        $row = array();
-
-        $row['data'] = array();
-        foreach ($header as $fieldname => $title) {
-          $row['data'][] = drupal_render($element[$type_id][$version][$fieldname]);
-        }
-        $rows[] = $row;
-      }
-    }
-  }
-
-  return theme('table', array(
-    'header' => $header,
-    'rows' => $rows
-  ));
-}
-
-/**
- * This function is used in a hook_insert, hook_update for a node form
- * when the chado node properties form has been added to the form.  It retrieves all of the properties
- * and returns them in an array of the format:
- *
- *   $dbxefs[<type_id>][<rank>] = <value>
- *
- * This array can then be used for inserting or updating properties
- *
- * @param $node
- *
- * @return
- *   A property array
- *
- * @ingroup tripal_properties_api
- */
-function chado_node_properties_form_retreive($node) {
-  $properties = array();
-
-  if (isset($node->property_table)) {
-    foreach ($node->property_table as $type_id => $elements) {
-      if ($type_id != 'new' AND $type_id != 'details') {
-        foreach ($elements as $rank => $element) {
-          $properties[$type_id][$rank] = $element['prop_value'];
-        }
-      }
-    }
-  }
-
-  return $properties;
-}
-
-/**
- * This function is used in hook_insert or hook_update and handles inserting of any new
- * properties
- *
- * @param $node
- *    The node passed into hook_insert & hook_update
- * @param $details
- *   - property_table: the name of the _property linking table (ie: feature_property)
- *   - base_table: the name of the base table (ie: feature)
- *   - foreignkey_name: the name of the foreign key used to link to the node content (ie: feature_id)
- *   - foreignkey_value: the value of the foreign key (ie: 445, if there exists a feature where feature_id=445)
- * @param $retrieved_properties
- *   An array of properties from chado_node_properties_form_retreive($node). This can be used if you need
- *   special handling for some of the properties (See FeatureMap chado_featuremap_insert for an example)
- */
-function chado_node_properties_form_update_properties($node, $details, $retrieved_properties = FALSE) {
-
-  $details['foreignkey_value'] = (isset($details['foreignkey_value'])) ? $details['foreignkey_value'] : 0;
-
-  if (isset($node->property_table) AND ($details['foreignkey_value'] > 0)) {
-    // First remove existing property links
-    tripal_core_chado_delete($details['property_table'], array($details['foreignkey_name'] => $details['foreignkey_value']));
-
-    // Add back in property links and insert properties as needed
-    if ($retrieved_properties) {
-      $properties = $retrieved_properties;
-    }
-    else {
-      $properties = chado_node_properties_form_retreive($node);
-    }
-    foreach ($properties as $type_id => $ranks) {
-      foreach ($ranks as $rank => $value) {
-
-        $success = tripal_core_chado_insert(
-          $details['property_table'],
-          array(
-            $details['foreignkey_name'] => $details['foreignkey_value'],
-            'type_id' => $type_id,
-            'value' => $value,
-            'rank' => $rank
-          )
-        );
-
-        if (!$success) {
-          watchdog(
-            'tripal_' . $details['base_table'],
-            $details['base_table'] . ' Insert: Unable to insert property type_id %cvterm with value %value.',
-            array('%cvterm' => $type_id, '%value' => $value),
-            WATCHDOG_ERROR
-          );
-        }
-
-      }
-    }
-  }
-}

+ 0 - 725
tripal_core/api/tripal_core.relationships.api.inc

@@ -1,725 +0,0 @@
-<?php
-
-/**
- * @file
- * API to manage the chado _relationship table for various Tripal Node Types
- *
- * How To Use:
- * @code
-
-  function chado_example_form($form, $form_state) {
-
-    // Default values for form elements can come in the following ways:
-    //
-    // 1) as elements of the $node object.  This occurs when editing an existing node
-    // 2) in the $form_state['values'] array which occurs on a failed validation or
-    //    ajax callbacks when the ajax call originates from non-submit fields other
-    //    than button
-    // 3) in the $form_state['input'] array which occurs on ajax callbacks from submit
-    //    form elements (e.g. buttons) and the form is being rebuilt but has not yet
-    //    been validated
-    //
-    // The reference elements added by this function do use AJAX calls from buttons,
-    // therefore, it is important to check for form values in the $form_state['values']
-    // for case #2 above, and in the $form_state['input'] for case #3.
-    // See the chado analysis node form for an example.
-
-
-    // Next, add in all the form array definition particular to your node type
-
-    // To add in the relationship form elements, you first need to prepare the arguments
-    // for the function call.
-
-    $details = array(
-      'relationship_table' => 'example_relationship',    // the name of the table linking additional dbxrefs to this node
-      'base_table' => 'example',                         // the name of the chado table this node links to
-      'base_foreign_key' => 'example_id',                // key to link to the chado content created by this node
-      'base_key_value' => $example_id,                   // the value of the above key
-      'fieldset_title' => 'Relationships',               // the non-translated title for this fieldset
-      'additional_instructions' => ''                    // a non-stranslated string providing additional instructions
-    );
-
-    // Finally, and add the additional form elements to the form
-    tripal_core_relationships_form($form, $form_state, $details);
-
-    return $form;
-  }
-
-  function chado_example_insert($node) {
-
-    // if there is an example_id in the $node object then this must be a sync so
-    // we can skip adding the chado_example as it is already there, although
-    // we do need to proceed with the rest of the insert
-    if (!property_exists($node, 'example_id')) {
-
-      // Add record to chado example table
-
-      // Add to any other tables needed
-
-      // Add all relationships
-      // Existing _relationship links with the current example as either the subject_id
-      // or object_id will be cleared and then re-added
-      tripal_core_relationships_form_update_relationships(
-        $node,
-        'example_relationship',
-        $node->example_id
-      );
-    }
-
-    // Add record to chado_example linking example_id to new node
-
-  }
-
-  function chado_example_update($node) {
-
-
-      // Update record in chado example table
-
-      // Update any other tables needed
-
-      // Update all additional database references
-      // Existing _relationship links with the current example as either the subject_id
-      // or object_id will be cleared and then re-added
-      tripal_core_relationships_form_update_relationships(
-        $node,
-        'example_relationship',
-        $node->example_id
-      );
-
-    // Don't need to update chado_example linking table since niether example_id or nid can be changed in update
-
-  }
-
- * @endcode
- */
-
-/**
- * Provides a form for adding to BASE_relationship and relationship tables
- *
- * @param $form
- *   The Drupal form array into which the relationship elements will be added
- * @param $form_state
- *   The corresponding form_state array for the form
- * @param $details
- *   An array defining details needed by this form. Required Keys are:
- *     - relationship_table: the name of the relationship table (ie: feature_relationship)
- *     - base_table: the name of the base table (ie: feature)
- *     - base_foreign_key: the name of the foreign key linking this table to the non-relationship table (ie: feature_id)
- *     - base_key_value: the value of the base_foreign_key for the current form (ie: 999 if the feature_id=999)
- *     - nodetype: the non-translated singular title of this node type
- *   One of the following:
- *     - cv_id: the id of the ontology to supply terms for the type dropdown
- *     - cv_name: the name of the ontology to supply terms for the type dropdown
- *   Optional keys include:
- *     - fieldset_title: the non-translated title for this fieldset
- *     - additional_instructions: a non-translated string providing additional instructions
- *     - nodetype_plural: the non-translated plural title of this node type
- *
- * @ingroup tripal_relationships_api
- */
-function tripal_core_relationships_form(&$form, &$form_state, $details) {
-
-  $form_state['rebuild'] = TRUE;
-
-  // Set Defaults for optional fields
-  $details['fieldset_title'] = (isset($details['fieldset_title'])) ? $details['fieldset_title'] : 'Relationships';
-  $details['additional_instructions'] = (isset($details['additional_instructions'])) ? $details['additional_instructions'] : '';
-  $details['nodetype_plural']  = (isset($details['nodetype_plural'])) ? $details['nodetype_plural'] : $details['nodetype'] . 's';
-
-  // Add defaults into form_state to be used elsewhere
-  $form['rel_details'] = array(
-    '#type' => 'hidden',
-    '#value' => serialize($details)
-  );
-
-  // Get relationship type options
-  if (isset($details['cv_id'])) {
-    $query = "SELECT cvterm_id, name FROM {cvterm} cvterm WHERE cv_id = :cv_id";
-    $result = chado_query($query, array(':cv_id' => $details['cv_id']));
-  } elseif (isset($details['cv_name'])) {
-    $query = "SELECT cvterm_id, name FROM {cvterm} cvterm WHERE cv_id IN (SELECT cv_id FROM cv WHERE name = :cv_name)";
-    $result = chado_query($query, array(':cv_name' => $details['cv_name']));
-  }
-  $type_options = array(0 => 'Select a Type');
-  foreach ($result as $cvterm) {
-    $type_options[ $cvterm->cvterm_id ] = $cvterm->name;
-  }
-
-  $form['relationships'] = array(
-    '#type' => 'fieldset',
-    '#title' => t($details['fieldset_title']),
-    '#description' => t('You may add relationships between this %nodetype and other
-      %nodetype_plural by entering the details below.  You may add
-      as many relationships as desired by clicking the add button on the right.  To
-      remove a relationship, click the remove button. ' . $details['additional_instructions'],
-      array('%nodetype' => $details['nodetype'], '%nodetype_plural' => $details['nodetype_plural'])),
-    '#prefix' => "<div id='relationships-fieldset'>",
-    '#suffix' => '</div>'
-  );
-
-  // this form element is a tree, so that we don't puke all of the values into then node variable
-  // it is set as a tree, and keeps them in the $form_state['values']['relationship_table'] heading.
-  $form['relationships']['relationship_table'] = array(
-    '#type' => 'markup',
-    '#tree' => TRUE,
-    '#prefix' => '<div id="tripal-generic-edit-relationships-table">',
-    '#suffix' => '</div>',
-    '#theme' => 'tripal_core_relationships_form_table'
-  );
-
-  // Add relationships already attached to the node
-  //---------------------------------------------
-  /* Relationships can come to us in two ways:
-   *
-   * 1) In the form state in the $form_state['chado_relationships']. Data is in this field
-   *    when an AJAX call updates the form state or a validation error.
-   *
-   * 2) Directly from the database if the record already has _relationships associated.  This
-   *    data is only used the first time the form is loaded. On AJAX calls or validation
-   *    errors the fields on the form are populated from the $form_state['chado_relationships']
-   *    entry.
-   */
-  if (isset($form_state['chado_relationships'])) {
-    $existing_rels = $form_state['chado_relationships'];
-  }
-  else {
-    $existing_rels = chado_query(
-      "SELECT rel.*, base1.uniquename as object_name, base2.uniquename as subject_name, cvterm.name as type_name
-        FROM {".$details['relationship_table']."} rel
-        LEFT JOIN {".$details['base_table']."} base1 ON base1.".$details['base_foreign_key']." = rel.object_id
-        LEFT JOIN {".$details['base_table']."} base2 ON base2.".$details['base_foreign_key']." = rel.subject_id
-        LEFT JOIN {cvterm} cvterm ON cvterm.cvterm_id = rel.type_id
-        WHERE rel.object_id = :base_key_value OR rel.subject_id = :base_key_value",
-        array(':base_key_value' => $details['base_key_value'])
-    );
-  }
-
-  /* The format of the $existing_rels' array is either:
-   *
-   * From the chado_relationships array:
-   * $form_state['chado_relationships'] = array(
-   *   '[type_id]-[rank]' => array(
-   *     'object_id' => [the _relationship.object_id value],
-   *     'object_name' => [the base_table.uniquename value linked on base_foreign_key=object_id],
-   *     'subject_id' => [the _relationship.subject_id value],
-   *     'subject_name' => [the base_table.uniquename value linked on base_foreign_key=subject_id],
-   *     'type_id' => [the _relationship.type_id value],
-   *     'type_name' => [the cvterm.name value linked on type_id],
-   *     'rank' => [the _relationship.rank value],
-   *   ),
-   * );
-   *
-   * OR
-   * Populated from the database:
-   * $existing_rels = array(
-   *   0 => array(
-   *     'relationship_id' => [the _relationship.relationship_id value],
-   *     'object_id' => [the _relationship.object_id value],
-   *     'object_name' => [the base_table.uniquename value linked on base_foreign_key=object_id],
-   *     'subject_id' => [the _relationship.subject_id value],
-   *     'subject_name' => [the base_table.uniquename value linked on base_foreign_key=subject_id],
-   *     'type_id' => [the _relationship.type_id value],
-   *     'type_name' => [the cvterm.name value linked on type_id],
-   *     'rank' => [the _relationship.rank value],
-   *   ),
-   * );
-   *
-   * NOTE: The main difference is the key
-   *
-   * Loop on the array elements of the $existing_rels array and add
-   * an element to the form for each one.
-   */
-  foreach ($existing_rels as $relationship) {
-
-    $form['relationships']['relationship_table'][$relationship->type_id]['#type'] = 'markup';
-    $form['relationships']['relationship_table'][$relationship->type_id]['#type'] = '';
-
-    $form['relationships']['relationship_table'][$relationship->type_id][$relationship->rank]['#type'] = 'markup';
-    $form['relationships']['relationship_table'][$relationship->type_id][$relationship->rank]['#value'] = '';
-
-    $form['relationships']['relationship_table'][$relationship->type_id][$relationship->rank]['object_id'] = array(
-      '#type' => 'hidden',
-      '#value' => $relationship->object_id
-    );
-
-    $form['relationships']['relationship_table'][$relationship->type_id][$relationship->rank]['subject_id'] = array(
-      '#type' => 'hidden',
-      '#value' => $relationship->subject_id
-    );
-
-    $form['relationships']['relationship_table'][$relationship->type_id][$relationship->rank]['type_id'] = array(
-      '#type' => 'hidden',
-      '#value' => $relationship->type_id
-    );
-
-    $form['relationships']['relationship_table'][$relationship->type_id][$relationship->rank]['object_name'] = array(
-      '#type' => 'markup',
-      '#markup' => $relationship->object_name
-    );
-
-    $form['relationships']['relationship_table'][$relationship->type_id][$relationship->rank]['type_name'] = array(
-      '#type' => 'markup',
-      '#markup' => $relationship->type_name
-    );
-
-    $form['relationships']['relationship_table'][$relationship->type_id][$relationship->rank]['subject_name'] = array(
-      '#type' => 'markup',
-      '#markup' => $relationship->subject_name
-    );
-
-    $form['relationships']['relationship_table'][$relationship->type_id][$relationship->rank]['rank'] = array(
-      '#type' => 'markup',
-      '#markup' => $relationship->rank
-    );
-
-    $form['relationships']['relationship_table'][$relationship->type_id][$relationship->rank]['rel_action'] = array(
-      '#type' => 'submit',
-      '#value' => t('Remove'),
-      '#name' => "rel_remove-".$relationship->type_id.'-'.$relationship->rank,
-      '#ajax' => array(
-        'callback' => 'tripal_core_relationships_form_ajax_update',
-        'wrapper' => 'tripal-generic-edit-relationships-table',
-        'effect'   => 'fade',
-        'method'   => 'replace',
-        'prevent'  => 'click'
-      ),
-      // When this button is clicked, the form will be validated and submitted.
-      // Therefore, we set custom submit and validate functions to override the
-      // default node form submit.  In the validate function we validate only the
-      // relationship fields and in the submit we remove the indicated relationship
-      // from the chado_relationships array. In order to keep validate errors
-      // from the node form validate and Drupal required errors for non-relationship fields
-      // preventing the user from removing relationships we set the #limit_validation_errors below
-      '#validate' => array('tripal_core_relationships_form_remove_button_validate'),
-      '#submit' => array('tripal_core_relationships_form_remove_button_submit'),
-      // Limit the validation of the form upon clicking this button to the relationship_table tree
-      // No other fields will be validated (ie: no fields from the main form or any other api
-      // added form).
-      '#limit_validation_errors' => array(
-        array('relationship_table')  // Validate all fields within $form_state['values']['relationship_table']
-      )
-    );
-  }
-
-  $form['relationships']['relationship_table']['new']['object_name'] = array(
-    '#type' => 'textfield',
-  );
-
-  $form['relationships']['relationship_table']['new']['object_is_current'] = array(
-    '#type' => 'checkbox',
-    '#title' => t('Current '.$details['nodetype']),
-  );
-
-  $form['relationships']['relationship_table']['new']['type_name'] = array(
-    '#type' => 'select',
-    '#options' => $type_options,
-  );
-
-  $form['relationships']['relationship_table']['new']['subject_name'] = array(
-    '#type' => 'textfield',
-  );
-
-  $form['relationships']['relationship_table']['new']['subject_is_current'] = array(
-    '#type' => 'checkbox',
-    '#title' => t('Current '.$details['nodetype']),
-  );
-
-  $form['relationships']['relationship_table']['new']['rank'] = array(
-    '#type' => 'markup',
-    '#markup' => ''
-  );
-
-  $form['relationships']['relationship_table']['new']['rel_action'] = array(
-    '#type' => 'submit',
-    '#value' => t('Add'),
-    '#name' => 'rel_add',
-    '#ajax' => array(
-      'callback' => 'tripal_core_relationships_form_ajax_update',
-      'wrapper' => 'tripal-generic-edit-relationships-table',
-      'effect'   => 'fade',
-      'method'   => 'replace',
-      'prevent'  => 'click'
-    ),
-    // When this button is clicked, the form will be validated and submitted.
-    // Therefore, we set custom submit and validate functions to override the
-    // default node form submit.  In the validate function we validate only the
-    // relationship fields and in the submit we add them to the chado_relationships
-    // array. In order to keep validate errors from the node form validate and Drupal
-    // required errors for non-relationship fields preventing the user from adding relationships we
-    // set the #limit_validation_errors below
-    '#validate' => array('tripal_core_relationships_form_add_button_validate'),
-    '#submit' => array('tripal_core_relationships_form_add_button_submit'),
-    // Limit the validation of the form upon clicking this button to the relationship_table tree
-    // No other fields will be validated (ie: no fields from the main form or any other api
-    // added form).
-    '#limit_validation_errors' => array(
-      array('relationship_table')  // Validate all fields within $form_state['values']['relationship_table']
-    )
-  );
-
-}
-
-/**
- * Validate the user input for creating a new relationship
- * Called by the add button in tripal_core_relationships_form
- *
- * @ingroup tripal_relationships_api
- */
-function tripal_core_relationships_form_add_button_validate($form, &$form_state) {
-
-  $details = unserialize($form_state['values']['rel_details']);
-
-  // At least one of the participants must be the current node
-  if (!($form_state['values']['relationship_table']['new']['subject_is_current'] OR $form_state['values']['relationship_table']['new']['object_is_current'])) {
-    // If the checkbox isn't set then check to see if either has the same uniquename as the node
-    if ($form_state['values']['relationship_table']['new']['subject_name'] == $form_state['values']['uniquename']) {
-      $form_state['values']['relationship_table']['new']['subject_is_current'] = 1;
-      form_set_error('subject_is_current', 'To set the current '.$details['nodetype'].', select the
-        checkbox. You entered the unique name of the current '.$details['nodetype'].' as the subject,
-        is this what you meant to do?');
-    }
-    elseif ($form_state['values']['relationship_table']['new']['subject_name'] == $form_state['values']['uniquename']) {
-      $form_state['values']['relationship_table']['new']['object_is_current'] = 1;
-      form_set_error('subject_is_current', 'To set the current '.$details['nodetype'].', select the
-        checkbox. You entered the unique name of the current '.$details['nodetype'].' as the subject,
-        is this what you meant to do?');
-    }
-    else {
-      form_set_error('object_is_current', 'At least one member of the relationship must be
-        the current '.$details['nodetype'].'. This is specified by checking the "Current '.$details['nodetype'].'"
-        checkbox for either the subject or object.');
-    }
-  }
-
-  // The non-current uniquename must be exist in the base table (subject)
-  if (!($form_state['values']['relationship_table']['new']['subject_is_current'])) {
-    $result = tripal_core_chado_select(
-      $details['base_table'],
-      array($details['base_foreign_key']),
-      array('uniquename' => $form_state['values']['relationship_table']['new']['subject_name'])
-    );
-    if (!isset($result[0])) {
-      form_set_error('subject_name', 'The subject must be the unique name of an
-        existing '.$details['nodetype'].' unless the "Current '.$details['nodetype'].'" checkbox is selected');
-    }
-    else {
-      $form_state['values']['relationship_table']['new']['subject_id'] = $result[0]->{$details['base_foreign_key']};
-    }
-  }
-
-  // The non-current uniquename must exist in the base table (object)
-  if (!($form_state['values']['relationship_table']['new']['object_is_current'])) {
-    $result = tripal_core_chado_select(
-      $details['base_table'],
-      array($details['base_foreign_key']),
-      array('uniquename' => $form_state['values']['relationship_table']['new']['object_name'])
-    );
-    if (!isset($result[0])) {
-      form_set_error('object_name', 'The object must be the unique name of an
-        existing '.$details['nodetype'].' unless the "Current '.$details['nodetype'].'" checkbox is selected');
-    }
-    else {
-      $form_state['values']['relationship_table']['new']['object_id'] = $result[0]->{$details['base_foreign_key']};
-    }
-  }
-
-  // The type must be a valid cvterm
-  if ($form_state['values']['relationship_table']['new']['type_name']) {
-    $form_state['values']['relationship_table']['new']['type_id'] = $form_state['values']['relationship_table']['new']['type_name'];
-    $result = tripal_core_chado_select(
-      'cvterm',
-      array('name'),
-      array('cvterm_id' => $form_state['values']['relationship_table']['new']['type_id'])
-    );
-    if (!isset($result[0])) {
-      form_set_error('type_id', 'The select type is not a valid controlled vocabulary term.');
-    }
-    else {
-      $form_state['values']['relationship_table']['new']['type_name'] = $result[0]->name;
-    }
-  }
-  else {
-    form_set_error('type_id', 'Please select a type of relationship');
-  }
-}
-
-/**
- * Called by the add button in tripal_core_relationships_form
- *
- * Create an array of additional relationships in the form state. This array will then be
- * used to rebuild the form in subsequent builds
- *
- * @ingroup tripal_relationships_api
- */
-function tripal_core_relationships_form_add_button_submit(&$form, &$form_state) {
-
-  $details = unserialize($form_state['values']['rel_details']);
-
-  // if the chado_relationships array is not set then this is the first time modifying the
-  // relationship table. this means we need to include all the relationships from the db
-  if (!isset($form_state['chado_relationships'])) {
-    tripal_core_relationships_form_create_relationship_formstate_array($form, $form_state);
-  }
-
-  // get details for the new relationship
-  if ($form_state['values']['relationship_table']['new']['subject_is_current']) {
-
-    $relationship = array(
-      'type_id' => $form_state['values']['relationship_table']['new']['type_id'],
-      'object_id' => $form_state['values']['relationship_table']['new']['object_id'],
-      'subject_id' => $form_state['values'][ $details['base_foreign_key'] ],
-      'type_name' => $form_state['values']['relationship_table']['new']['type_name'],
-      'object_name' => $form_state['values']['relationship_table']['new']['object_name'],
-      'subject_name' => $form_state['values']['uniquename'],
-      'rank' => '0'
-    );
-  }
-  else {
-    $relationship = array(
-      'type_id' => $form_state['values']['relationship_table']['new']['type_id'],
-      'object_id' => $form_state['values'][ $details['base_foreign_key'] ],
-      'subject_id' => $form_state['values']['relationship_table']['new']['subject_id'],
-      'type_name' => $form_state['values']['relationship_table']['new']['type_name'],
-      'object_name' => $form_state['values']['uniquename'],
-      'subject_name' => $form_state['values']['relationship_table']['new']['subject_name'],
-      'rank' => '0'
-    );
-  }
-
-  // get max rank
-  $rank = tripal_core_get_max_chado_rank(
-    $details['relationship_table'],
-    array(
-      'subject_id' => $relationship['subject_id'],
-      'type_id' => $relationship['type_id'],
-      'object_id' => $relationship['object_id'],
-    )
-  );
-  $relationship['rank'] = strval($rank + 1);
-
-  $key = $relationship['type_id'] . '-' . $relationship['rank'];
-  $form_state['chado_relationships'][$key] = (object) $relationship;
-
-  $form_state['rebuild'] = TRUE;
-}
-
-/**
- * There is no user input for the remove buttons so there is no need to validate
- * However, both a submit & validate need to be specified so this is just a placeholder
- *
- * Called by the many remove buttons in tripal_core_relationships_form
- *
- * @ingroup tripal_relationships_api
- */
-function tripal_core_relationships_form_remove_button_validate($form, $form_state) {
-  // No Validation needed for remove
-}
-
-/**
- * Remove the correct relationship from the form
- * Called by the many remove buttons in tripal_core_relationships_form
- *
- * @ingroup tripal_relationships_api
- */
-function tripal_core_relationships_form_remove_button_submit(&$form, &$form_state) {
-
-  // if the chado_relationships array is not set then this is the first time modifying the
-  // relationship table. this means we need to include all the relationships from the db
-  if (!isset($form_state['chado_relationships'])) {
-    tripal_core_relationships_form_create_relationship_formstate_array($form, $form_state);
-  }
-
-  // @TODO: Test that this actually works
-
-  // remove the specified relationship from the form relationship table
-  if(preg_match('/rel_remove-([^-]+-[^-]+)/',$form_state['triggering_element']['#name'],$match)) {
-    $key = $match[1];
-    if (array_key_exists($key, $form_state['chado_relationships'])) {
-      unset($form_state['chado_relationships'][$key]);
-    }
-  }
-
-  $form_state['rebuild'] = TRUE;
-}
-
-/**
- * Ajax function which returns the section of the form to be re-rendered
- *
- * @ingroup tripal_relationships_api
- */
-function tripal_core_relationships_form_ajax_update($form, $form_state) {
-  return $form['relationships']['relationship_table'];
-}
-
-/**
- * Creates an array in form_state containing the existing relationships. This array is
- * then modified by the add/remove buttons and used as a source for rebuilding the form.
- *
- * $form_state['chado_relationships'] = array(
- *   '[type_id]-[rank]' => array(
- *     'object_id' => [the _relationship.object_id value],
- *     'object_name' => [the base_table.uniquename value linked on base_foreign_key=object_id],
- *     'subject_id' => [the _relationship.subject_id value],
- *     'subject_name' => [the base_table.uniquename value linked on base_foreign_key=subject_id],
- *     'type_id' => [the _relationship.type_id value],
- *     'type_name' => [the cvterm.name value linked on type_id],
- *     'rank' => [the _relationship.rank value],
- *   ),
- * );
- *
- * @ingroup tripal_relationships_api
- */
-function tripal_core_relationships_form_create_relationship_formstate_array($form, &$form_state) {
-
-  $form_state['chado_relationships'] = array();
-
-  foreach (element_children($form['relationships']['relationship_table']) as $type_id) {
-    if ($type_id != 'new') {
-      foreach (element_children($form['relationships']['relationship_table'][$type_id]) as $rank) {
-          $element = $form['relationships']['relationship_table'][$type_id][$rank];
-          $rel = array(
-            'type_id' => $element['type_id']['#value'],
-            'object_id' => $element['object_id']['#value'],
-            'subject_id' => $element['subject_id']['#value'],
-            'type_name' => $element['type_name']['#markup'],
-            'object_name' => $element['object_name']['#markup'],
-            'subject_name' => $element['subject_name']['#markup'],
-            'rank' => $element['rank']['#markup']
-          );
-          $key = $rel['type_id'] . '-' . $rel['rank'];
-          $form_state['chado_relationships'][$key] = (object) $rel;
-      }
-    }
-  }
-}
-
-/**
- * Function to theme the add/remove relationships form into a table
- *
- * @ingroup tripal_relationships_api
- */
-function theme_tripal_core_relationships_form_table($variables) {
-  $element = $variables['element'];
-
-  $header = array(
-    'object_name' => t('Object Unique Name'),
-    'type_name' => t('Type'),
-    'subject_name' => t('Subject Unique Name'),
-    'rank' => t('Rank'),
-    'rel_action' => t('Action')
-  );
-
-  $rows = array();
-  foreach (element_children($element) as $type_id) {
-    if ($type_id == 'new') {
-      $row = array();
-
-        $row['data'] = array();
-        foreach ($header as $fieldname => $title) {
-          if ($fieldname == 'subject_name') {
-            $row['data'][] = drupal_render($element[$type_id][$fieldname]) . drupal_render($element[$type_id]['subject_is_current']);
-          }
-          elseif ($fieldname == 'object_name') {
-            $row['data'][] = drupal_render($element[$type_id][$fieldname]) . drupal_render($element[$type_id]['object_is_current']);
-          }
-          else {
-            $row['data'][] = drupal_render($element[$type_id][$fieldname]);
-          }
-        }
-        $rows[] = $row;
-    }
-    else {
-      foreach (element_children($element[$type_id]) as $rank) {
-        $row = array();
-
-        $row['data'] = array();
-        foreach ($header as $fieldname => $title) {
-          $row['data'][] = drupal_render($element[$type_id][$rank][$fieldname]);
-        }
-        $rows[] = $row;
-      }
-    }
-  }
-
-  return theme('table', array(
-    'header' => $header,
-    'rows' => $rows
-  ));
-}
-
-/**
- * This function is used in a hook_insert, hook_update for a node form
- * when the relationships form has been added to the form.  It retrieves all of the relationships
- * and returns them in an array of the format:
- *
- *   $relationships[<type_id>][<rank>] = array(
- *         'subject_id' => <subject_id>,
- *         'object_id'  => <object_id>,
- *   );
- *
- * This array can then be used for inserting or updating relationships manually
- *
- * @param $node
- *
- * @return
- *   A relationship array
- *
- * @ingroup tripal_relationships_api
- */
-function tripal_core_relationships_form_retreive($node) {
-  $rels = array();
-
-  if (isset($node->rel_table)) {
-    foreach ($node->rel_table as $type_id => $elements) {
-      if ($type_id != 'new') {
-        foreach ($elements as $rank => $relationships) {
-          $rels[$type_id][$rank]['subject_id'] = $relationships['subject_id'];
-          $rels[$type_id][$rank]['object_id'] = $relationships['object_id'];
-        }
-      }
-    }
-  }
-
-  return $rels;
-}
-
-/**
- * This function is used in hook_insert or hook_update and handles inserting of
- * relationships between the current nodetype and other memebers of the same nodetype
- *
- * @param $node
- *    The node passed into hook_insert & hook_update
- * @param $relationship_table
- *    The name of the _relationship linking table (ie: feature_relationship)
- * @param $current_id
- *    The value of the foreign key (ie: 445, if there exists a feature where feature_id=445)
- *
- * @ingroup tripal_relationships_api
- */
-function tripal_core_relationships_form_update_relationships($node, $relationship_table, $current_id) {
-
-  if (isset($node->rel_table) AND ($current_id > 0)) {
-    // First remove existing relationships links
-    tripal_core_chado_delete($relationship_table, array('subject_id' => $current_id));
-    tripal_core_chado_delete($relationship_table, array('object_id' => $current_id));
-
-    // Add back in dbxref links and insert dbxrefs as needed
-    $relationships = tripal_core_relationships_form_retreive($node);
-    foreach ($relationships as $type_id => $ranks) {
-      foreach ($ranks as $rank => $element) {
-
-        // add relationship
-        $success_link = tripal_core_chado_insert(
-          $relationship_table,
-          array(
-            'subject_id' => $element['subject_id'],
-            'type_id' => $type_id,
-            'object_id' => $element['object_id'],
-            'rank' => $rank
-          )
-        );
-
-      }
-    }
-  }
-}