Browse Source

Merge branch '7.x-3.x' into 7.x-3.x-small_fixes

Lacey-Anne Sanderson 6 years ago
parent
commit
907aba4d19
100 changed files with 8141 additions and 2522 deletions
  1. 2 2
      .gitignore
  2. 65 22
      .travis.yml
  3. 8 5
      README.md
  4. 4 1
      composer.json
  5. 1928 0
      composer.lock
  6. 87 2
      legacy/tripal_feature/theme/tripal_feature.theme.inc
  7. 0 44
      legacy/tripal_pub/api/tripal_pub.DEPRECATED.inc
  8. 24 2
      phpunit.xml
  9. 73 0
      tests/DataFactory.php
  10. 28 0
      tests/DatabaseSeeders/UsersTableSeeder.php
  11. 2 37
      tests/bootstrap.php
  12. 2 0
      tests/example.env
  13. 6 7
      tests/tripal/api/TripalJobsApiTest.php
  14. 71 0
      tests/tripal_chado/api/TripalChadoAPITest.php
  15. 19 0
      tests/tripal_chado/api/TripalChadoCustomTablesAPITest.php
  16. 113 0
      tests/tripal_chado/api/TripalChadoOrganismAPITest.php
  17. 28 4
      tripal/api/tripal.DEPRECATED.api.inc
  18. 21 0
      tripal/api/tripal.d3js.api.inc
  19. 99 81
      tripal/api/tripal.entities.api.inc
  20. 47 30
      tripal/api/tripal.fields.api.inc
  21. 123 2
      tripal/api/tripal.files.api.inc
  22. 5 6
      tripal/api/tripal.importer.api.inc
  23. 14 11
      tripal/api/tripal.jobs.api.inc
  24. 16 12
      tripal/api/tripal.notice.api.inc
  25. 150 0
      tripal/api/tripal.quotas.api.inc
  26. 51 13
      tripal/api/tripal.terms.api.inc
  27. 3 2
      tripal/api/tripal.upload.api.inc
  28. 4 10
      tripal/includes/TripalFieldDownloaders/TripalFieldDownloader.inc
  29. 568 0
      tripal/includes/tripal.admin_files.inc
  30. 2 2
      tripal/includes/tripal.extensions.inc
  31. 18 0
      tripal/includes/tripal.fields.inc
  32. 33 7
      tripal/includes/tripal.importer.inc
  33. 85 30
      tripal/includes/tripal.upload.inc
  34. 328 0
      tripal/includes/tripal.user.inc
  35. 84 0
      tripal/tripal.install
  36. 233 61
      tripal/tripal.module
  37. 45 0
      tripal/tripal_views_query.inc
  38. 30 24
      tripal/views_handlers/tripal_views_handler_filter_string.inc
  39. 18 11
      tripal_bulk_loader/api/tripal_bulk_loader.api.templates.inc
  40. 10 10
      tripal_chado/api/generate_chado_schema_file.php
  41. 37 32
      tripal_chado/api/modules/tripal_chado.analysis.api.inc
  42. 18 15
      tripal_chado/api/modules/tripal_chado.contact.api.inc
  43. 199 168
      tripal_chado/api/modules/tripal_chado.cv.api.inc
  44. 150 129
      tripal_chado/api/modules/tripal_chado.db.api.inc
  45. 115 687
      tripal_chado/api/modules/tripal_chado.feature.api.inc
  46. 1522 0
      tripal_chado/api/modules/tripal_chado.module.DEPRECATED.api.inc
  47. 60 52
      tripal_chado/api/modules/tripal_chado.organism.api.inc
  48. 50 41
      tripal_chado/api/modules/tripal_chado.phylotree.api.inc
  49. 134 111
      tripal_chado/api/modules/tripal_chado.pub.api.inc
  50. 55 43
      tripal_chado/api/modules/tripal_chado.stock.api.inc
  51. 390 0
      tripal_chado/api/tripal_chado.DEPRECATED.api.inc
  52. 28 5
      tripal_chado/api/tripal_chado.api.inc
  53. 47 46
      tripal_chado/api/tripal_chado.custom_tables.api.inc
  54. 20 8
      tripal_chado/api/tripal_chado.migrate.api.inc
  55. 62 58
      tripal_chado/api/tripal_chado.mviews.api.inc
  56. 43 37
      tripal_chado/api/tripal_chado.property.api.inc
  57. 278 250
      tripal_chado/api/tripal_chado.query.api.inc
  58. 14 7
      tripal_chado/api/tripal_chado.schema.api.inc
  59. 35 9
      tripal_chado/api/tripal_chado.semweb.api.inc
  60. 210 175
      tripal_chado/api/tripal_chado.variables.api.inc
  61. 2 2
      tripal_chado/includes/TripalFields/ChadoField.inc
  62. 12 12
      tripal_chado/includes/TripalFields/chado_linker__contact/chado_linker__contact.inc
  63. 3 3
      tripal_chado/includes/TripalFields/chado_linker__contact/chado_linker__contact_formatter.inc
  64. 1 1
      tripal_chado/includes/TripalFields/chado_linker__contact/chado_linker__contact_widget.inc
  65. 14 4
      tripal_chado/includes/TripalFields/chado_linker__prop/chado_linker__prop.inc
  66. 5 0
      tripal_chado/includes/TripalFields/chado_linker__prop/chado_linker__prop_formatter.inc
  67. 1 1
      tripal_chado/includes/TripalFields/chado_linker__prop/chado_linker__prop_widget.inc
  68. 2 2
      tripal_chado/includes/TripalFields/data__accession/data__accession.inc
  69. 2 2
      tripal_chado/includes/TripalFields/data__accession/data__accession_widget.inc
  70. 5 5
      tripal_chado/includes/TripalFields/data__sequence/data__sequence.inc
  71. 16 16
      tripal_chado/includes/TripalFields/data__sequence_coordinates/data__sequence_coordinates.inc
  72. 4 4
      tripal_chado/includes/TripalFields/data__sequence_coordinates/data__sequence_coordinates_formatter.inc
  73. 1 1
      tripal_chado/includes/TripalFields/go__gene_expression/go__gene_expression.inc
  74. 12 12
      tripal_chado/includes/TripalFields/local__contact/local__contact.inc
  75. 3 3
      tripal_chado/includes/TripalFields/local__contact/local__contact_formatter.inc
  76. 1 1
      tripal_chado/includes/TripalFields/local__contact/local__contact_widget.inc
  77. 12 12
      tripal_chado/includes/TripalFields/local__source_data/local__source_data.inc
  78. 3 3
      tripal_chado/includes/TripalFields/local__source_data/local__source_data_formatter.inc
  79. 19 19
      tripal_chado/includes/TripalFields/obi__organism/obi__organism.inc
  80. 1 1
      tripal_chado/includes/TripalFields/obi__organism/obi__organism_widget.inc
  81. 24 24
      tripal_chado/includes/TripalFields/ogi__location_on_map/ogi__location_on_map.inc
  82. 13 13
      tripal_chado/includes/TripalFields/sbo__database_cross_reference/sbo__database_cross_reference.inc
  83. 5 5
      tripal_chado/includes/TripalFields/sbo__database_cross_reference/sbo__database_cross_reference_formatter.inc
  84. 1 1
      tripal_chado/includes/TripalFields/sbo__database_cross_reference/sbo__database_cross_reference_widget.inc
  85. 5 5
      tripal_chado/includes/TripalFields/sbo__relationship/sbo__relationship.inc
  86. 7 7
      tripal_chado/includes/TripalFields/sbo__relationship/sbo__relationship_widget.inc
  87. 2 2
      tripal_chado/includes/TripalFields/schema__additional_type/schema__additional_type_widget.inc
  88. 1 1
      tripal_chado/includes/TripalFields/schema__publication/schema__publication.inc
  89. 1 1
      tripal_chado/includes/TripalFields/schema__publication/schema__publication_widget.inc
  90. 13 13
      tripal_chado/includes/TripalFields/sio__annotation/sio__annotation.inc
  91. 3 2
      tripal_chado/includes/TripalFields/sio__annotation/sio__annotation_formatter.inc
  92. 10 10
      tripal_chado/includes/TripalFields/sio__annotation/sio__annotation_widget.inc
  93. 1 1
      tripal_chado/includes/TripalFields/sio__references/sio__references.inc
  94. 1 1
      tripal_chado/includes/TripalFields/sio__vocabulary/sio__vocabulary_widget.inc
  95. 2 2
      tripal_chado/includes/TripalFields/so__cds/so__cds.inc
  96. 8 8
      tripal_chado/includes/TripalFields/taxrank__infraspecific_taxon/taxrank__infraspecific_taxon.inc
  97. 2 2
      tripal_chado/includes/TripalFields/taxrank__infraspecific_taxon/taxrank__infraspecific_taxon_formatter.inc
  98. 2 2
      tripal_chado/includes/TripalFields/taxrank__infraspecific_taxon/taxrank__infraspecific_taxon_widget.inc
  99. 2 2
      tripal_chado/includes/TripalFields/uo__unit/uo__unit_widget.inc
  100. 5 5
      tripal_chado/includes/TripalImporter/GFF3Importer.inc

+ 2 - 2
.gitignore

@@ -1,4 +1,4 @@
 .DS_Store
-composer.lock
-vendor/*
+.idea/
+vendor/
 tests/.env

+ 65 - 22
.travis.yml

@@ -2,36 +2,79 @@ language: php
 
 services:
   - docker
+  - postgres
 
 sudo: required
 
+php:
+  - 5.6
+  - 7.0
+  - 7.1
+
+env:
+  - BASE_URL="http://localhost:8080"
+
+install:
+  - composer global require drush/drush:8
+
 before_script:
-  - docker pull statonlab/drupal7
+  - docker pull statonlab/tripal2
+  - psql -c "create database test_db encoding 'utf-8';" -U postgres
+  - psql -c "alter role postgres with password 'dbpass';" -U postgres
+  - cd ..
+
+  # Set additional environment variables
+  - export PATH="$HOME/.config/composer/vendor/bin:$PATH"
+  - export DRUPAL_ROOT="$(pwd)/drupal"
+
+  # Download and install Drupal
+  - drush dl drupal-7 -y
+  - mv drupal-7* drupal
+  - cd drupal
+  - drush si -y --db-url='pgsql://postgres:dbpass@localhost:5432/test_db'
+                --account-name='admin'
+                --account-pass='admin_pass'
+                --site-mail='admin@example.com'
+                --site-name='Tripal 3'
+
+  # Download Dependencies
+  - drush dl -y field_group, field_group_table, field_formatter_class, field_formatter_settings, ctools, date, devel,
+                ds, link, entity, libraries, redirect, token, uuid, jquery_update, views, webform
+
+  # Enable dependencies
+  - drush en -y field_group, field_group_table, field_formatter_class, field_formatter_settings, ctools, date, devel,
+              ds, link, entity, libraries, redirect, token uuid, jquery_update, views, webform
+
+  # Run the drush server
+  - drush runserver localhost:8080 &
 
 script:
-  # Set branch name
-  - export REPO=$(if [ "$TRAVIS_PULL_REQUEST" == "false" ]; then echo $TRAVIS_REPO_SLUG; else echo $TRAVIS_PULL_REQUEST_SLUG; fi)
-  - export BRANCH=$(if [ "$TRAVIS_PULL_REQUEST" == "false" ]; then echo $TRAVIS_BRANCH; else echo $TRAVIS_PULL_REQUEST_BRANCH; fi)
-  #  Travis does a shallow clone and we need a full clone to test Tripal v2 to v3 upgrade
-  - cd .. && rm -rf tripal && git clone https://github.com/$REPO.git tripal && cd tripal
-  - git checkout $BRANCH
-  # Test tripal 3 installation
-  - docker run -it -d --rm --name tripal3 -v "$(pwd)":/modules/tripal statonlab/drupal7
-  - sleep 15
-  - docker exec -it tripal3 drush en -y tripal tripal_chado tripal_chado_views tripal_ds tripal_ws
+  # Link our repo to the modules directory
+  - mv ../tripal sites/all/modules/tripal
+
+  # Run a docker container with tripal 2 pre-installed
+  - docker run -it -d --rm --name tripal2 -v "$(pwd)/tripal":/modules/tripal statonlab/tripal2
+
+  # Apply patches
+  - wget --no-check-certificate https://drupal.org/files/drupal.pgsql-bytea.27.patch
+  - patch -p1 < drupal.pgsql-bytea.27.patch
+  - cd sites/all/modules/views
+  - patch -p1 < ../tripal/tripal_chado_views/views-sql-compliant-three-tier-naming-1971160-30.patch
+  - cd ../tripal
+
+  # Install Tripal
+  - drush en -y tripal tripal_chado tripal_chado_views tripal_ds tripal_ws
+  - drush eval "module_load_include('inc', 'tripal_chado', 'includes/tripal_chado.install'); tripal_chado_load_drush_submit('Install Chado v1.3');"
+  - drush trp-run-jobs --username=admin
+
   # Prepare Chado
-  - docker exec -it tripal3 drush eval "module_load_include('inc', 'tripal_chado', 'includes/tripal_chado.install'); tripal_chado_load_drush_submit('Install Chado v1.3');"
-  - docker exec -it tripal3 drush trp-run-jobs --username=admin
-  # Prepare Drupal
-  - docker exec -it tripal3 drush eval "module_load_include('inc', 'tripal_chado', 'includes/setup/tripal_chado.setup'); tripal_chado_prepare_drush_submit();"
-  - docker exec -it tripal3 drush trp-run-jobs --username=admin
+  - drush eval "module_load_include('inc', 'tripal_chado', 'includes/setup/tripal_chado.setup'); tripal_chado_prepare_drush_submit();"
+  - drush trp-run-jobs --username=admin
+
   # Run PHPUnit tests
-  - docker exec -it tripal3 bash -c "cd /modules/tripal && composer install && DRUPAL_ROOT=/var/www/html ./vendor/bin/phpunit"
+  - composer update
+  - ./vendor/bin/phpunit
+
   # Test Tripal v2 to v3 upgrade steps
-  - git checkout 7.x-2.x
-  - docker run -it -d --rm --name tripal2 -v "$(pwd)":/modules/tripal statonlab/drupal7
-  - sleep 15
-  - docker exec -it tripal2 drush en -y tripal_core
   - docker exec -it tripal2 drush pm-disable tripal_core -y
-  - git checkout $BRANCH
   - docker exec -it tripal2 drush en -y tripal

+ 8 - 5
README.md

@@ -66,7 +66,7 @@ http://tripal.info/tutorials/v2.0/installation
 
 
 # Upgrade from Tripal v2.x to v3.x
-Note:  Upgrade can only be performed using 'drush' command.
+Note:  Upgrade can only be performed using the `drush` command.
 
 Note: Deprecated API functions from Tripal v1.x have been removed from Tripal
 v3.  Therefore, use of deprecated API functions in templates or custom 
@@ -80,24 +80,27 @@ Step 1: Put the site in maintenance mode.
 Step 2: Disable tripal modules. Disabling the core module will disable all
 other Tripal modules:
 
-  drush pm-disable tripal_core
+  `drush pm-disable tripal_core`
   
 Step 3: Remove old Tripal v2 package and replace with Tripal v3 package
 Step 4: Enable the tripal module
 
-  drush pm-enable tripal
+  `drush pm-enable tripal`
  
 Step 5: Enable the tripal_chado module  
 
-  drush pm-enable tripal_chado
+  `drush pm-enable tripal_chado`
   
 Step 6:  Tripal v2 modules are now called 'legacy modules'. these are the
 modules that were disabled in step #2.  For backwards compatibility, you 
 should re-enable these modules:
 
+```
   drush pm-enable tripal_core, tripal_views, tripal_db, tripal_cv, \
     tripal_analysis, tripal_organism, tripal_feature, tripal_pub, \
     tripal_stock
+```
+
 
 Be sure to enable any additional modules not included in the example
 drush command above.
@@ -117,7 +120,7 @@ Developer's Handbook for additional details.
 
 # Development Testing
 
-To run PHP unit tests on your local system, simply create a `.env` file in your `/Tests/` directory that defines the `DRUPAL_ROOT` variable, for example 
+To run PHP unit tests on your local system, run `composer install` to install developer-specific requirements.  Next, create a `.env` file in your `/Tests/` directory that defines the `DRUPAL_ROOT` variable, for example 
 
 ```
 DRUPAL_ROOT=/var/www/html

+ 4 - 1
composer.json

@@ -1,5 +1,8 @@
 {
   "require-dev": {
-    "phpunit/phpunit": "^7"
+    "doctrine/instantiator": "1.0.*"
+  },
+  "require": {
+    "statonlab/tripal-test-suite": "1.0.*"
   }
 }

+ 1928 - 0
composer.lock

@@ -0,0 +1,1928 @@
+{
+    "_readme": [
+        "This file locks the dependencies of your project to a known state",
+        "Read more about it at https://getcomposer.org/doc/01-basic-usage.md#installing-dependencies",
+        "This file is @generated automatically"
+    ],
+    "content-hash": "6b7fddf464c4d4d28fc77f805792807d",
+    "packages": [
+        {
+            "name": "doctrine/instantiator",
+            "version": "1.0.5",
+            "source": {
+                "type": "git",
+                "url": "https://github.com/doctrine/instantiator.git",
+                "reference": "8e884e78f9f0eb1329e445619e04456e64d8051d"
+            },
+            "dist": {
+                "type": "zip",
+                "url": "https://api.github.com/repos/doctrine/instantiator/zipball/8e884e78f9f0eb1329e445619e04456e64d8051d",
+                "reference": "8e884e78f9f0eb1329e445619e04456e64d8051d",
+                "shasum": ""
+            },
+            "require": {
+                "php": ">=5.3,<8.0-DEV"
+            },
+            "require-dev": {
+                "athletic/athletic": "~0.1.8",
+                "ext-pdo": "*",
+                "ext-phar": "*",
+                "phpunit/phpunit": "~4.0",
+                "squizlabs/php_codesniffer": "~2.0"
+            },
+            "type": "library",
+            "extra": {
+                "branch-alias": {
+                    "dev-master": "1.0.x-dev"
+                }
+            },
+            "autoload": {
+                "psr-4": {
+                    "Doctrine\\Instantiator\\": "src/Doctrine/Instantiator/"
+                }
+            },
+            "notification-url": "https://packagist.org/downloads/",
+            "license": [
+                "MIT"
+            ],
+            "authors": [
+                {
+                    "name": "Marco Pivetta",
+                    "email": "ocramius@gmail.com",
+                    "homepage": "http://ocramius.github.com/"
+                }
+            ],
+            "description": "A small, lightweight utility to instantiate objects in PHP without invoking their constructors",
+            "homepage": "https://github.com/doctrine/instantiator",
+            "keywords": [
+                "constructor",
+                "instantiate"
+            ],
+            "time": "2015-06-14T21:17:01+00:00"
+        },
+        {
+            "name": "fzaninotto/faker",
+            "version": "v1.7.1",
+            "source": {
+                "type": "git",
+                "url": "https://github.com/fzaninotto/Faker.git",
+                "reference": "d3ed4cc37051c1ca52d22d76b437d14809fc7e0d"
+            },
+            "dist": {
+                "type": "zip",
+                "url": "https://api.github.com/repos/fzaninotto/Faker/zipball/d3ed4cc37051c1ca52d22d76b437d14809fc7e0d",
+                "reference": "d3ed4cc37051c1ca52d22d76b437d14809fc7e0d",
+                "shasum": ""
+            },
+            "require": {
+                "php": "^5.3.3 || ^7.0"
+            },
+            "require-dev": {
+                "ext-intl": "*",
+                "phpunit/phpunit": "^4.0 || ^5.0",
+                "squizlabs/php_codesniffer": "^1.5"
+            },
+            "type": "library",
+            "extra": {
+                "branch-alias": {
+                    "dev-master": "1.8-dev"
+                }
+            },
+            "autoload": {
+                "psr-4": {
+                    "Faker\\": "src/Faker/"
+                }
+            },
+            "notification-url": "https://packagist.org/downloads/",
+            "license": [
+                "MIT"
+            ],
+            "authors": [
+                {
+                    "name": "François Zaninotto"
+                }
+            ],
+            "description": "Faker is a PHP library that generates fake data for you.",
+            "keywords": [
+                "data",
+                "faker",
+                "fixtures"
+            ],
+            "time": "2017-08-15T16:48:10+00:00"
+        },
+        {
+            "name": "guzzlehttp/guzzle",
+            "version": "6.3.3",
+            "source": {
+                "type": "git",
+                "url": "https://github.com/guzzle/guzzle.git",
+                "reference": "407b0cb880ace85c9b63c5f9551db498cb2d50ba"
+            },
+            "dist": {
+                "type": "zip",
+                "url": "https://api.github.com/repos/guzzle/guzzle/zipball/407b0cb880ace85c9b63c5f9551db498cb2d50ba",
+                "reference": "407b0cb880ace85c9b63c5f9551db498cb2d50ba",
+                "shasum": ""
+            },
+            "require": {
+                "guzzlehttp/promises": "^1.0",
+                "guzzlehttp/psr7": "^1.4",
+                "php": ">=5.5"
+            },
+            "require-dev": {
+                "ext-curl": "*",
+                "phpunit/phpunit": "^4.8.35 || ^5.7 || ^6.4 || ^7.0",
+                "psr/log": "^1.0"
+            },
+            "suggest": {
+                "psr/log": "Required for using the Log middleware"
+            },
+            "type": "library",
+            "extra": {
+                "branch-alias": {
+                    "dev-master": "6.3-dev"
+                }
+            },
+            "autoload": {
+                "files": [
+                    "src/functions_include.php"
+                ],
+                "psr-4": {
+                    "GuzzleHttp\\": "src/"
+                }
+            },
+            "notification-url": "https://packagist.org/downloads/",
+            "license": [
+                "MIT"
+            ],
+            "authors": [
+                {
+                    "name": "Michael Dowling",
+                    "email": "mtdowling@gmail.com",
+                    "homepage": "https://github.com/mtdowling"
+                }
+            ],
+            "description": "Guzzle is a PHP HTTP client library",
+            "homepage": "http://guzzlephp.org/",
+            "keywords": [
+                "client",
+                "curl",
+                "framework",
+                "http",
+                "http client",
+                "rest",
+                "web service"
+            ],
+            "time": "2018-04-22T15:46:56+00:00"
+        },
+        {
+            "name": "guzzlehttp/promises",
+            "version": "v1.3.1",
+            "source": {
+                "type": "git",
+                "url": "https://github.com/guzzle/promises.git",
+                "reference": "a59da6cf61d80060647ff4d3eb2c03a2bc694646"
+            },
+            "dist": {
+                "type": "zip",
+                "url": "https://api.github.com/repos/guzzle/promises/zipball/a59da6cf61d80060647ff4d3eb2c03a2bc694646",
+                "reference": "a59da6cf61d80060647ff4d3eb2c03a2bc694646",
+                "shasum": ""
+            },
+            "require": {
+                "php": ">=5.5.0"
+            },
+            "require-dev": {
+                "phpunit/phpunit": "^4.0"
+            },
+            "type": "library",
+            "extra": {
+                "branch-alias": {
+                    "dev-master": "1.4-dev"
+                }
+            },
+            "autoload": {
+                "psr-4": {
+                    "GuzzleHttp\\Promise\\": "src/"
+                },
+                "files": [
+                    "src/functions_include.php"
+                ]
+            },
+            "notification-url": "https://packagist.org/downloads/",
+            "license": [
+                "MIT"
+            ],
+            "authors": [
+                {
+                    "name": "Michael Dowling",
+                    "email": "mtdowling@gmail.com",
+                    "homepage": "https://github.com/mtdowling"
+                }
+            ],
+            "description": "Guzzle promises library",
+            "keywords": [
+                "promise"
+            ],
+            "time": "2016-12-20T10:07:11+00:00"
+        },
+        {
+            "name": "guzzlehttp/psr7",
+            "version": "1.4.2",
+            "source": {
+                "type": "git",
+                "url": "https://github.com/guzzle/psr7.git",
+                "reference": "f5b8a8512e2b58b0071a7280e39f14f72e05d87c"
+            },
+            "dist": {
+                "type": "zip",
+                "url": "https://api.github.com/repos/guzzle/psr7/zipball/f5b8a8512e2b58b0071a7280e39f14f72e05d87c",
+                "reference": "f5b8a8512e2b58b0071a7280e39f14f72e05d87c",
+                "shasum": ""
+            },
+            "require": {
+                "php": ">=5.4.0",
+                "psr/http-message": "~1.0"
+            },
+            "provide": {
+                "psr/http-message-implementation": "1.0"
+            },
+            "require-dev": {
+                "phpunit/phpunit": "~4.0"
+            },
+            "type": "library",
+            "extra": {
+                "branch-alias": {
+                    "dev-master": "1.4-dev"
+                }
+            },
+            "autoload": {
+                "psr-4": {
+                    "GuzzleHttp\\Psr7\\": "src/"
+                },
+                "files": [
+                    "src/functions_include.php"
+                ]
+            },
+            "notification-url": "https://packagist.org/downloads/",
+            "license": [
+                "MIT"
+            ],
+            "authors": [
+                {
+                    "name": "Michael Dowling",
+                    "email": "mtdowling@gmail.com",
+                    "homepage": "https://github.com/mtdowling"
+                },
+                {
+                    "name": "Tobias Schultze",
+                    "homepage": "https://github.com/Tobion"
+                }
+            ],
+            "description": "PSR-7 message implementation that also provides common utility methods",
+            "keywords": [
+                "http",
+                "message",
+                "request",
+                "response",
+                "stream",
+                "uri",
+                "url"
+            ],
+            "time": "2017-03-20T17:10:46+00:00"
+        },
+        {
+            "name": "myclabs/deep-copy",
+            "version": "1.7.0",
+            "source": {
+                "type": "git",
+                "url": "https://github.com/myclabs/DeepCopy.git",
+                "reference": "3b8a3a99ba1f6a3952ac2747d989303cbd6b7a3e"
+            },
+            "dist": {
+                "type": "zip",
+                "url": "https://api.github.com/repos/myclabs/DeepCopy/zipball/3b8a3a99ba1f6a3952ac2747d989303cbd6b7a3e",
+                "reference": "3b8a3a99ba1f6a3952ac2747d989303cbd6b7a3e",
+                "shasum": ""
+            },
+            "require": {
+                "php": "^5.6 || ^7.0"
+            },
+            "require-dev": {
+                "doctrine/collections": "^1.0",
+                "doctrine/common": "^2.6",
+                "phpunit/phpunit": "^4.1"
+            },
+            "type": "library",
+            "autoload": {
+                "psr-4": {
+                    "DeepCopy\\": "src/DeepCopy/"
+                },
+                "files": [
+                    "src/DeepCopy/deep_copy.php"
+                ]
+            },
+            "notification-url": "https://packagist.org/downloads/",
+            "license": [
+                "MIT"
+            ],
+            "description": "Create deep copies (clones) of your objects",
+            "keywords": [
+                "clone",
+                "copy",
+                "duplicate",
+                "object",
+                "object graph"
+            ],
+            "time": "2017-10-19T19:58:43+00:00"
+        },
+        {
+            "name": "phar-io/manifest",
+            "version": "1.0.1",
+            "source": {
+                "type": "git",
+                "url": "https://github.com/phar-io/manifest.git",
+                "reference": "2df402786ab5368a0169091f61a7c1e0eb6852d0"
+            },
+            "dist": {
+                "type": "zip",
+                "url": "https://api.github.com/repos/phar-io/manifest/zipball/2df402786ab5368a0169091f61a7c1e0eb6852d0",
+                "reference": "2df402786ab5368a0169091f61a7c1e0eb6852d0",
+                "shasum": ""
+            },
+            "require": {
+                "ext-dom": "*",
+                "ext-phar": "*",
+                "phar-io/version": "^1.0.1",
+                "php": "^5.6 || ^7.0"
+            },
+            "type": "library",
+            "extra": {
+                "branch-alias": {
+                    "dev-master": "1.0.x-dev"
+                }
+            },
+            "autoload": {
+                "classmap": [
+                    "src/"
+                ]
+            },
+            "notification-url": "https://packagist.org/downloads/",
+            "license": [
+                "BSD-3-Clause"
+            ],
+            "authors": [
+                {
+                    "name": "Arne Blankerts",
+                    "email": "arne@blankerts.de",
+                    "role": "Developer"
+                },
+                {
+                    "name": "Sebastian Heuer",
+                    "email": "sebastian@phpeople.de",
+                    "role": "Developer"
+                },
+                {
+                    "name": "Sebastian Bergmann",
+                    "email": "sebastian@phpunit.de",
+                    "role": "Developer"
+                }
+            ],
+            "description": "Component for reading phar.io manifest information from a PHP Archive (PHAR)",
+            "time": "2017-03-05T18:14:27+00:00"
+        },
+        {
+            "name": "phar-io/version",
+            "version": "1.0.1",
+            "source": {
+                "type": "git",
+                "url": "https://github.com/phar-io/version.git",
+                "reference": "a70c0ced4be299a63d32fa96d9281d03e94041df"
+            },
+            "dist": {
+                "type": "zip",
+                "url": "https://api.github.com/repos/phar-io/version/zipball/a70c0ced4be299a63d32fa96d9281d03e94041df",
+                "reference": "a70c0ced4be299a63d32fa96d9281d03e94041df",
+                "shasum": ""
+            },
+            "require": {
+                "php": "^5.6 || ^7.0"
+            },
+            "type": "library",
+            "autoload": {
+                "classmap": [
+                    "src/"
+                ]
+            },
+            "notification-url": "https://packagist.org/downloads/",
+            "license": [
+                "BSD-3-Clause"
+            ],
+            "authors": [
+                {
+                    "name": "Arne Blankerts",
+                    "email": "arne@blankerts.de",
+                    "role": "Developer"
+                },
+                {
+                    "name": "Sebastian Heuer",
+                    "email": "sebastian@phpeople.de",
+                    "role": "Developer"
+                },
+                {
+                    "name": "Sebastian Bergmann",
+                    "email": "sebastian@phpunit.de",
+                    "role": "Developer"
+                }
+            ],
+            "description": "Library for handling version information and constraints",
+            "time": "2017-03-05T17:38:23+00:00"
+        },
+        {
+            "name": "phpdocumentor/reflection-common",
+            "version": "1.0.1",
+            "source": {
+                "type": "git",
+                "url": "https://github.com/phpDocumentor/ReflectionCommon.git",
+                "reference": "21bdeb5f65d7ebf9f43b1b25d404f87deab5bfb6"
+            },
+            "dist": {
+                "type": "zip",
+                "url": "https://api.github.com/repos/phpDocumentor/ReflectionCommon/zipball/21bdeb5f65d7ebf9f43b1b25d404f87deab5bfb6",
+                "reference": "21bdeb5f65d7ebf9f43b1b25d404f87deab5bfb6",
+                "shasum": ""
+            },
+            "require": {
+                "php": ">=5.5"
+            },
+            "require-dev": {
+                "phpunit/phpunit": "^4.6"
+            },
+            "type": "library",
+            "extra": {
+                "branch-alias": {
+                    "dev-master": "1.0.x-dev"
+                }
+            },
+            "autoload": {
+                "psr-4": {
+                    "phpDocumentor\\Reflection\\": [
+                        "src"
+                    ]
+                }
+            },
+            "notification-url": "https://packagist.org/downloads/",
+            "license": [
+                "MIT"
+            ],
+            "authors": [
+                {
+                    "name": "Jaap van Otterdijk",
+                    "email": "opensource@ijaap.nl"
+                }
+            ],
+            "description": "Common reflection classes used by phpdocumentor to reflect the code structure",
+            "homepage": "http://www.phpdoc.org",
+            "keywords": [
+                "FQSEN",
+                "phpDocumentor",
+                "phpdoc",
+                "reflection",
+                "static analysis"
+            ],
+            "time": "2017-09-11T18:02:19+00:00"
+        },
+        {
+            "name": "phpdocumentor/reflection-docblock",
+            "version": "4.3.0",
+            "source": {
+                "type": "git",
+                "url": "https://github.com/phpDocumentor/ReflectionDocBlock.git",
+                "reference": "94fd0001232e47129dd3504189fa1c7225010d08"
+            },
+            "dist": {
+                "type": "zip",
+                "url": "https://api.github.com/repos/phpDocumentor/ReflectionDocBlock/zipball/94fd0001232e47129dd3504189fa1c7225010d08",
+                "reference": "94fd0001232e47129dd3504189fa1c7225010d08",
+                "shasum": ""
+            },
+            "require": {
+                "php": "^7.0",
+                "phpdocumentor/reflection-common": "^1.0.0",
+                "phpdocumentor/type-resolver": "^0.4.0",
+                "webmozart/assert": "^1.0"
+            },
+            "require-dev": {
+                "doctrine/instantiator": "~1.0.5",
+                "mockery/mockery": "^1.0",
+                "phpunit/phpunit": "^6.4"
+            },
+            "type": "library",
+            "extra": {
+                "branch-alias": {
+                    "dev-master": "4.x-dev"
+                }
+            },
+            "autoload": {
+                "psr-4": {
+                    "phpDocumentor\\Reflection\\": [
+                        "src/"
+                    ]
+                }
+            },
+            "notification-url": "https://packagist.org/downloads/",
+            "license": [
+                "MIT"
+            ],
+            "authors": [
+                {
+                    "name": "Mike van Riel",
+                    "email": "me@mikevanriel.com"
+                }
+            ],
+            "description": "With this component, a library can provide support for annotations via DocBlocks or otherwise retrieve information that is embedded in a DocBlock.",
+            "time": "2017-11-30T07:14:17+00:00"
+        },
+        {
+            "name": "phpdocumentor/type-resolver",
+            "version": "0.4.0",
+            "source": {
+                "type": "git",
+                "url": "https://github.com/phpDocumentor/TypeResolver.git",
+                "reference": "9c977708995954784726e25d0cd1dddf4e65b0f7"
+            },
+            "dist": {
+                "type": "zip",
+                "url": "https://api.github.com/repos/phpDocumentor/TypeResolver/zipball/9c977708995954784726e25d0cd1dddf4e65b0f7",
+                "reference": "9c977708995954784726e25d0cd1dddf4e65b0f7",
+                "shasum": ""
+            },
+            "require": {
+                "php": "^5.5 || ^7.0",
+                "phpdocumentor/reflection-common": "^1.0"
+            },
+            "require-dev": {
+                "mockery/mockery": "^0.9.4",
+                "phpunit/phpunit": "^5.2||^4.8.24"
+            },
+            "type": "library",
+            "extra": {
+                "branch-alias": {
+                    "dev-master": "1.0.x-dev"
+                }
+            },
+            "autoload": {
+                "psr-4": {
+                    "phpDocumentor\\Reflection\\": [
+                        "src/"
+                    ]
+                }
+            },
+            "notification-url": "https://packagist.org/downloads/",
+            "license": [
+                "MIT"
+            ],
+            "authors": [
+                {
+                    "name": "Mike van Riel",
+                    "email": "me@mikevanriel.com"
+                }
+            ],
+            "time": "2017-07-14T14:27:02+00:00"
+        },
+        {
+            "name": "phpspec/prophecy",
+            "version": "1.7.6",
+            "source": {
+                "type": "git",
+                "url": "https://github.com/phpspec/prophecy.git",
+                "reference": "33a7e3c4fda54e912ff6338c48823bd5c0f0b712"
+            },
+            "dist": {
+                "type": "zip",
+                "url": "https://api.github.com/repos/phpspec/prophecy/zipball/33a7e3c4fda54e912ff6338c48823bd5c0f0b712",
+                "reference": "33a7e3c4fda54e912ff6338c48823bd5c0f0b712",
+                "shasum": ""
+            },
+            "require": {
+                "doctrine/instantiator": "^1.0.2",
+                "php": "^5.3|^7.0",
+                "phpdocumentor/reflection-docblock": "^2.0|^3.0.2|^4.0",
+                "sebastian/comparator": "^1.1|^2.0|^3.0",
+                "sebastian/recursion-context": "^1.0|^2.0|^3.0"
+            },
+            "require-dev": {
+                "phpspec/phpspec": "^2.5|^3.2",
+                "phpunit/phpunit": "^4.8.35 || ^5.7 || ^6.5"
+            },
+            "type": "library",
+            "extra": {
+                "branch-alias": {
+                    "dev-master": "1.7.x-dev"
+                }
+            },
+            "autoload": {
+                "psr-0": {
+                    "Prophecy\\": "src/"
+                }
+            },
+            "notification-url": "https://packagist.org/downloads/",
+            "license": [
+                "MIT"
+            ],
+            "authors": [
+                {
+                    "name": "Konstantin Kudryashov",
+                    "email": "ever.zet@gmail.com",
+                    "homepage": "http://everzet.com"
+                },
+                {
+                    "name": "Marcello Duarte",
+                    "email": "marcello.duarte@gmail.com"
+                }
+            ],
+            "description": "Highly opinionated mocking framework for PHP 5.3+",
+            "homepage": "https://github.com/phpspec/prophecy",
+            "keywords": [
+                "Double",
+                "Dummy",
+                "fake",
+                "mock",
+                "spy",
+                "stub"
+            ],
+            "time": "2018-04-18T13:57:24+00:00"
+        },
+        {
+            "name": "phpunit/php-code-coverage",
+            "version": "6.0.4",
+            "source": {
+                "type": "git",
+                "url": "https://github.com/sebastianbergmann/php-code-coverage.git",
+                "reference": "52187754b0eed0b8159f62a6fa30073327e8c2ca"
+            },
+            "dist": {
+                "type": "zip",
+                "url": "https://api.github.com/repos/sebastianbergmann/php-code-coverage/zipball/52187754b0eed0b8159f62a6fa30073327e8c2ca",
+                "reference": "52187754b0eed0b8159f62a6fa30073327e8c2ca",
+                "shasum": ""
+            },
+            "require": {
+                "ext-dom": "*",
+                "ext-xmlwriter": "*",
+                "php": "^7.1",
+                "phpunit/php-file-iterator": "^1.4.2",
+                "phpunit/php-text-template": "^1.2.1",
+                "phpunit/php-token-stream": "^3.0",
+                "sebastian/code-unit-reverse-lookup": "^1.0.1",
+                "sebastian/environment": "^3.1",
+                "sebastian/version": "^2.0.1",
+                "theseer/tokenizer": "^1.1"
+            },
+            "require-dev": {
+                "phpunit/phpunit": "^7.0"
+            },
+            "suggest": {
+                "ext-xdebug": "^2.6.0"
+            },
+            "type": "library",
+            "extra": {
+                "branch-alias": {
+                    "dev-master": "6.0-dev"
+                }
+            },
+            "autoload": {
+                "classmap": [
+                    "src/"
+                ]
+            },
+            "notification-url": "https://packagist.org/downloads/",
+            "license": [
+                "BSD-3-Clause"
+            ],
+            "authors": [
+                {
+                    "name": "Sebastian Bergmann",
+                    "email": "sebastian@phpunit.de",
+                    "role": "lead"
+                }
+            ],
+            "description": "Library that provides collection, processing, and rendering functionality for PHP code coverage information.",
+            "homepage": "https://github.com/sebastianbergmann/php-code-coverage",
+            "keywords": [
+                "coverage",
+                "testing",
+                "xunit"
+            ],
+            "time": "2018-04-29T14:59:09+00:00"
+        },
+        {
+            "name": "phpunit/php-file-iterator",
+            "version": "1.4.5",
+            "source": {
+                "type": "git",
+                "url": "https://github.com/sebastianbergmann/php-file-iterator.git",
+                "reference": "730b01bc3e867237eaac355e06a36b85dd93a8b4"
+            },
+            "dist": {
+                "type": "zip",
+                "url": "https://api.github.com/repos/sebastianbergmann/php-file-iterator/zipball/730b01bc3e867237eaac355e06a36b85dd93a8b4",
+                "reference": "730b01bc3e867237eaac355e06a36b85dd93a8b4",
+                "shasum": ""
+            },
+            "require": {
+                "php": ">=5.3.3"
+            },
+            "type": "library",
+            "extra": {
+                "branch-alias": {
+                    "dev-master": "1.4.x-dev"
+                }
+            },
+            "autoload": {
+                "classmap": [
+                    "src/"
+                ]
+            },
+            "notification-url": "https://packagist.org/downloads/",
+            "license": [
+                "BSD-3-Clause"
+            ],
+            "authors": [
+                {
+                    "name": "Sebastian Bergmann",
+                    "email": "sb@sebastian-bergmann.de",
+                    "role": "lead"
+                }
+            ],
+            "description": "FilterIterator implementation that filters files based on a list of suffixes.",
+            "homepage": "https://github.com/sebastianbergmann/php-file-iterator/",
+            "keywords": [
+                "filesystem",
+                "iterator"
+            ],
+            "time": "2017-11-27T13:52:08+00:00"
+        },
+        {
+            "name": "phpunit/php-text-template",
+            "version": "1.2.1",
+            "source": {
+                "type": "git",
+                "url": "https://github.com/sebastianbergmann/php-text-template.git",
+                "reference": "31f8b717e51d9a2afca6c9f046f5d69fc27c8686"
+            },
+            "dist": {
+                "type": "zip",
+                "url": "https://api.github.com/repos/sebastianbergmann/php-text-template/zipball/31f8b717e51d9a2afca6c9f046f5d69fc27c8686",
+                "reference": "31f8b717e51d9a2afca6c9f046f5d69fc27c8686",
+                "shasum": ""
+            },
+            "require": {
+                "php": ">=5.3.3"
+            },
+            "type": "library",
+            "autoload": {
+                "classmap": [
+                    "src/"
+                ]
+            },
+            "notification-url": "https://packagist.org/downloads/",
+            "license": [
+                "BSD-3-Clause"
+            ],
+            "authors": [
+                {
+                    "name": "Sebastian Bergmann",
+                    "email": "sebastian@phpunit.de",
+                    "role": "lead"
+                }
+            ],
+            "description": "Simple template engine.",
+            "homepage": "https://github.com/sebastianbergmann/php-text-template/",
+            "keywords": [
+                "template"
+            ],
+            "time": "2015-06-21T13:50:34+00:00"
+        },
+        {
+            "name": "phpunit/php-timer",
+            "version": "2.0.0",
+            "source": {
+                "type": "git",
+                "url": "https://github.com/sebastianbergmann/php-timer.git",
+                "reference": "8b8454ea6958c3dee38453d3bd571e023108c91f"
+            },
+            "dist": {
+                "type": "zip",
+                "url": "https://api.github.com/repos/sebastianbergmann/php-timer/zipball/8b8454ea6958c3dee38453d3bd571e023108c91f",
+                "reference": "8b8454ea6958c3dee38453d3bd571e023108c91f",
+                "shasum": ""
+            },
+            "require": {
+                "php": "^7.1"
+            },
+            "require-dev": {
+                "phpunit/phpunit": "^7.0"
+            },
+            "type": "library",
+            "extra": {
+                "branch-alias": {
+                    "dev-master": "2.0-dev"
+                }
+            },
+            "autoload": {
+                "classmap": [
+                    "src/"
+                ]
+            },
+            "notification-url": "https://packagist.org/downloads/",
+            "license": [
+                "BSD-3-Clause"
+            ],
+            "authors": [
+                {
+                    "name": "Sebastian Bergmann",
+                    "email": "sebastian@phpunit.de",
+                    "role": "lead"
+                }
+            ],
+            "description": "Utility class for timing",
+            "homepage": "https://github.com/sebastianbergmann/php-timer/",
+            "keywords": [
+                "timer"
+            ],
+            "time": "2018-02-01T13:07:23+00:00"
+        },
+        {
+            "name": "phpunit/php-token-stream",
+            "version": "3.0.0",
+            "source": {
+                "type": "git",
+                "url": "https://github.com/sebastianbergmann/php-token-stream.git",
+                "reference": "21ad88bbba7c3d93530d93994e0a33cd45f02ace"
+            },
+            "dist": {
+                "type": "zip",
+                "url": "https://api.github.com/repos/sebastianbergmann/php-token-stream/zipball/21ad88bbba7c3d93530d93994e0a33cd45f02ace",
+                "reference": "21ad88bbba7c3d93530d93994e0a33cd45f02ace",
+                "shasum": ""
+            },
+            "require": {
+                "ext-tokenizer": "*",
+                "php": "^7.1"
+            },
+            "require-dev": {
+                "phpunit/phpunit": "^7.0"
+            },
+            "type": "library",
+            "extra": {
+                "branch-alias": {
+                    "dev-master": "3.0-dev"
+                }
+            },
+            "autoload": {
+                "classmap": [
+                    "src/"
+                ]
+            },
+            "notification-url": "https://packagist.org/downloads/",
+            "license": [
+                "BSD-3-Clause"
+            ],
+            "authors": [
+                {
+                    "name": "Sebastian Bergmann",
+                    "email": "sebastian@phpunit.de"
+                }
+            ],
+            "description": "Wrapper around PHP's tokenizer extension.",
+            "homepage": "https://github.com/sebastianbergmann/php-token-stream/",
+            "keywords": [
+                "tokenizer"
+            ],
+            "time": "2018-02-01T13:16:43+00:00"
+        },
+        {
+            "name": "phpunit/phpunit",
+            "version": "7.1.5",
+            "source": {
+                "type": "git",
+                "url": "https://github.com/sebastianbergmann/phpunit.git",
+                "reference": "ca64dba53b88aba6af32aebc6b388068db95c435"
+            },
+            "dist": {
+                "type": "zip",
+                "url": "https://api.github.com/repos/sebastianbergmann/phpunit/zipball/ca64dba53b88aba6af32aebc6b388068db95c435",
+                "reference": "ca64dba53b88aba6af32aebc6b388068db95c435",
+                "shasum": ""
+            },
+            "require": {
+                "ext-dom": "*",
+                "ext-json": "*",
+                "ext-libxml": "*",
+                "ext-mbstring": "*",
+                "ext-xml": "*",
+                "myclabs/deep-copy": "^1.6.1",
+                "phar-io/manifest": "^1.0.1",
+                "phar-io/version": "^1.0",
+                "php": "^7.1",
+                "phpspec/prophecy": "^1.7",
+                "phpunit/php-code-coverage": "^6.0.1",
+                "phpunit/php-file-iterator": "^1.4.3",
+                "phpunit/php-text-template": "^1.2.1",
+                "phpunit/php-timer": "^2.0",
+                "phpunit/phpunit-mock-objects": "^6.1.1",
+                "sebastian/comparator": "^3.0",
+                "sebastian/diff": "^3.0",
+                "sebastian/environment": "^3.1",
+                "sebastian/exporter": "^3.1",
+                "sebastian/global-state": "^2.0",
+                "sebastian/object-enumerator": "^3.0.3",
+                "sebastian/resource-operations": "^1.0",
+                "sebastian/version": "^2.0.1"
+            },
+            "require-dev": {
+                "ext-pdo": "*"
+            },
+            "suggest": {
+                "ext-xdebug": "*",
+                "phpunit/php-invoker": "^2.0"
+            },
+            "bin": [
+                "phpunit"
+            ],
+            "type": "library",
+            "extra": {
+                "branch-alias": {
+                    "dev-master": "7.1-dev"
+                }
+            },
+            "autoload": {
+                "classmap": [
+                    "src/"
+                ]
+            },
+            "notification-url": "https://packagist.org/downloads/",
+            "license": [
+                "BSD-3-Clause"
+            ],
+            "authors": [
+                {
+                    "name": "Sebastian Bergmann",
+                    "email": "sebastian@phpunit.de",
+                    "role": "lead"
+                }
+            ],
+            "description": "The PHP Unit Testing framework.",
+            "homepage": "https://phpunit.de/",
+            "keywords": [
+                "phpunit",
+                "testing",
+                "xunit"
+            ],
+            "time": "2018-04-29T15:09:19+00:00"
+        },
+        {
+            "name": "phpunit/phpunit-mock-objects",
+            "version": "6.1.1",
+            "source": {
+                "type": "git",
+                "url": "https://github.com/sebastianbergmann/phpunit-mock-objects.git",
+                "reference": "70c740bde8fd9ea9ea295be1cd875dd7b267e157"
+            },
+            "dist": {
+                "type": "zip",
+                "url": "https://api.github.com/repos/sebastianbergmann/phpunit-mock-objects/zipball/70c740bde8fd9ea9ea295be1cd875dd7b267e157",
+                "reference": "70c740bde8fd9ea9ea295be1cd875dd7b267e157",
+                "shasum": ""
+            },
+            "require": {
+                "doctrine/instantiator": "^1.0.5",
+                "php": "^7.1",
+                "phpunit/php-text-template": "^1.2.1",
+                "sebastian/exporter": "^3.1"
+            },
+            "require-dev": {
+                "phpunit/phpunit": "^7.0"
+            },
+            "suggest": {
+                "ext-soap": "*"
+            },
+            "type": "library",
+            "extra": {
+                "branch-alias": {
+                    "dev-master": "6.1-dev"
+                }
+            },
+            "autoload": {
+                "classmap": [
+                    "src/"
+                ]
+            },
+            "notification-url": "https://packagist.org/downloads/",
+            "license": [
+                "BSD-3-Clause"
+            ],
+            "authors": [
+                {
+                    "name": "Sebastian Bergmann",
+                    "email": "sebastian@phpunit.de",
+                    "role": "lead"
+                }
+            ],
+            "description": "Mock Object library for PHPUnit",
+            "homepage": "https://github.com/sebastianbergmann/phpunit-mock-objects/",
+            "keywords": [
+                "mock",
+                "xunit"
+            ],
+            "time": "2018-04-11T04:50:36+00:00"
+        },
+        {
+            "name": "psr/http-message",
+            "version": "1.0.1",
+            "source": {
+                "type": "git",
+                "url": "https://github.com/php-fig/http-message.git",
+                "reference": "f6561bf28d520154e4b0ec72be95418abe6d9363"
+            },
+            "dist": {
+                "type": "zip",
+                "url": "https://api.github.com/repos/php-fig/http-message/zipball/f6561bf28d520154e4b0ec72be95418abe6d9363",
+                "reference": "f6561bf28d520154e4b0ec72be95418abe6d9363",
+                "shasum": ""
+            },
+            "require": {
+                "php": ">=5.3.0"
+            },
+            "type": "library",
+            "extra": {
+                "branch-alias": {
+                    "dev-master": "1.0.x-dev"
+                }
+            },
+            "autoload": {
+                "psr-4": {
+                    "Psr\\Http\\Message\\": "src/"
+                }
+            },
+            "notification-url": "https://packagist.org/downloads/",
+            "license": [
+                "MIT"
+            ],
+            "authors": [
+                {
+                    "name": "PHP-FIG",
+                    "homepage": "http://www.php-fig.org/"
+                }
+            ],
+            "description": "Common interface for HTTP messages",
+            "homepage": "https://github.com/php-fig/http-message",
+            "keywords": [
+                "http",
+                "http-message",
+                "psr",
+                "psr-7",
+                "request",
+                "response"
+            ],
+            "time": "2016-08-06T14:39:51+00:00"
+        },
+        {
+            "name": "sebastian/code-unit-reverse-lookup",
+            "version": "1.0.1",
+            "source": {
+                "type": "git",
+                "url": "https://github.com/sebastianbergmann/code-unit-reverse-lookup.git",
+                "reference": "4419fcdb5eabb9caa61a27c7a1db532a6b55dd18"
+            },
+            "dist": {
+                "type": "zip",
+                "url": "https://api.github.com/repos/sebastianbergmann/code-unit-reverse-lookup/zipball/4419fcdb5eabb9caa61a27c7a1db532a6b55dd18",
+                "reference": "4419fcdb5eabb9caa61a27c7a1db532a6b55dd18",
+                "shasum": ""
+            },
+            "require": {
+                "php": "^5.6 || ^7.0"
+            },
+            "require-dev": {
+                "phpunit/phpunit": "^5.7 || ^6.0"
+            },
+            "type": "library",
+            "extra": {
+                "branch-alias": {
+                    "dev-master": "1.0.x-dev"
+                }
+            },
+            "autoload": {
+                "classmap": [
+                    "src/"
+                ]
+            },
+            "notification-url": "https://packagist.org/downloads/",
+            "license": [
+                "BSD-3-Clause"
+            ],
+            "authors": [
+                {
+                    "name": "Sebastian Bergmann",
+                    "email": "sebastian@phpunit.de"
+                }
+            ],
+            "description": "Looks up which function or method a line of code belongs to",
+            "homepage": "https://github.com/sebastianbergmann/code-unit-reverse-lookup/",
+            "time": "2017-03-04T06:30:41+00:00"
+        },
+        {
+            "name": "sebastian/comparator",
+            "version": "3.0.0",
+            "source": {
+                "type": "git",
+                "url": "https://github.com/sebastianbergmann/comparator.git",
+                "reference": "ed5fd2281113729f1ebcc64d101ad66028aeb3d5"
+            },
+            "dist": {
+                "type": "zip",
+                "url": "https://api.github.com/repos/sebastianbergmann/comparator/zipball/ed5fd2281113729f1ebcc64d101ad66028aeb3d5",
+                "reference": "ed5fd2281113729f1ebcc64d101ad66028aeb3d5",
+                "shasum": ""
+            },
+            "require": {
+                "php": "^7.1",
+                "sebastian/diff": "^3.0",
+                "sebastian/exporter": "^3.1"
+            },
+            "require-dev": {
+                "phpunit/phpunit": "^7.1"
+            },
+            "type": "library",
+            "extra": {
+                "branch-alias": {
+                    "dev-master": "3.0-dev"
+                }
+            },
+            "autoload": {
+                "classmap": [
+                    "src/"
+                ]
+            },
+            "notification-url": "https://packagist.org/downloads/",
+            "license": [
+                "BSD-3-Clause"
+            ],
+            "authors": [
+                {
+                    "name": "Jeff Welch",
+                    "email": "whatthejeff@gmail.com"
+                },
+                {
+                    "name": "Volker Dusch",
+                    "email": "github@wallbash.com"
+                },
+                {
+                    "name": "Bernhard Schussek",
+                    "email": "bschussek@2bepublished.at"
+                },
+                {
+                    "name": "Sebastian Bergmann",
+                    "email": "sebastian@phpunit.de"
+                }
+            ],
+            "description": "Provides the functionality to compare PHP values for equality",
+            "homepage": "https://github.com/sebastianbergmann/comparator",
+            "keywords": [
+                "comparator",
+                "compare",
+                "equality"
+            ],
+            "time": "2018-04-18T13:33:00+00:00"
+        },
+        {
+            "name": "sebastian/diff",
+            "version": "3.0.0",
+            "source": {
+                "type": "git",
+                "url": "https://github.com/sebastianbergmann/diff.git",
+                "reference": "e09160918c66281713f1c324c1f4c4c3037ba1e8"
+            },
+            "dist": {
+                "type": "zip",
+                "url": "https://api.github.com/repos/sebastianbergmann/diff/zipball/e09160918c66281713f1c324c1f4c4c3037ba1e8",
+                "reference": "e09160918c66281713f1c324c1f4c4c3037ba1e8",
+                "shasum": ""
+            },
+            "require": {
+                "php": "^7.1"
+            },
+            "require-dev": {
+                "phpunit/phpunit": "^7.0",
+                "symfony/process": "^2 || ^3.3 || ^4"
+            },
+            "type": "library",
+            "extra": {
+                "branch-alias": {
+                    "dev-master": "3.0-dev"
+                }
+            },
+            "autoload": {
+                "classmap": [
+                    "src/"
+                ]
+            },
+            "notification-url": "https://packagist.org/downloads/",
+            "license": [
+                "BSD-3-Clause"
+            ],
+            "authors": [
+                {
+                    "name": "Kore Nordmann",
+                    "email": "mail@kore-nordmann.de"
+                },
+                {
+                    "name": "Sebastian Bergmann",
+                    "email": "sebastian@phpunit.de"
+                }
+            ],
+            "description": "Diff implementation",
+            "homepage": "https://github.com/sebastianbergmann/diff",
+            "keywords": [
+                "diff",
+                "udiff",
+                "unidiff",
+                "unified diff"
+            ],
+            "time": "2018-02-01T13:45:15+00:00"
+        },
+        {
+            "name": "sebastian/environment",
+            "version": "3.1.0",
+            "source": {
+                "type": "git",
+                "url": "https://github.com/sebastianbergmann/environment.git",
+                "reference": "cd0871b3975fb7fc44d11314fd1ee20925fce4f5"
+            },
+            "dist": {
+                "type": "zip",
+                "url": "https://api.github.com/repos/sebastianbergmann/environment/zipball/cd0871b3975fb7fc44d11314fd1ee20925fce4f5",
+                "reference": "cd0871b3975fb7fc44d11314fd1ee20925fce4f5",
+                "shasum": ""
+            },
+            "require": {
+                "php": "^7.0"
+            },
+            "require-dev": {
+                "phpunit/phpunit": "^6.1"
+            },
+            "type": "library",
+            "extra": {
+                "branch-alias": {
+                    "dev-master": "3.1.x-dev"
+                }
+            },
+            "autoload": {
+                "classmap": [
+                    "src/"
+                ]
+            },
+            "notification-url": "https://packagist.org/downloads/",
+            "license": [
+                "BSD-3-Clause"
+            ],
+            "authors": [
+                {
+                    "name": "Sebastian Bergmann",
+                    "email": "sebastian@phpunit.de"
+                }
+            ],
+            "description": "Provides functionality to handle HHVM/PHP environments",
+            "homepage": "http://www.github.com/sebastianbergmann/environment",
+            "keywords": [
+                "Xdebug",
+                "environment",
+                "hhvm"
+            ],
+            "time": "2017-07-01T08:51:00+00:00"
+        },
+        {
+            "name": "sebastian/exporter",
+            "version": "3.1.0",
+            "source": {
+                "type": "git",
+                "url": "https://github.com/sebastianbergmann/exporter.git",
+                "reference": "234199f4528de6d12aaa58b612e98f7d36adb937"
+            },
+            "dist": {
+                "type": "zip",
+                "url": "https://api.github.com/repos/sebastianbergmann/exporter/zipball/234199f4528de6d12aaa58b612e98f7d36adb937",
+                "reference": "234199f4528de6d12aaa58b612e98f7d36adb937",
+                "shasum": ""
+            },
+            "require": {
+                "php": "^7.0",
+                "sebastian/recursion-context": "^3.0"
+            },
+            "require-dev": {
+                "ext-mbstring": "*",
+                "phpunit/phpunit": "^6.0"
+            },
+            "type": "library",
+            "extra": {
+                "branch-alias": {
+                    "dev-master": "3.1.x-dev"
+                }
+            },
+            "autoload": {
+                "classmap": [
+                    "src/"
+                ]
+            },
+            "notification-url": "https://packagist.org/downloads/",
+            "license": [
+                "BSD-3-Clause"
+            ],
+            "authors": [
+                {
+                    "name": "Jeff Welch",
+                    "email": "whatthejeff@gmail.com"
+                },
+                {
+                    "name": "Volker Dusch",
+                    "email": "github@wallbash.com"
+                },
+                {
+                    "name": "Bernhard Schussek",
+                    "email": "bschussek@2bepublished.at"
+                },
+                {
+                    "name": "Sebastian Bergmann",
+                    "email": "sebastian@phpunit.de"
+                },
+                {
+                    "name": "Adam Harvey",
+                    "email": "aharvey@php.net"
+                }
+            ],
+            "description": "Provides the functionality to export PHP variables for visualization",
+            "homepage": "http://www.github.com/sebastianbergmann/exporter",
+            "keywords": [
+                "export",
+                "exporter"
+            ],
+            "time": "2017-04-03T13:19:02+00:00"
+        },
+        {
+            "name": "sebastian/global-state",
+            "version": "2.0.0",
+            "source": {
+                "type": "git",
+                "url": "https://github.com/sebastianbergmann/global-state.git",
+                "reference": "e8ba02eed7bbbb9e59e43dedd3dddeff4a56b0c4"
+            },
+            "dist": {
+                "type": "zip",
+                "url": "https://api.github.com/repos/sebastianbergmann/global-state/zipball/e8ba02eed7bbbb9e59e43dedd3dddeff4a56b0c4",
+                "reference": "e8ba02eed7bbbb9e59e43dedd3dddeff4a56b0c4",
+                "shasum": ""
+            },
+            "require": {
+                "php": "^7.0"
+            },
+            "require-dev": {
+                "phpunit/phpunit": "^6.0"
+            },
+            "suggest": {
+                "ext-uopz": "*"
+            },
+            "type": "library",
+            "extra": {
+                "branch-alias": {
+                    "dev-master": "2.0-dev"
+                }
+            },
+            "autoload": {
+                "classmap": [
+                    "src/"
+                ]
+            },
+            "notification-url": "https://packagist.org/downloads/",
+            "license": [
+                "BSD-3-Clause"
+            ],
+            "authors": [
+                {
+                    "name": "Sebastian Bergmann",
+                    "email": "sebastian@phpunit.de"
+                }
+            ],
+            "description": "Snapshotting of global state",
+            "homepage": "http://www.github.com/sebastianbergmann/global-state",
+            "keywords": [
+                "global state"
+            ],
+            "time": "2017-04-27T15:39:26+00:00"
+        },
+        {
+            "name": "sebastian/object-enumerator",
+            "version": "3.0.3",
+            "source": {
+                "type": "git",
+                "url": "https://github.com/sebastianbergmann/object-enumerator.git",
+                "reference": "7cfd9e65d11ffb5af41198476395774d4c8a84c5"
+            },
+            "dist": {
+                "type": "zip",
+                "url": "https://api.github.com/repos/sebastianbergmann/object-enumerator/zipball/7cfd9e65d11ffb5af41198476395774d4c8a84c5",
+                "reference": "7cfd9e65d11ffb5af41198476395774d4c8a84c5",
+                "shasum": ""
+            },
+            "require": {
+                "php": "^7.0",
+                "sebastian/object-reflector": "^1.1.1",
+                "sebastian/recursion-context": "^3.0"
+            },
+            "require-dev": {
+                "phpunit/phpunit": "^6.0"
+            },
+            "type": "library",
+            "extra": {
+                "branch-alias": {
+                    "dev-master": "3.0.x-dev"
+                }
+            },
+            "autoload": {
+                "classmap": [
+                    "src/"
+                ]
+            },
+            "notification-url": "https://packagist.org/downloads/",
+            "license": [
+                "BSD-3-Clause"
+            ],
+            "authors": [
+                {
+                    "name": "Sebastian Bergmann",
+                    "email": "sebastian@phpunit.de"
+                }
+            ],
+            "description": "Traverses array structures and object graphs to enumerate all referenced objects",
+            "homepage": "https://github.com/sebastianbergmann/object-enumerator/",
+            "time": "2017-08-03T12:35:26+00:00"
+        },
+        {
+            "name": "sebastian/object-reflector",
+            "version": "1.1.1",
+            "source": {
+                "type": "git",
+                "url": "https://github.com/sebastianbergmann/object-reflector.git",
+                "reference": "773f97c67f28de00d397be301821b06708fca0be"
+            },
+            "dist": {
+                "type": "zip",
+                "url": "https://api.github.com/repos/sebastianbergmann/object-reflector/zipball/773f97c67f28de00d397be301821b06708fca0be",
+                "reference": "773f97c67f28de00d397be301821b06708fca0be",
+                "shasum": ""
+            },
+            "require": {
+                "php": "^7.0"
+            },
+            "require-dev": {
+                "phpunit/phpunit": "^6.0"
+            },
+            "type": "library",
+            "extra": {
+                "branch-alias": {
+                    "dev-master": "1.1-dev"
+                }
+            },
+            "autoload": {
+                "classmap": [
+                    "src/"
+                ]
+            },
+            "notification-url": "https://packagist.org/downloads/",
+            "license": [
+                "BSD-3-Clause"
+            ],
+            "authors": [
+                {
+                    "name": "Sebastian Bergmann",
+                    "email": "sebastian@phpunit.de"
+                }
+            ],
+            "description": "Allows reflection of object attributes, including inherited and non-public ones",
+            "homepage": "https://github.com/sebastianbergmann/object-reflector/",
+            "time": "2017-03-29T09:07:27+00:00"
+        },
+        {
+            "name": "sebastian/recursion-context",
+            "version": "3.0.0",
+            "source": {
+                "type": "git",
+                "url": "https://github.com/sebastianbergmann/recursion-context.git",
+                "reference": "5b0cd723502bac3b006cbf3dbf7a1e3fcefe4fa8"
+            },
+            "dist": {
+                "type": "zip",
+                "url": "https://api.github.com/repos/sebastianbergmann/recursion-context/zipball/5b0cd723502bac3b006cbf3dbf7a1e3fcefe4fa8",
+                "reference": "5b0cd723502bac3b006cbf3dbf7a1e3fcefe4fa8",
+                "shasum": ""
+            },
+            "require": {
+                "php": "^7.0"
+            },
+            "require-dev": {
+                "phpunit/phpunit": "^6.0"
+            },
+            "type": "library",
+            "extra": {
+                "branch-alias": {
+                    "dev-master": "3.0.x-dev"
+                }
+            },
+            "autoload": {
+                "classmap": [
+                    "src/"
+                ]
+            },
+            "notification-url": "https://packagist.org/downloads/",
+            "license": [
+                "BSD-3-Clause"
+            ],
+            "authors": [
+                {
+                    "name": "Jeff Welch",
+                    "email": "whatthejeff@gmail.com"
+                },
+                {
+                    "name": "Sebastian Bergmann",
+                    "email": "sebastian@phpunit.de"
+                },
+                {
+                    "name": "Adam Harvey",
+                    "email": "aharvey@php.net"
+                }
+            ],
+            "description": "Provides functionality to recursively process PHP variables",
+            "homepage": "http://www.github.com/sebastianbergmann/recursion-context",
+            "time": "2017-03-03T06:23:57+00:00"
+        },
+        {
+            "name": "sebastian/resource-operations",
+            "version": "1.0.0",
+            "source": {
+                "type": "git",
+                "url": "https://github.com/sebastianbergmann/resource-operations.git",
+                "reference": "ce990bb21759f94aeafd30209e8cfcdfa8bc3f52"
+            },
+            "dist": {
+                "type": "zip",
+                "url": "https://api.github.com/repos/sebastianbergmann/resource-operations/zipball/ce990bb21759f94aeafd30209e8cfcdfa8bc3f52",
+                "reference": "ce990bb21759f94aeafd30209e8cfcdfa8bc3f52",
+                "shasum": ""
+            },
+            "require": {
+                "php": ">=5.6.0"
+            },
+            "type": "library",
+            "extra": {
+                "branch-alias": {
+                    "dev-master": "1.0.x-dev"
+                }
+            },
+            "autoload": {
+                "classmap": [
+                    "src/"
+                ]
+            },
+            "notification-url": "https://packagist.org/downloads/",
+            "license": [
+                "BSD-3-Clause"
+            ],
+            "authors": [
+                {
+                    "name": "Sebastian Bergmann",
+                    "email": "sebastian@phpunit.de"
+                }
+            ],
+            "description": "Provides a list of PHP built-in functions that operate on resources",
+            "homepage": "https://www.github.com/sebastianbergmann/resource-operations",
+            "time": "2015-07-28T20:34:47+00:00"
+        },
+        {
+            "name": "sebastian/version",
+            "version": "2.0.1",
+            "source": {
+                "type": "git",
+                "url": "https://github.com/sebastianbergmann/version.git",
+                "reference": "99732be0ddb3361e16ad77b68ba41efc8e979019"
+            },
+            "dist": {
+                "type": "zip",
+                "url": "https://api.github.com/repos/sebastianbergmann/version/zipball/99732be0ddb3361e16ad77b68ba41efc8e979019",
+                "reference": "99732be0ddb3361e16ad77b68ba41efc8e979019",
+                "shasum": ""
+            },
+            "require": {
+                "php": ">=5.6"
+            },
+            "type": "library",
+            "extra": {
+                "branch-alias": {
+                    "dev-master": "2.0.x-dev"
+                }
+            },
+            "autoload": {
+                "classmap": [
+                    "src/"
+                ]
+            },
+            "notification-url": "https://packagist.org/downloads/",
+            "license": [
+                "BSD-3-Clause"
+            ],
+            "authors": [
+                {
+                    "name": "Sebastian Bergmann",
+                    "email": "sebastian@phpunit.de",
+                    "role": "lead"
+                }
+            ],
+            "description": "Library that helps with managing the version number of Git-hosted PHP projects",
+            "homepage": "https://github.com/sebastianbergmann/version",
+            "time": "2016-10-03T07:35:21+00:00"
+        },
+        {
+            "name": "statonlab/tripal-test-suite",
+            "version": "1.0.2",
+            "source": {
+                "type": "git",
+                "url": "https://github.com/statonlab/TripalTestSuite.git",
+                "reference": "2d09cd7565a82f16cc4bba7411bc32e2553cb92c"
+            },
+            "dist": {
+                "type": "zip",
+                "url": "https://api.github.com/repos/statonlab/TripalTestSuite/zipball/2d09cd7565a82f16cc4bba7411bc32e2553cb92c",
+                "reference": "2d09cd7565a82f16cc4bba7411bc32e2553cb92c",
+                "shasum": ""
+            },
+            "require": {
+                "fzaninotto/faker": "^1.7",
+                "guzzlehttp/guzzle": "^6.3",
+                "phpunit/phpunit": "^5 || ^6 || ^7.0",
+                "symfony/console": "^3 || ^4.0"
+            },
+            "bin": [
+                "tripaltest"
+            ],
+            "type": "library",
+            "autoload": {
+                "psr-4": {
+                    "StatonLab\\TripalTestSuite\\": "src/"
+                },
+                "files": [
+                    "src/Helpers/helpers.php"
+                ]
+            },
+            "notification-url": "https://packagist.org/downloads/",
+            "license": [
+                "GPL-3.0"
+            ],
+            "authors": [
+                {
+                    "name": "Abdullah Almsaeed",
+                    "email": "aalmsaee@utk.edu"
+                },
+                {
+                    "name": "Bradford Condon",
+                    "email": "bcondon@utk.edu"
+                }
+            ],
+            "time": "2018-05-02T15:51:28+00:00"
+        },
+        {
+            "name": "symfony/console",
+            "version": "v4.0.9",
+            "source": {
+                "type": "git",
+                "url": "https://github.com/symfony/console.git",
+                "reference": "3e820bc2c520a87ca209ad8fa961c97f42e0b4ae"
+            },
+            "dist": {
+                "type": "zip",
+                "url": "https://api.github.com/repos/symfony/console/zipball/3e820bc2c520a87ca209ad8fa961c97f42e0b4ae",
+                "reference": "3e820bc2c520a87ca209ad8fa961c97f42e0b4ae",
+                "shasum": ""
+            },
+            "require": {
+                "php": "^7.1.3",
+                "symfony/polyfill-mbstring": "~1.0"
+            },
+            "conflict": {
+                "symfony/dependency-injection": "<3.4",
+                "symfony/process": "<3.3"
+            },
+            "require-dev": {
+                "psr/log": "~1.0",
+                "symfony/config": "~3.4|~4.0",
+                "symfony/dependency-injection": "~3.4|~4.0",
+                "symfony/event-dispatcher": "~3.4|~4.0",
+                "symfony/lock": "~3.4|~4.0",
+                "symfony/process": "~3.4|~4.0"
+            },
+            "suggest": {
+                "psr/log-implementation": "For using the console logger",
+                "symfony/event-dispatcher": "",
+                "symfony/lock": "",
+                "symfony/process": ""
+            },
+            "type": "library",
+            "extra": {
+                "branch-alias": {
+                    "dev-master": "4.0-dev"
+                }
+            },
+            "autoload": {
+                "psr-4": {
+                    "Symfony\\Component\\Console\\": ""
+                },
+                "exclude-from-classmap": [
+                    "/Tests/"
+                ]
+            },
+            "notification-url": "https://packagist.org/downloads/",
+            "license": [
+                "MIT"
+            ],
+            "authors": [
+                {
+                    "name": "Fabien Potencier",
+                    "email": "fabien@symfony.com"
+                },
+                {
+                    "name": "Symfony Community",
+                    "homepage": "https://symfony.com/contributors"
+                }
+            ],
+            "description": "Symfony Console Component",
+            "homepage": "https://symfony.com",
+            "time": "2018-04-30T01:23:47+00:00"
+        },
+        {
+            "name": "symfony/polyfill-mbstring",
+            "version": "v1.8.0",
+            "source": {
+                "type": "git",
+                "url": "https://github.com/symfony/polyfill-mbstring.git",
+                "reference": "3296adf6a6454a050679cde90f95350ad604b171"
+            },
+            "dist": {
+                "type": "zip",
+                "url": "https://api.github.com/repos/symfony/polyfill-mbstring/zipball/3296adf6a6454a050679cde90f95350ad604b171",
+                "reference": "3296adf6a6454a050679cde90f95350ad604b171",
+                "shasum": ""
+            },
+            "require": {
+                "php": ">=5.3.3"
+            },
+            "suggest": {
+                "ext-mbstring": "For best performance"
+            },
+            "type": "library",
+            "extra": {
+                "branch-alias": {
+                    "dev-master": "1.8-dev"
+                }
+            },
+            "autoload": {
+                "psr-4": {
+                    "Symfony\\Polyfill\\Mbstring\\": ""
+                },
+                "files": [
+                    "bootstrap.php"
+                ]
+            },
+            "notification-url": "https://packagist.org/downloads/",
+            "license": [
+                "MIT"
+            ],
+            "authors": [
+                {
+                    "name": "Nicolas Grekas",
+                    "email": "p@tchwork.com"
+                },
+                {
+                    "name": "Symfony Community",
+                    "homepage": "https://symfony.com/contributors"
+                }
+            ],
+            "description": "Symfony polyfill for the Mbstring extension",
+            "homepage": "https://symfony.com",
+            "keywords": [
+                "compatibility",
+                "mbstring",
+                "polyfill",
+                "portable",
+                "shim"
+            ],
+            "time": "2018-04-26T10:06:28+00:00"
+        },
+        {
+            "name": "theseer/tokenizer",
+            "version": "1.1.0",
+            "source": {
+                "type": "git",
+                "url": "https://github.com/theseer/tokenizer.git",
+                "reference": "cb2f008f3f05af2893a87208fe6a6c4985483f8b"
+            },
+            "dist": {
+                "type": "zip",
+                "url": "https://api.github.com/repos/theseer/tokenizer/zipball/cb2f008f3f05af2893a87208fe6a6c4985483f8b",
+                "reference": "cb2f008f3f05af2893a87208fe6a6c4985483f8b",
+                "shasum": ""
+            },
+            "require": {
+                "ext-dom": "*",
+                "ext-tokenizer": "*",
+                "ext-xmlwriter": "*",
+                "php": "^7.0"
+            },
+            "type": "library",
+            "autoload": {
+                "classmap": [
+                    "src/"
+                ]
+            },
+            "notification-url": "https://packagist.org/downloads/",
+            "license": [
+                "BSD-3-Clause"
+            ],
+            "authors": [
+                {
+                    "name": "Arne Blankerts",
+                    "email": "arne@blankerts.de",
+                    "role": "Developer"
+                }
+            ],
+            "description": "A small library for converting tokenized PHP source code into XML and potentially other formats",
+            "time": "2017-04-07T12:08:54+00:00"
+        },
+        {
+            "name": "webmozart/assert",
+            "version": "1.3.0",
+            "source": {
+                "type": "git",
+                "url": "https://github.com/webmozart/assert.git",
+                "reference": "0df1908962e7a3071564e857d86874dad1ef204a"
+            },
+            "dist": {
+                "type": "zip",
+                "url": "https://api.github.com/repos/webmozart/assert/zipball/0df1908962e7a3071564e857d86874dad1ef204a",
+                "reference": "0df1908962e7a3071564e857d86874dad1ef204a",
+                "shasum": ""
+            },
+            "require": {
+                "php": "^5.3.3 || ^7.0"
+            },
+            "require-dev": {
+                "phpunit/phpunit": "^4.6",
+                "sebastian/version": "^1.0.1"
+            },
+            "type": "library",
+            "extra": {
+                "branch-alias": {
+                    "dev-master": "1.3-dev"
+                }
+            },
+            "autoload": {
+                "psr-4": {
+                    "Webmozart\\Assert\\": "src/"
+                }
+            },
+            "notification-url": "https://packagist.org/downloads/",
+            "license": [
+                "MIT"
+            ],
+            "authors": [
+                {
+                    "name": "Bernhard Schussek",
+                    "email": "bschussek@gmail.com"
+                }
+            ],
+            "description": "Assertions to validate method input/output with nice error messages.",
+            "keywords": [
+                "assert",
+                "check",
+                "validate"
+            ],
+            "time": "2018-01-29T19:49:41+00:00"
+        }
+    ],
+    "packages-dev": [],
+    "aliases": [],
+    "minimum-stability": "stable",
+    "stability-flags": [],
+    "prefer-stable": false,
+    "prefer-lowest": false,
+    "platform": [],
+    "platform-dev": []
+}

+ 87 - 2
legacy/tripal_feature/theme/tripal_feature.theme.inc

@@ -53,7 +53,7 @@ function tripal_feature_load_featureloc_sequences($feature_id, $featurelocs) {
 
   // get the list of relationships (including any aggregators) and iterate
   // through each one to find information needed to color-code the reference sequence
-  $relationships = _tripal_feature_get_aggregate_relationships($feature_id);
+  $relationships = tripal_feature_get_aggregate_relationships($feature_id);
   if (!$relationships) {
     return array();
   }
@@ -243,7 +243,7 @@ function tripal_feature_load_featurelocs($feature_id, $side = 'as_parent', $aggr
   if ($aggregate and strcmp($side, 'as_parent')==0) {
     // get the relationships for this feature without substituting any children
     // for the parent. We want all relationships
-    $relationships = _tripal_feature_get_aggregate_relationships($feature_id, 0);
+    $relationships = tripal_feature_get_aggregate_relationships($feature_id, 0);
     foreach ($relationships as $rindex => $rel) {
       // get the featurelocs for each of the relationship features
       $rel_featurelocs = tripal_feature_load_featurelocs($rel->subject_id, 'as_child', 0);
@@ -945,3 +945,88 @@ function tripal_feature_preprocess_tripal_feature_bar_chart_type_organism_summar
   // it in our js script.
   drupal_add_js(array('tripalFeature' => array('admin' => $vars['chart_details'])), 'setting');
 }
+
+
+/**
+ * Get features related to the current feature to a given depth. Recursive function.
+ *
+ * @param $feature_id
+ * @param $substitute
+ * @param $levels
+ * @param $base_type_id
+ * @param $depth
+ *
+ */
+function tripal_feature_get_aggregate_relationships($feature_id, $substitute=1,
+  $levels=0, $base_type_id=NULL, $depth=0) {
+    
+    // we only want to recurse to as many levels deep as indicated by the
+    // $levels variable, but only if this variable is > 0. If 0 then we
+    // recurse until we reach the end of the relationships tree.
+    if ($levels > 0 and $levels == $depth) {
+      return NULL;
+    }
+    
+    // first get the relationships for this feature
+    return tripal_feature_load_relationships($feature_id, 'as_object');
+    
+}
+
+/**
+ * Get the relationships for a feature.
+ *
+ * @param $feature_id
+ *   The feature to get relationships for
+ * @param $side
+ *   The side of the relationship this feature is (ie: 'as_subject' or
+ *   'as_object')
+ *
+ *
+ */
+function tripal_feature_load_relationships($feature_id, $side = 'as_subject') {
+  // Get the relationships for this feature.  The query below is used for both
+  // querying the object and subject relationships
+  $sql = "
+    SELECT
+      FS.name as subject_name, FS.uniquename as subject_uniquename,
+      CVTS.name as subject_type, CVTS.cvterm_id as subject_type_id,
+      FR.subject_id, FR.type_id as relationship_type_id, FR.object_id, FR.rank,
+      CVT.name as rel_type,
+      FO.name as object_name, FO.uniquename as object_uniquename,
+      CVTO.name as object_type, CVTO.cvterm_id as object_type_id
+    FROM {feature_relationship} FR
+     INNER JOIN {cvterm} CVT  ON FR.type_id    = CVT.cvterm_id
+     INNER JOIN {feature} FS  ON FS.feature_id = FR.subject_id
+     INNER JOIN {feature} FO  ON FO.feature_id = FR.object_id
+     INNER JOIN {cvterm} CVTO ON FO.type_id    = CVTO.cvterm_id
+     INNER JOIN {cvterm} CVTS ON FS.type_id    = CVTS.cvterm_id
+  ";
+  if (strcmp($side, 'as_object')==0) {
+    $sql .= " WHERE FR.object_id = :feature_id";
+  }
+  if (strcmp($side, 'as_subject')==0) {
+    $sql .= " WHERE FR.subject_id = :feature_id";
+  }
+  $sql .= " ORDER BY FR.rank";
+  
+  // Get the relationships.
+  $results = chado_query($sql, array(':feature_id' => $feature_id));
+  
+  // Iterate through the relationships, put these in an array and add
+  // in the Drupal node id if one exists.
+  $i=0;
+  $nodesql = "SELECT nid FROM {chado_feature} WHERE feature_id = :feature_id";
+  $relationships = array();
+  while ($rel = $results->fetchObject()) {
+    $node = db_query($nodesql, array(':feature_id' => $rel->subject_id))->fetchObject();
+    if ($node) {
+      $rel->subject_nid = $node->nid;
+    }
+    $node = db_query($nodesql, array(':feature_id' => $rel->object_id))->fetchObject();
+    if ($node) {
+      $rel->object_nid = $node->nid;
+    }
+    $relationships[$i++] = $rel;
+  }
+  return $relationships;
+}

+ 0 - 44
legacy/tripal_pub/api/tripal_pub.DEPRECATED.inc

@@ -26,28 +26,6 @@ function pub_search($search_array, $offset, $limit, &$total_records) {
   return tripal_search_publications($search_array, $offset, $limit, $total_records);
 }
 
-/**
- * @deprecated Restructured API to make naming more readable and consistent.
- * Function was deprecated in Tripal 2.0 and will be removed 2 releases from now.
- * This function has been replaced by tripal_get_publication().
- *
- * @see tripal_get_publication().
- */
-function chado_get_publication($identifiers, $options = array()) {
-
-  tripal_report_error(
-    'tripal_deprecated',
-    TRIPAL_NOTICE,
-    "DEPRECATED: %old_function has been replaced with %new_function. Please update your code.",
-    array(
-      '%old_function'=>'chado_get_publication',
-      '%new_function' => 'tripal_get_publication'
-    )
-  );
-
-  return tripal_get_publication($identifiers, $options);
-}
-
 /**
  * @deprecated Restructured API to make naming more readable and consistent.
  * Function was deprecated in Tripal 2.0 and will be removed 2 releases from now.
@@ -70,28 +48,6 @@ function chado_does_pub_exist($pub_details) {
   return tripal_publication_exists($pub_details);
 }
 
-/**
- * @deprecated Restructured API to make naming more readable and consistent.
- * Function was deprecated in Tripal 2.0 and will be removed 2 releases from now.
- * This function has been replaced by tripal_reimport_publications().
- *
- * @see tripal_reimport_publications().
- */
-function chado_reimport_publications($do_contact = FALSE, $dbxref = NULL, $db = NULL) {
-
-  tripal_report_error(
-    'tripal_deprecated',
-    TRIPAL_NOTICE,
-    "DEPRECATED: %old_function has been replaced with %new_function. Please update your code.",
-    array(
-      '%old_function'=>'chado_reimport_publications',
-      '%new_function' => 'tripal_reimport_publications'
-    )
-  );
-
-  return tripal_reimport_publications($do_contact, $dbxref, $db);
-}
-
 /**
  * @deprecated Restructured API to make naming more readable and consistent.
  * Function was deprecated in Tripal 2.0 and will be removed 2 releases from now.

+ 24 - 2
phpunit.xml

@@ -1,11 +1,33 @@
+<?xml version="1.0" encoding="UTF-8"?>
 <phpunit xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
          xsi:noNamespaceSchemaLocation="phpunit.xsd"
+         convertErrorsToExceptions="true"
+         convertNoticesToExceptions="true"
+         convertWarningsToExceptions="true"
          bootstrap="tests/bootstrap.php"
          verbose="true"
          colors="true">
     <testsuites>
-        <testsuite name="default">
-            <directory suffix=".test">./tests/</directory>
+        <testsuite name="tripal">
+            <directory suffix="Test.php">tests/tripal</directory>
+        </testsuite>
+        <testsuite name="tripal_chado">
+            <directory suffix="Test.php">tests/tripal_chado/</directory>
+        </testsuite>
+        <testsuite name="tripal_bulk_loader">
+            <directory suffix="Test.php">tests/tripal_bulk_loader/</directory>
+        </testsuite>
+        <testsuite name="tripal_chado_views">
+            <directory suffix="Test.php">tests/tripal_chado_views/</directory>
+        </testsuite>
+        <testsuite name="tripal_daemon">
+            <directory suffix="Test.php">tests/tripal_daemon/</directory>
+        </testsuite>
+        <testsuite name="tripal_ds">
+            <directory suffix="Test.php">tests/tripal_ds/</directory>
+        </testsuite>
+        <testsuite name="tripal_ws">
+            <directory suffix="Test.php">tests/tripal_ws/</directory>
         </testsuite>
     </testsuites>
 </phpunit>

+ 73 - 0
tests/DataFactory.php

@@ -0,0 +1,73 @@
+<?php
+
+use StatonLab\TripalTestSuite\Database\Factory;
+
+/**
+ * Data Factory
+ * -----------------------------------------------------------
+ * This is where you can define factories for use in tests and
+ * database seeders.
+ *
+ * @docs https://github.com/statonlab/TripalTestSuite
+ */
+
+/** @see  StatonLab\TripalTestSuite\Database\Factory::define() */
+Factory::define('chado.cv', function (Faker\Generator $faker) {
+    return [
+        'name' => $faker->name,
+        'definition' => $faker->text,
+    ];
+});
+
+/** @see  StatonLab\TripalTestSuite\Database\Factory::define() */
+Factory::define('chado.db', function (Faker\Generator $faker) {
+    return [
+        'name' => $faker->name,
+        'description' => $faker->text,
+        'urlprefix' => $faker->url,
+        'url' => $faker->url,
+    ];
+});
+
+/** @see  StatonLab\TripalTestSuite\Database\Factory::define() */
+Factory::define('chado.dbxref', function (Faker\Generator $faker) {
+    return [
+        'db_id' => factory('chado.db')->create()->db_id,
+        'accession' => $faker->numberBetween(),
+        'version' => $faker->numberBetween(),
+        'description' => $faker->text,
+    ];
+});
+
+/** @see  StatonLab\TripalTestSuite\Database\Factory::define() */
+Factory::define('chado.cvterm', function (Faker\Generator $faker) {
+    return [
+        'cv_id' => factory('chado.cv')->create()->cv_id,
+        'dbxref_id' => factory('chado.dbxref')->create()->dbxref_id,
+        'name' => $faker->name,
+        'definition' => $faker->text,
+        'is_obsolete' => 0,
+        'is_relationshiptype' => 0,
+    ];
+});
+
+/** @see  StatonLab\TripalTestSuite\Database\Factory::define() */
+Factory::define('chado.organism', function (Faker\Generator $faker) {
+    return [
+        'abbreviation' => $faker->name,
+        'genus' => $faker->name,
+        'species' => $faker->name,
+        'common_name' => $faker->name,
+        'type_id' => factory('chado.cvterm')->create()->cvterm_id,
+    ];
+});
+
+/** @see  StatonLab\TripalTestSuite\Database\Factory::define() */
+Factory::define('chado.feature', function (Faker\Generator $faker) {
+    return [
+        'name' => $faker->name,
+        'uniquename' => $faker->unique()->name,
+        'organism_id' => factory('chado.organism')->create()->organism_id,
+        'type_id' => factory('chado.cvterm')->create()->cvterm_id,
+    ];
+});

+ 28 - 0
tests/DatabaseSeeders/UsersTableSeeder.php

@@ -0,0 +1,28 @@
+<?php
+
+namespace Tests\DatabaseSeeders;
+
+use StatonLab\TripalTestSuite\Database\Seeder;
+
+class UsersTableSeeder extends Seeder
+{
+  /**
+   * Seeds the database with users.
+   */
+  public function up()
+  {
+    $new_user = [
+      'name' => 'test user',
+      'pass' => 'secret',
+      'mail' => 'test@example.com',
+      'status' => 1,
+      'init' => 'Email',
+      'roles' => [
+        DRUPAL_AUTHENTICATED_RID => 'authenticated user',
+      ],
+    ];
+
+    // The first parameter is sent blank so a new user is created.
+    user_save(new \stdClass(), $new_user);
+  }
+}

+ 2 - 37
tests/bootstrap.php

@@ -1,39 +1,4 @@
 <?php
-// Set environment variables
-test_suite_read_and_set_environment_variables();
+require_once __DIR__.'/../vendor/autoload.php';
 
-// Get Drupal root path
-$drupal_root = getenv('DRUPAL_ROOT');
-define('DRUPAL_ROOT', $drupal_root ?: '/var/www/html');
-
-// Get Drupal bootstrap functions
-require_once DRUPAL_ROOT.'/includes/bootstrap.inc';
-$_SERVER['REMOTE_ADDR'] = '127.0.0.1';
-
-// Bootstrap Drupal.
-$current_dir = getcwd();
-chdir(DRUPAL_ROOT);
-drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);
-chdir($current_dir);
-
-/**
- * Get and set environment variables from .env file if it exists.
- *
- * @throws \Exception
- */
-function test_suite_read_and_set_environment_variables() {
-  $filename = __DIR__.'/.env';
-  if(file_exists($filename)) {
-    $file = fopen($filename, 'r');
-    while ($line = str_replace("\n", '', fgets($file))) {
-      // break line into key value
-      $env = explode('=', $line);
-      if(count($env) === 2) {
-        putenv($line);
-      } else {
-        throw new Exception('Invalid environment line: ' . $line);
-      }
-    }
-    fclose($file);
-  }
-}
+new \StatonLab\TripalTestSuite\TripalTestBootstrap();

+ 2 - 0
tests/example.env

@@ -0,0 +1,2 @@
+DRUPAL_ROOT=/var/www/html
+FAKER_LOCALE=en_US

+ 6 - 7
tests/TripalJobsTest.test → tests/tripal/api/TripalJobsApiTest.php

@@ -1,8 +1,12 @@
 <?php
+namespace Tests\tripal\api;
 
-use PHPUnit\Framework\TestCase;
+use StatonLab\TripalTestSuite\DBTransaction;
+use StatonLab\TripalTestSuite\TripalTestCase;
 
-class TripalJobsTest extends TestCase {
+class TripalJobsApiTest extends TripalTestCase {
+
+  use DBTransaction;
 
   /**
    * Tests the ability to create a tripal job.
@@ -12,10 +16,5 @@ class TripalJobsTest extends TestCase {
   public function should_create_a_tripal_job() {
     $job_id = tripal_add_job('Test adding jobs', 'tripal', 'tripal_tripal_cron_notification', [], 1);
     $this->assertTrue(is_numeric($job_id));
-
-    // Clean up
-    if($job_id) {
-      db_query('DELETE FROM {tripal_jobs} WHERE job_id = :id', [':id' => $job_id]);
-    }
   }
 }

+ 71 - 0
tests/tripal_chado/api/TripalChadoAPITest.php

@@ -0,0 +1,71 @@
+<?php
+namespace Tests\tripal_chado\api;
+
+
+use StatonLab\TripalTestSuite\DBTransaction;
+use StatonLab\TripalTestSuite\TripalTestCase;
+
+class TripalChadoAPITest extends TripalTestCase {
+
+  use DBTransaction;
+
+  /**
+   * Test the ability to publish Chado organism records as entities.
+   *
+   * @group api
+   * @group failing
+   */
+  public function test_tripal_chado_publish_records() {
+    $genus_string = 'a_genius_genus';
+    //create an organism, publish it
+    $organism = factory('chado.organism')->create([
+      'genus' => $genus_string,
+      'species' => 'fake_species',
+    ]);
+    //get bundle ID for organism
+    $bundle = db_select('public.chado_bundle', 'CB')
+      ->fields('CB', ['bundle_id'])
+      ->condition('data_table', 'organism')
+      ->execute()->fetchField();
+
+    var_dump($bundle);
+    $values = ['bundle_name' => 'bio_data_' . $bundle];
+
+ //   ob_start();//dont display the job message
+    $bool = chado_publish_records($values);
+   // ob_end_clean();
+
+    $this->assertTrue($bool, 'Publishing a fake organism record failed');
+
+    //ensure that our entity was created
+    $query = db_select('chado.organism', 'O')
+      ->fields('O', ['organism_id']);
+    $query->join('public.chado_bio_data_' . $bundle, 'CBD', 'O.organism_id = CBD.record_id');
+    $query->condition('O.genus', $genus_string);
+    $organism_id = $query->execute()->fetchField();
+    $this->assertNotNull($organism_id, 'Organism with record ID not found in chado_bio_data table.');
+  }
+
+  /**
+   * Test chado_publish_records returns false given bad bundle.
+   *
+   * @group api
+   */
+  public function test_tripal_chado_publish_records_false_with_bad_bundle() {
+    putenv("TRIPAL_SUPPRESS_ERRORS=TRUE");//this will fail, so we suppress the tripal error reporter
+    $bool = chado_publish_records(['bundle_name' => 'never_in_a_million_years']);
+    $this->assertFalse($bool);
+    putenv("TRIPAL_SUPPRESS_ERRORS");//unset
+  }
+
+  /**
+   * calls chado_get_tokens.
+   *
+   * @group api
+   */
+  public function test_chado_get_tokens() {
+    $tokens = chado_get_tokens('organism');
+    $this->assertNotEmpty($tokens);
+    $this->assertArrayHasKey('[organism.organism_id]', $tokens);
+  }
+}

+ 19 - 0
tests/tripal_chado/api/TripalChadoCustomTablesAPITest.php

@@ -0,0 +1,19 @@
+<?php
+namespace Tests\tripal_chado\api;
+
+use StatonLab\TripalTestSuite\DBTransaction;
+use StatonLab\TripalTestSuite\TripalTestCase;
+
+class TripalChadoCustomTablesAPITest extends TripalTestCase {
+  // Uncomment to auto start and rollback db transactions per test method.
+  // use DBTransaction;
+
+  /**
+   * Basic test example.
+   * Tests must begin with the word "test".
+   * See https://phpunit.readthedocs.io/en/latest/ for more information.
+   */
+  public function testBasicExample() {
+    $this->assertTrue(true);
+  }
+}

+ 113 - 0
tests/tripal_chado/api/TripalChadoOrganismAPITest.php

@@ -0,0 +1,113 @@
+<?php
+
+namespace Tests\tripal_chado\api;
+
+use StatonLab\TripalTestSuite\DBTransaction;
+use StatonLab\TripalTestSuite\TripalTestCase;
+
+class TripalChadoOrganismAPITest extends TripalTestCase {
+
+  use DBTransaction;
+
+  /**
+   * Test tripal_get_organism.
+   *
+   * @group api
+   */
+  public function test_tripal_get_organism() {
+    $genus_string = 'a_genius_genus';
+    $species_string = 'fake_species';
+
+    $organism = factory('chado.organism')->create([
+      'genus' => $genus_string,
+      'species' => $species_string,
+    ]);
+
+    $results = [];
+
+    $results[] = chado_get_organism(['organism_id' => $organism->organism_id]);
+    $results[] = chado_get_organism([
+      'genus' => $genus_string,
+      'species' => $species_string,
+    ]);
+
+    foreach ($results as $result) {
+      $this->assertNotFalse($result);
+      $this->assertNotNull($result);
+      $this->assertObjectHasAttribute('genus', $result);
+      $this->assertEquals($genus_string, $result->genus);
+    }
+  }
+
+  /**
+   * Test tripal_get_organism doesn't return anything
+   * when the organism doesn't exist.
+   */
+  public function test_tripal_get_organism_fails_gracefully() {
+    $result = chado_get_organism([
+      'genus' => uniqid(),
+      'species' => uniqid(),
+    ]);
+
+    $this->assertNull($result);
+  }
+
+  /**
+   * Test tripal_get_organism_scientific_name
+   *
+   * @group  api
+   */
+  function test_tripal_get_organism_scientific_name() {
+    $genus_string = 'a_genius_genus';
+    $species_string = 'fake_species';
+    $infraspecific_name = "infrawhat?";
+    $term = factory('chado.cvterm')->create();
+
+    $organism = factory('chado.organism')->create([
+      'genus' => $genus_string,
+      'species' => $species_string,
+      'infraspecific_name' => $infraspecific_name,
+      'type_id' => $term->cvterm_id,
+    ]);
+
+    $sci_name = chado_get_organism_scientific_name($organism);
+    $this->assertEquals(implode(" ", [
+      $genus_string,
+      $species_string,
+      $term->name,
+      $infraspecific_name,
+    ]), $sci_name);
+  }
+
+  //TODO: Can't test because it uses drupal_json_output.
+  //Need HTTP testing.
+  //
+  //  function test_tripal_autocomplete_organism(){
+  //
+  //    $genus_string = 'a_genius_genus';
+  //    $species_string = 'fake_species';
+  //
+  //    $organism = factory('chado.organism')->create([
+  //      'genus' => $genus_string,
+  //      'species' => $species_string,
+  //    ]);
+  //
+  //    tripal_autocomplete_organism(substr($genus_string, 0, 4));
+  //
+  //   //$this->assertEquals($genus_string, $auto_complete);
+  //  }
+
+  //This function is Tripal 2, and needs to be updated or deprecated
+
+  //  function test_tripal_get_organism_select_options_sycned_only_false(){
+  //
+  //    db_truncate('chado.organism');
+  //    factory('chado.organism', 20)->create();
+  //
+  //    $options = tripal_get_organism_select_options(FALSE);
+  //
+  //    $this->assertNotEmpty($options);
+  //    $this->assertGreaterThan(20, count($options));
+  //
+  //  }
+}

+ 28 - 4
tripal/api/tripal.DEPRECATED.api.inc

@@ -1,5 +1,25 @@
 <?php
+
+/**
+ * @file
+ *
+ * These api functions are deprecated, if your site is currently using them
+ * please update your code with the newer tripal.jobs.api functions.
+ */
+
+/**
+ * @defgroup tripal_DEPRECATED_jobs_api Data Collections
+ * @ingroup tripal_api
+ * @{
+ * Deprecated legacy api code from Tripal 2. Please see tripal.jobs.api.inc
+ * for the new Tripal 3 functions.
+ * @}
+ */
+
+
 /**
+ * DEPRECATED
+ * 
  * Returns the end time for a given job
  *
  * @param $job
@@ -8,7 +28,7 @@
  * @return
  *   The end time of the job if it was already run and empty otherwise
  *
- * @ingroup tripal_jobs_api
+ * @ingroup tripal_DEPRECATED_jobs_api
  */
 function tripal_get_job_end($job) {
   tripal_report_error('tripal_deprecated', TRIPAL_NOTICE,
@@ -31,6 +51,8 @@ function tripal_get_job_end($job) {
 }
 
 /**
+ * DEPRECATED
+ * 
  * Returns the start time for a given job
  *
  * @param $job
@@ -39,7 +61,7 @@ function tripal_get_job_end($job) {
  * @return
  *   The start time of the job if it was already run and either "Cancelled" or "Not Yet Started" otherwise
  *
- * @ingroup tripal_jobs_api
+ * @ingroup tripal_DEPRECATED_jobs_api
  */
 function tripal_get_job_start($job) {
 
@@ -67,15 +89,17 @@ function tripal_get_job_start($job) {
 }
 
 /**
+ * DEPRECATED
+ * 
  * Returns the date the job was added to the queue
  *
  * @param $job
  *   An object describing the job
  *
  * @return
- *   The date teh job was submitted
+ *   The date the job was submitted
  *
- * @ingroup tripal_jobs_api
+ * @ingroup tripal_DEPRECATED_jobs_api
  */
 function tripal_get_job_submit_date($job) {
 

+ 21 - 0
tripal/api/tripal.d3js.api.inc

@@ -1,11 +1,32 @@
 <?php
+
 /**
+ * @file
  *
+ * Provides the API for loading d3js onto pages.
+ */
+
+/**
+ * @defgroup tripal_d3js_api d3js
+ * @ingroup tripal_api
+ * @{
+ * D3.js is a JavaScript library for producing dynamic, interactive data 
+ * visualizations in web browsers. It makes use of the widely implemented SVG, 
+ * HTML5, and CSS standards. For more information on how to use d3js please see
+ * https://github.com/d3/d3. 
+ * 
+ * For an example of d3 usage in Tripal please review 
+ * tripal_chado/includes/tripal_chado.phylotree.inc and 
+ * tripal_chado/theme/js/d3.phylogram.js
+ * 
+ * @}
  */
 
 
 /**
  * Load D3.js releated javascripts for the current page.
+ * 
+ * @ingroup tripal_d3js_api
  */
 function tripal_add_d3js() {
   $library = array('loaded' => FALSE);

+ 99 - 81
tripal/api/tripal.entities.api.inc

@@ -1,8 +1,10 @@
 <?php
+
 /**
  * @file
  * Provides an application programming interface (API) for working with
- * TripalEntity content types (bundles) and their entities.
+ * TripalEntity content types (bundles) and their entities. 
+ * 
  */
 
 /**
@@ -11,10 +13,41 @@
  * @{
  * Provides an application programming interface (API) for working with
  * TripalEntity content types (bundles) and their entities.
+ * 
+ * Bundles (Content Types): Bundles are types of content in a Drupal site.  
+ * By default, Drupal provides the Basic Page and Article content types, 
+ * and Drupal allows a site developer to create new content types on-the-fly 
+ * using the administrative interface--no programming required.  Tripal also 
+ * provides several Content Type by default. During installation of Tripal the 
+ * Organism, Gene, Project, Analysis and other content types are created 
+ * automatically.  The site developer can then create new content types for 
+ * different biological data--again, without any programming required.
+ * 
+ * In order to to assist with data exchange and use of common data formats, 
+ * Tripal Bundles are defined using a controlled vocabulary term (cvterm). 
+ * For example, a "Gene" Bundle is defined using the Sequence Ontology term for 
+ * gene whose term accession is: SO:0000704. This mapping allows Tripal to 
+ * compare content across Tripal sites, and expose data to computational tools 
+ * that understand these vocabularies. By default, Tripal uses Chado as its 
+ * primary data storage back-end.  
+ * 
+ * Entity: An entity is a discrete data record.  Entities are most commonly
+ * seen as "pages" on a Drupal web site and are instances of a Bundle 
+ * (i.e content type). When data is published on a Tripal site such as 
+ * organisms, genes, germplasm, maps, etc., each record is represented by a 
+ * single entity with an entity ID as its only attribute. All other 
+ * information that the entity provides is made available via Fields.  
+ * 
+ * For more information please see: 
+ * http://tripal.info/tutorials/v3.x/developers-handbook/structure
  * @}
  *
  */
 
+/**
+ * @section
+ * Hooks.
+ */
 
 /**
  * Allows a module to make changes to an entity object after creation.
@@ -84,14 +117,16 @@ function hook_bundle_delete($bundle) {
  * Implement this hook to define default formats for Tripal Content Types.
  *
  * @param TripalBundle $bundle
- *   A tripal content type entity with information to be used for determining the default title format.
+ *   A tripal content type entity with information to be used for determining 
+ *   the default title format.
  * @param array $available_tokens
  *   An array of available tokens for this particular tripal content type.
  *
  * @return array
- *   An array of potential formats. The lightest weighted format suggested by all modules will be chosen.
- *   Each array item should consist of a 'weight' and 'format'. See the hook implementation below
- *   for examples.
+ *   An array of potential formats. The lightest weighted format suggested by 
+ *   all modules will be chosen.
+ *   Each array item should consist of a 'weight' and 'format'. See the hook 
+ *   implementation below for examples.
  *    - weight: an integer used to determine priority of suggestions.
  *        The smaller/lighter the number the higher the priority.
  *        Best practice is to use a weight less than 0 for extension modules.
@@ -113,15 +148,15 @@ function hook_tripal_default_title_format($bundle, $available_tokens) {
 
   // If it's the term you are interested in then suggest a format.
   if ($term->name == 'organism') {
-
-    // To suggest a format, add an element to the array with a format & weight key.
+    // To suggest a format, add an element to the array with a format & weight 
+    // key.
     $format[] = array(
-      // This is the format/pattern you suggest be used to determine the title of organism pages.
+      // This is the format/pattern you suggest be used to determine the title 
+      // of organism pages.
       'format' => '[organism__genus] [organism__species]',
       // The weight/priority of your suggestion.
       'weight' => -5
     );
-
   }
 
   // Say you know that in your particular site, all 'names' are required
@@ -139,13 +174,18 @@ function hook_tripal_default_title_format($bundle, $available_tokens) {
   return $format;
 }
 
+/**
+ * @section
+ * Entity.
+ */
+
 /**
  * A replacement for the entity_load function of Drupal.
  *
  * This function should be used for loading of Tripal Entities. It provides
  * greater control to limit which fields are loaded with the entity. The
  * entity_load() function of Drupal will automatically attach all fields at
- * once but this may not be desired as some fields can be comples and large and
+ * once but this may not be desired as some fields can be complex and large, and
  * the site developer may desire loading of fields via AJAX or the user of
  * web services may wish to specify the fields they want to include.
  *
@@ -192,14 +232,18 @@ function tripal_load_entity($entity_type, $ids = FALSE, $reset = FALSE,
 
   return $ec->load($ids, $conditions, $field_ids, $cache);
 }
+
 /**
  * Retrieves a TripalTerm entity that matches the given arguments.
  *
  * @param $values
- *   An associative array used to match a term.  Valid keys may be 'vocabulary',
- *   'accession, or 'term_id'.  The keys 'vocabulary' and 'accession' must
- *   always be used together to uniquely identify a term.  The key 'term_id'
- *   can be used alone to uniquely identify a term.
+ *   An associative array used to match a term.  
+ *   Valid keys may be: 
+ *        - vocabulary: Must always be used with accession to uniquely 
+ *                        identify a term.  
+ *        - accession: Must always be used with vocabulary to uniquely 
+ *                       identify a term. 
+ *        - term_id: Can be used alone to uniquely identify a term.
  *
  * @return
  *   A TripalTerm entity object or NULL if not found.
@@ -240,8 +284,10 @@ function tripal_load_term_entity($values) {
  * Retrieves a TripalVocab entity that maches the given arguments.
  *
  * @param $values
- *   An associative array used to match a vocabulary.  The valid keys are
- *   'vocab_id' and 'vocabulary'.
+ *   An associative array used to match a vocabulary.  
+ *   The valid keys are:
+ *      - vocab_id: integer id of the vocabulary.
+ *      - vocabulary: string name of vocabulary.
  *
  * @return
  * A TripalVocab entity object or NULL if not found.
@@ -320,13 +366,16 @@ function tripal_load_bundle_entity($values) {
  * @param $details
  *   A human-readable sentence or two describing the issue.
  * @param $type
- *   A one word type indicating the type of notification. Tripal types include:  Jobs, Fields.
- *   If not type is required please pass NULL.
+ *   A one word type indicating the type of notification. Tripal types include: 
+ *   Jobs, Fields.
+ *   If no type is required please pass NULL.
  * @param $actions
- *   A serialized PHP associative array containing the link and URL for each action.
+ *   A serialized PHP associative array containing the link and URL for each 
+ *   action.
  *   If not type is required please pass NULL.
  * @param $submitter_id
- *   A unique ID provided by the submitter for checking to make sure that the notification is not added more than once.
+ *   A unique ID provided by the submitter for checking to make sure that the 
+ *   notification is not added more than once.
  *
  * @ingroup tripal_entities_api
  */
@@ -356,6 +405,7 @@ function tripal_add_notification($title, $details, $type, $actions, $submitter_i
     }
   }
 }
+
 /**
  * Creates a new Tripal Entity type (i.e. bundle).
  *
@@ -459,47 +509,6 @@ function tripal_create_bundle($args, &$error = '') {
   return $bundle;
 }
 
-/*
- * Checks access permissions for a given entity.
- *
- * This function is set for TripalEntity access checking in the
- * tripal_entity_info() under the 'access callback' element.
- *
- *
- * @param $entity
- *   The entity to check access for.
-
-function tripal_entity_permissions($entity) {
-
-  if ($entity) {
-    $bundle_name = $entity->bundle;
-  }
-  else {
-    return FALSE;
-  }
-
-  // Get the bundle object.
-  $bundle = tripal_load_bundle_entity(array('name' => $bundle_name));
-
-  // Identify the administrative user roles.
-  $admin_role = user_role_load_by_name('administrator');
-  $roles = array($admin_role->rid => $admin_role->name);
-  // Define the permissions.
-  $permission_for_role = array(
-    'create ' . $bundle->label => TRUE,
-    'view ' . $bundle->label => TRUE,
-    'edit ' . $bundle->label => TRUE,
-    'delete ' . $bundle->label => TRUE,
-  );
-  // Assign the permissions
-  foreach($roles as $role => $value){
-    user_role_grant_permissions($role, $permission_for_role);
-    watchdog('debug', '<pre>tripal_entity_permissions  $role: '. print_r($role, TRUE) .'</pre>');
-  }
-
-  return TRUE;
-}
- */
 /**
  * Retrieves a list of the content types.
  *
@@ -517,7 +526,8 @@ function tripal_get_content_types() {
 }
 
 /**
- * Refreshes the bundle such that new fields added by modules will be found during cron.
+ * Refreshes the bundle such that new fields added by modules will be found 
+ * during cron.
  *
  * @param $bundle_name
  *   The name of the bundle to refresh (e.g. bio_data_4).
@@ -710,22 +720,22 @@ function tripal_create_bundle_fields($bundle, $term) {
  * @param $field_info
  *   An associative array containing the field information.  The following
  *   key/value pairs are supported:
- *     'field_type' : a valid field type.  May be any of the Drupal default
+ *     - field_type: a valid field type.  May be any of the Drupal default
  *       fields, one created by the tripal_chado module or another custom module.
- *     'widget_type' : a valid widget type. May be any of the Drupal default
+ *     - widget_type: a valid widget type. May be any of the Drupal default
  *       fields, one created by the tripal_chado module or another custom module.
- *     'field_settings' : an array of settings that are appropriate for the
+ *     - field_settings: an array of settings that are appropriate for the
  *       selected field type.
- *     'widget_settings' : an array of settings that are appropriate for the
+ *     - widget_settings: an array of settings that are appropriate for the
  *       selected widget type.
- *     'description' :  a default description for this field.
- *     'label' : a label used as a header for this field.
- *     'is_required' : indicates if the field is required in the edit form.
- *     'cardinality' : indicates the number of values this field can support.
+ *     - description:  a default description for this field.
+ *     - label: a label used as a header for this field.
+ *     - is_required: indicates if the field is required in the edit form.
+ *     - cardinality: indicates the number of values this field can support.
  *       the default is 1 (meaning only one value). Use a value of
  *       FIELD_CARDINALITY_UNLIMITED for unlimited number of values.
- *     'default_value' : A default value for the field.
- *     'format' : A string indicating the format for the field. Must be
+ *     - default_value: A default value for the field.
+ *     - format: A string indicating the format for the field. Must be
  *       specific to the field.
  * @param $entity_type_name
  *   The entity type name.
@@ -874,7 +884,8 @@ function tripal_set_bundle_variable($variable_name, $bundle_id, $value) {
     }
   }
 
-  // And then we need to write the new format to the tripal_bundle_variables table.
+  // And then we need to write the new format to the tripal_bundle_variables 
+  // table.
   $record = array(
     'bundle_id' => $bundle_id,
     'variable_id' => $variable->variable_id,
@@ -979,7 +990,8 @@ function tripal_get_default_title_format($bundle) {
   if (!$format) {
     $tmp = array();
 
-    // Check which tokens are required fields and join them into a default format.
+    // Check which tokens are required fields and join them into a default 
+    // format.
     foreach($tokens as $token) {
       if ($token['required']) {
         $tmp[] = $token['token'];
@@ -1067,7 +1079,8 @@ function tripal_get_entity_tokens($entity, $options = array()) {
  * @param TripalEntity $entity
  *   The entity with field values used to find values of tokens.
  * @param TripalBundle $bundle_entity
- *   The bundle enitity containing special values sometimes needed for token replacement.
+ *   The bundle enitity containing special values sometimes needed for token 
+ *   replacement.
  *
  * @return
  *   The string will all tokens replaced with values.
@@ -1086,7 +1099,7 @@ function tripal_replace_entity_tokens($string, &$entity, $bundle_entity = NULL)
     return $string;
   }
 
-  // If the field are not loaded for the entity then we want to load them
+  // If the fields are not loaded for the entity then we want to load them
   // but we won't do a field_attach_load() as that will load all of the
   // fields. For syncing (publishing) of content loading all fields for
   // all synced entities causes extreme slowness, so we'll only attach
@@ -1334,13 +1347,16 @@ function _tripal_get_bundle_field_element_details($elements, &$field_details) {
 }
 
 /**
- *
- * @param unknown $bundle_name
+ * Is this completed? It doesn't look right and I can't find it used anywhere
+ * in the existing code. 
+ * 
+ * @param $bundle_name
+ *   The name of the bundle (e.g. bio_data_xx)
  * @param unknown $values
  *
  * @throws Exception
  *
- * @ingroup tripal_entities_api
+ * 
  */
 function tripal_insert_entity($bundle_name, $values){
   global $user;
@@ -1379,7 +1395,7 @@ function tripal_insert_entity($bundle_name, $values){
     }
   }
 
-  // Make sure that all required fields are presnet
+  // Make sure that all required fields are present.
 
   // TODO: make sure the user has permission to do this.
   $ec = entity_get_controller('TripalEntity');
@@ -1391,10 +1407,12 @@ function tripal_insert_entity($bundle_name, $values){
 }
 
 /**
+ * Are we keeping this? 
+ * 
  * @param $bundle_name
  * @param $values
  *
- * @ingroup tripal_entities_api
+ * 
  */
 function tripal_update_entity($bundle_name, $values) {
 

+ 47 - 30
tripal/api/tripal.fields.api.inc

@@ -4,6 +4,7 @@
  * @file
  * Provides an application programming interface (API) for working with
  * fields attached to TripalEntity content types (bundles).
+ * 
  */
 
 /**
@@ -12,10 +13,41 @@
  * @{
  * Provides an application programming interface (API) for working with
  * fields attached to TripalEntity content types (bundles).
+ * 
+ * Fields:
+ * A field is a reusable "data container" that is attached to a Bundle. 
+ * Programmatically, each field provides one or more primitive data types, with 
+ * validators and widgets for editing and formatters for display. Each field 
+ * independently manages the data to which it assigned.  Just like with Bundles, 
+ * Fields are also described using controlled vocabulary terms.  For example, a 
+ * gene Bundle has a field attached that provides the name of the gene.   
+ * This field only provides the name and nothing more.  Tripal uses the 
+ * schema:name vocabulary term to describe the field.  
+ *
+ * Field Instances:
+ * Fields describe "atomic" units of data that are associated with an entity.  
+ * For example, a "name" is an atomic unit of data about a Gene or Organism 
+ * entity. Fields can be reused for multiple Bundles. For example, gene, mRNA, 
+ * genetic markers and variants all have name data.  Despite that all of these 
+ * Bundles provides a "name", we only need one field to describe that this data
+ * is a "name".  However, we may want to customize a field specific to each 
+ * bundle.  Therefore, an Instance of a field is attached to a bundle, and 
+ * field instances can then be customized differently.  The most important 
+ * customization is the one that defines the Chado table from which the data 
+ * for a field is retrieved.   Despite that field instances are attached to 
+ * bundles, they become visible with Entities.  When an entity is loaded for 
+ * display, Drupal examines all of the fields that are attached to the entity's 
+ * bundle, and then populates the fields instances with data specific to the 
+ * entity being loaded.
  * @}
  *
  */
 
+/**
+ * @section
+ * Hooks.
+ */
+
 /**
  * Executes a TripalFieldQuery using the provided conditions.
  *
@@ -49,9 +81,12 @@ function hook_field_storage_tquery($conditions, $orderBy) {
 }
 
 /**
- *
- * @param unknown $entity_type
- * @param unknown $bundle
+ * Allows a module to return a bundles field info. 
+ * 
+ * @param $entity_type
+ *  The name of the entity, like 'TripalEntity'.
+ * @param $bundle
+ *  The bundle object.
  *
  * @ingroup tripal_fields_api
  */
@@ -60,37 +95,18 @@ function hook_bundle_fields_info($entity_type, $bundle) {
 }
 
 /**
- *
- * @param unknown $entity_type
- * @param unknown $bundle
- *
+ * Allows a module to return the field instances of a bundle.
+ * @param $entity_type
+ *  The name of the entity, most likely 'TripalEntity'.
+ * @param $bundle
+ *  The bundle object.
+ * 
  * @ingroup tripal_fields_api
  */
 function hook_bundle_instances_info($entity_type, $bundle) {
 
 }
-/**
- *
- * @param unknown $info
- * @param unknown $bundle
- * @param unknown $term
- *
- * @ingroup tripal_fields_api
- */
-function hook_bundle_fields_info_alter(&$info, $bundle, $term) {
-
-}
-/**
- *
- * @param unknown $info
- * @param unknown $bundle
- * @param unknown $term
- *
- * @ingroup tripal_fields_api
- */
-function hook_bundle_instances_info_alter(&$info, $bundle, $term) {
 
-}
 /**
  * Retrieves a list of TripalField types.
  *
@@ -156,6 +172,7 @@ function tripal_get_field_types() {
   }
   return $types;
 }
+
 /**
  * Retrieves a list of TripalFieldWidgets.
  *
@@ -221,7 +238,7 @@ function tripal_get_field_widgets() {
  * @param $field
  *   A field array as returned by the field_info_field() function.
  * @param $instance
- *   An field instance array.
+ *   A field instance array.
  * @return
  *   A list of file formatter class names.
  */
@@ -313,7 +330,7 @@ function tripal_get_field_formatters() {
  * Loads the TripalField class file into scope.
  *
  * @param $class
- *   The class to include.  This can be a TripalField, TripalFieldWidget or
+ *   The class to include. This can be a TripalField, TripalFieldWidget or
  *   TripalFieldFormatter class name.
  *
  * @return

+ 123 - 2
tripal/api/tripal.files.api.inc

@@ -36,8 +36,8 @@
  */
 function tripal_create_files_dir($module_name, $path = FALSE) {
 
-  // if the path is not supplied then assume they want to create the base files directory
-  // for the specified module
+  // if the path is not supplied then assume they want to create the base files
+  // directory for the specified module
   if (!$path) {
     // make the data directory for this module
     $data_dir = tripal_get_files_dir() . "/$module_name";
@@ -125,3 +125,124 @@ function tripal_get_files_stream($module_name = FALSE) {
 
   return $stream;
 }
+
+/**
+ * Formats a size (in bytes) in human readable format.
+ *
+ * Function taken from php.net
+ *
+ * @param $bytes
+ *   The size of the file in bytes
+ * @param $precision
+ *   The number of decimal places to use in the final number if needed
+ *
+ * @return string
+ *   A formatted string indicating the size of the file
+ *   
+ *   
+ * @ingroup tripal_files_api
+ */
+function tripal_format_bytes($bytes, $precision = 2) {
+  $units = ['B', 'KB', 'MB', 'GB', 'TB'];
+    
+  $bytes = max($bytes, 0);
+  $pow = floor(($bytes ? log($bytes) : 0) / log(1024));
+  $pow = min($pow, count($units) - 1);
+    
+  // Uncomment one of the following alternatives
+  $bytes /= pow(1000, $pow);
+  // $bytes /= (1 << (10 * $pow));
+    
+  return round($bytes, $precision) . '' . $units[$pow];
+}
+
+/**
+ * Retrieves the list of files uploaded by a user.
+ * 
+ * @param $uid
+ *   The ID of the user whose files should be retrieved.
+ * @param $allowed_types
+ *   A list of valid extensions to restrict the files to.
+ * @param $module
+ *   The name of the module that is managing the file.
+ *      
+ * @return
+ *   A list of file objects.
+ *   
+ * @ingroup tripal_files_api
+ */
+function tripal_get_user_uploads($uid, $allowed_types = array(), $module = 'tripal') {
+  $user = user_load($uid);
+  
+  $query = db_select('file_managed', 'FM');
+  $query->fields('FM', array('fid'));
+  $query->distinct();
+  $query->condition('FM.uid', $user->uid);
+  $query->innerJoin('file_usage', 'FU', "FU.fid = FM.fid");
+  $query->condition('FU.module', $module);
+  $query->orderBy('FM.filename');
+  $files = $query->execute();
+  
+  $files_list = [];
+  while ($fid = $files->fetchField()) {
+    $file = file_load($fid);
+    foreach ($allowed_types as $type) {
+      if (preg_match('/\.' . $type . '$/', $file->filename)) {
+        $files_list[$fid] = $file;
+      }
+    }
+  }
+  
+  return $files_list;
+}
+
+/**
+ * Retrieves the URI for the dedicated directory for a user's files.
+ * 
+ * This directory is used by the file uploader and by data collections.
+ * 
+ * @param $user
+ *   A Drupal user object.
+ *   
+ * @return 
+ *   The URI of the directory.
+ *   
+ * @ingroup tripal_files_api
+ */
+function tripal_get_user_files_dir($user) {
+  
+  $user_dir = 'public://tripal/users/' . $user->uid;
+    
+  return $user_dir;
+}
+
+/**
+ * Checks if the user's dedicated directory is accessible and writeable. 
+ * 
+ * @param $user
+ *   A Drupal user object.
+ *   
+ * @return
+ *   TRUE if the user's directory is writeable. FALSE otherwise.
+ *   
+ * @ingroup tripal_files_api
+ */
+function tripal_is_user_files_dir_writeable($user) {
+  $user_dir = tripal_get_user_files_dir($user);
+   
+  // First, make sure the directory exists.
+  if (!file_prepare_directory($user_dir, FILE_CREATE_DIRECTORY)) {
+    return FALSE;
+  }
+  
+  // It has been reported that file_prepare_directory is not properly
+  // detecting if the directory is writeable, so we'll do another
+  // round of checks to be sure.
+  if (!is_dir($user_dir)) {
+    return FALSE;
+  }
+  if (!is_writeable($user_dir)) {
+    return FALSE;
+  }
+  return TRUE;
+}

+ 5 - 6
tripal/api/tripal.importer.api.inc

@@ -4,6 +4,7 @@
  * @file
  * Provides an application programming interface (API) for working with
  * data file importers using the TripalImporter class.
+ * 
  */
 
 /**
@@ -11,7 +12,7 @@
  * @ingroup tripal_api
  * @{
  * Provides an application programming interface (API) for working with
- * data file importers using the TripalImporter class.
+ * data file importers using the TripalImporter class into a chado database.
  * @}
  *
  */
@@ -22,10 +23,8 @@
  * This is a Tripal hook that allows the module to set the proper
  * parameters for a file uploaded via the Tripal HTML5 uploader.
  *
- * @param $filename
- *   The name of the file uploaded
- * @param $filepath
- *   The path to the file
+ * @param $file
+ *   The Drupal file object of the newly uploaded file.
  * @param $type
  *   The category or type of file.
  *
@@ -34,7 +33,7 @@
  *
  * @ingroup tripal_importer_api
  */
-function hook_handle_uploaded_file($filename, $filepath, $type) {
+function hook_handle_uploaded_file($file, $type) {
 
 }
 

+ 14 - 11
tripal/api/tripal.jobs.api.inc

@@ -1,8 +1,8 @@
 <?php
 /**
  * @file
- * Tripal offers a job management subsystem for managing tasks that may require an extended period of time for
- * completion.
+ * Tripal offers a job management subsystem for managing tasks that may require 
+ * an extended period of time for completion.
  */
 
 /**
@@ -39,8 +39,8 @@
  * @param $uid
  *    The uid of the user adding the job
  * @param $priority
- *    The priority at which to run the job where the highest priority is 10 and the lowest priority
- *    is 1. The default priority is 10.
+ *    The priority at which to run the job where the highest priority is 10 and 
+ *    the lowest priority is 1. The default priority is 10.
  * @param $includes
  *    An array of paths to files that should be included in order to execute
  *    the job. Use the module_load_include function to get a path for a given
@@ -60,7 +60,8 @@
  *         $user->uid, $analysis_id, $match_type);
  *
  *   $includes = array()
- *   $includes[] = module_load_include('inc', 'tripal_chado', 'includes/loaders/tripal_chado.fasta_loader');
+ *   $includes[] = module_load_include('inc', 'tripal_chado', 
+ *                                'includes/loaders/tripal_chado.fasta_loader');
  *
  *   tripal_add_job("Import FASTA file: $dfile", 'tripal_feature',
  *     'tripal_feature_load_fasta', $args, $user->uid, 10, $includes);
@@ -231,12 +232,13 @@ function tripal_max_jobs_exceeded($max_jobs) {
 }
 
 /**
- * Set a job to be re-ran (ie: add it back into the job queue)
+ * Set a job to be re-run (ie: add it back into the job queue).
  *
  * @param $job_id
  *   The job_id of the job to be re-ran
  * @param $goto_jobs_page
- *   If set to TRUE then after the re run job is added Drupal will redirect to the jobs page
+ *   If set to TRUE then after the re run job is added Drupal will redirect to 
+ *   the jobs page
  *
  * @ingroup tripal_jobs_api
  */
@@ -287,7 +289,7 @@ function tripal_rerun_job($job_id, $goto_jobs_page = TRUE) {
 }
 
 /**
- * Cancel a Tripal Job currently waiting in the job queue
+ * Cancel a Tripal Job currently waiting in the job queue.
  *
  * @param $job_id
  *   The job_id of the job to be cancelled
@@ -323,7 +325,7 @@ function tripal_cancel_job($job_id, $redirect = TRUE) {
 }
 
 /**
- * A function used to manually launch all queued tripal jobs
+ * A function used to manually launch all queued tripal jobs.
  *
  * @param $do_parallel
  *   A boolean indicating whether jobs should be attempted to run in parallel
@@ -335,7 +337,8 @@ function tripal_cancel_job($job_id, $redirect = TRUE) {
  *   job needs to be launched and this argument will allow it.  Only jobs
  *   which have not been run previously will run.
  * @param $max_jobs
- *   The maximum number of jobs that should be run concurrently. If -1 then unlimited.
+ *   The maximum number of jobs that should be run concurrently. If -1 then 
+ *   unlimited.
  * @param $single
  *   Ensures only a single job is run rather then the entire queue.
  *
@@ -434,7 +437,7 @@ function tripal_launch_job($do_parallel = 0, $job_id = NULL, $max_jobs = -1, $si
 }
 
 /**
- * An internal function for setting the progress for a current job
+ * An internal function for setting the progress for a current job.
  *
  * @param $job_id
  *   The job_id to set the progress for

+ 16 - 12
tripal/api/tripal.notice.api.inc

@@ -2,7 +2,7 @@
 /**
  * @file
  * Provides an application programming interface (API) for improved user
- * notivications.  These API functions can be used to set messages for
+ * notifications.  These API functions can be used to set messages for
  * end-users, administrators, or simple logging.
  */
 
@@ -63,6 +63,10 @@ define('TRIPAL_DEBUG',7);
  */
 function tripal_report_error($type, $severity, $message, $variables = array(), $options = array()) {
 
+  $suppress = getenv('TRIPAL_SUPPRESS_ERRORS');
+
+  if(strtolower($suppress) === 'true') return;
+
   // Get human-readable severity string
   $severity_string = '';
   switch ($severity) {
@@ -140,7 +144,7 @@ function tripal_report_error($type, $severity, $message, $variables = array(), $
  * tripal administrators.
  *
  * @param $message
- *   The message to be displayed to the tripal administrators
+ *   The message to be displayed to the tripal administrators.
  * @param $importance
  *   The level of importance for this message. In the future this will be used
  *   to allow administrators to filter some of these messages. It can be one of
@@ -167,10 +171,10 @@ function tripal_set_message($message, $importance = TRIPAL_INFO, $options = arra
     return '';
   }
 
-  // set defaults
+  // Set defaults.
   $options['return_html'] = (isset($options['return_html'])) ? $options['return_html'] : FALSE;
 
-  // Get human-readable severity string
+  // Get human-readable severity string.
   $importance_string = '';
   switch ($importance) {
     case TRIPAL_CRITICAL:
@@ -193,7 +197,7 @@ function tripal_set_message($message, $importance = TRIPAL_INFO, $options = arra
       break;
   }
 
-  // Mark-up the Message
+  // Mark-up the Message.
   $full_message =
      '<div class="tripal-site-admin-message">' .
        '<span class="tripal-severity-string ' . strtolower($importance_string) . '">' . $importance_string . ': </span>' .
@@ -201,7 +205,8 @@ function tripal_set_message($message, $importance = TRIPAL_INFO, $options = arra
    '</div>';
 
   // Handle whether to return the HTML & let the caller deal with it
-  // or to use drupal_set_message to put it near the top of the page  & let the theme deal with it
+  // or to use drupal_set_message to put it near the top of the page  & let the 
+  // theme deal with it.
   if ($options['return_html']) {
     return '<div class="messages tripal-site-admin-only">' . $full_message . '</div>';
   }
@@ -211,22 +216,22 @@ function tripal_set_message($message, $importance = TRIPAL_INFO, $options = arra
 }
 
 /**
- * File-based Logging for Tripal
+ * File-based logging for Tripal.
  *
  * @param $message
- *   The message to be logged. Need not contain date/time information
+ *   The message to be logged. Need not contain date/time information.
  * @param $log_type
  *   The type of log. Should be one of 'error' or 'job' although other types
  *   are supported.
  * @param $options
  *   An array of options where the following keys are supported:
  *     - first_progress_bar: this sohuld be used for the first log call for a
- *       progress bar
+ *       progress bar.
  *     - is_progress_bar: this option should be used for all but the first print
  *       of a progress bar to allow it all to be printed on the same line
- *       without intervening date prefixes
+ *       without intervening date prefixes.
  * @return
- *   The number of bytes that were written to the file, or FALSE on failure
+ *   The number of bytes that were written to the file, or FALSE on failure.
  *
  * @ingroup tripal_notify_api
  */
@@ -245,4 +250,3 @@ function tripal_log($message, $type = 'error', $options = array()) {
   return error_log($message);
 
 }
-

+ 150 - 0
tripal/api/tripal.quotas.api.inc

@@ -0,0 +1,150 @@
+<?php
+
+/**
+ * Retrieves the user's quote and default days to expire.
+ *
+ * @param $uid
+ *   The User ID.
+ *
+ * @return
+ *   An associative array containing the quota and default days to
+ *   expire.
+ */
+function tripal_get_user_quota($uid) {
+  $quota = db_select('tripal_custom_quota', 'tgcq')->fields('tgcq', [
+    'custom_quota',
+    'custom_expiration'
+  ])
+    ->condition('uid', $uid)
+    ->execute()
+    ->fetchObject();
+  if (! $quota) {
+    $quota = new stdClass();
+    $quota->custom_quota = variable_get('tripal_default_file_quota', pow(20, 6));
+    $quota->custom_expiration = variable_get('tripal_default_file_expiration', '60');
+  }
+  return $quota;
+}
+
+/**
+ * Sets a user's file space quota and default file expiration.
+ *
+ * @param $uid The
+ *          User ID for whom the quota will be set.
+ * @param $quota The
+ *          quota
+ * @param
+ *          $expriation
+ *          
+ * @return The inserted record.
+ */
+function tripal_set_user_quota($uid, $quota, $expriation) {
+  $values = [
+    'uid' => $uid,
+    'custom_quota' => $quota,
+    'custom_expiration' => $expriation
+  ];
+  return db_insert('tripal_custom_quota')->fields($values)->execute();
+}
+
+/**
+ * Removes a user's file space and default file expiration.
+ *
+ * @param $uid The
+ *          User ID for whom the quota will be removed.
+ *          
+ * @return
+ */
+function tripal_remove_user_quota($uid) {
+  db_delete('tripal_custom_quota')->condition('uid', $uid)->execute();
+}
+
+/**
+ * Retrieves the current size of all files uploaded by the user.
+ *
+ * @param $uid The
+ *          User ID.
+ *          
+ * @return The total number of bytes currently used.
+ */
+function tripal_get_user_usage($uid) {
+  // Get the user's current file usage
+  $sql = "
+    SELECT DISTINCT FU.fid
+    FROM {file_usage} FU
+      INNER JOIN {file_managed} FM ON FM.fid = FU.fid and FU.module = 'tripal'
+    WHERE FM.uid = :uid
+  ";
+  $fids = db_query($sql, [
+    ':uid' => $uid
+  ]);
+  $total_size = 0;
+  while ($fid = $fids->fetchObject()) {
+    $sql = "SELECT filesize FROM {file_managed} WHERE fid = :fid";
+    $total_size += db_query($sql, [
+      ':fid' => $fid->fid
+    ])->fetchObject()->filesize;
+  }
+  return $total_size;
+}
+
+/**
+ * Checks if a file needs to be expired.
+ */
+function tripal_expire_files(TripalJob $job = NULL) {
+  $results = db_select('tripal_expiration_files', 'tgfe')
+    ->fields('tgfe')
+    ->execute();
+  while ($result = $results->fetchObject()) {
+    if (time() > $result->expiration_date) {
+      
+      $file = file_load($result->fid);
+      if ($file) {
+        if ($job) {
+          $job->logMessage('File "' . $file->filename . '" has expired. Removing...');
+        }
+        // First remove the file from the file system.
+        file_delete($file, TRUE);
+        
+        // Remove the file from our file expiration table.
+        $query = db_delete('tripal_expiration_files');
+        $query->condition('fid', $result->fid);
+        $query->execute();
+      }
+    }
+  }
+}
+
+/**
+ * Resets the expiration data of a file managed by Tripal.
+ * 
+ * @param $fid
+ *   The file ID of the file to reset.
+ *   
+ * @return
+ *   TRUE on success, FALSE on failure.
+ */
+function tripal_reset_file_expiration($fid) {
+  
+  $file = file_load($fid);
+  try {
+    $quota = tripal_get_user_quota($file->uid);
+    $custom_expiration = $quota->custom_expiration;
+    $expiration_date = time() + $custom_expiration * 24 * 60 * 60;
+    
+    db_delete('tripal_expiration_files')
+       ->condition('fid', $fid)
+       ->execute();
+    db_insert('tripal_expiration_files')
+      ->fields([
+        'fid' => $file->fid,
+        'expiration_date' => $expiration_date,
+      ])
+      ->execute();  
+  }
+  catch (Exception $e) {
+    tripal_report_error('trp_quota', TRIPAL_ERROR, $e->getMessage());
+    return FALSE;
+  }
+  return TRUE;
+}

+ 51 - 13
tripal/api/tripal.terms.api.inc

@@ -12,7 +12,7 @@
  * Tripal provides an application programming interface (API) for working with
  * controlled vocaublary terms.  Tripal v3 is highly dependent on controlled
  * vocabularies for identifying all content types and fields attached to those
- * content types.  However, Tripal v3 is also database agnostic. Therefore, it
+ * content types.  However, Tripal v3 is also database agnostic. Therefore,
  * controlled vocabularies can be stored in any database back-end.  By default
  * the tripal_chado module is used for storing controlled vocabularies. However,
  * if someone wanted to store controlled vocabularies in a database other than
@@ -85,16 +85,19 @@ function hook_vocab_select_term_form(&$form, &$form_state) {
 
   return $form;
 }
+
 /**
  * Validates the hook_vocab_select_term_form().
  *
- * @param $name
+ * @param $form
+ * @param $form_state
  *
  * @ingroup tripal_terms_api
  */
 function hook_vocab_select_term_form_validate($form, &$form_state) {
 
 }
+
 /**
  * Provides a form for importing vocabularies and their terms.
  *
@@ -111,9 +114,27 @@ function hook_vocab_select_term_form_validate($form, &$form_state) {
 function hook_vocab_import_form($form, &$form_state) {
   return $form;
 }
+
+/**
+ * Validates the hook_vocab_import_form().
+ *
+ * @param $form
+ * @param $form_state
+ *
+ * @ingroup tripal_terms_api
+ */
 function hook_vocab_import_form_validate($form, &$form_state) {
 
 }
+
+/**
+ * Submits the hook_vocab_import_form().
+ *
+ * @param $form
+ * @param $form_state
+ *
+ * @ingroup tripal_terms_api
+ */
 function hook_vocab_import_form_submit($form, &$form_state) {
 
 }
@@ -132,7 +153,7 @@ function hook_vocab_import_form_submit($form, &$form_state) {
  *
  * @return
  *   An array with at least the following keys:
- *     -vocabulary : An associative array with the following keys
+ *     -vocabulary : An associative array with the following keys:
  *       -name:  The short name for the vocabulary (e.g. SO, PATO, etc).
  *       -description: The description of this vocabulary.
  *       -url: The URL for the vocabulary.
@@ -154,6 +175,7 @@ function hook_vocab_get_term($vocabulary, $accession) {
   // See the tripal_chado_vocab_get_term() function for an example.
 
 }
+
 /**
  * Retrieves a paged list of terms from a vocabulary.
  *
@@ -164,10 +186,13 @@ function hook_vocab_get_term($vocabulary, $accession) {
  * @param $element
  *   The pager element. This is equivalent to the element from the
  *   pager_default_initialize() function of Drupal.
+ * 
+ * @ingroup tripal_terms_api
  */
 function hook_vocab_get_terms($vocabulary, $limit = 25, $element = 0) {
-
+  // See the tripal_chado_vocab_get_terms() function for an example.
 }
+
 /**
  * Hook used by the default term storage backend to provide children for a term.
  *
@@ -188,8 +213,9 @@ function hook_vocab_get_terms($vocabulary, $limit = 25, $element = 0) {
  * @ingroup tripal_terms_api
  */
 function hook_vocab_get_term_children($vocabulary, $accession) {
-
+  // See the tripal_chado_vocab_get_term_children() function for an example.
 }
+
 /**
  * Hook used by the default term storage backend to provide root terms.
  *
@@ -208,8 +234,9 @@ function hook_vocab_get_term_children($vocabulary, $accession) {
  * @ingroup tripal_terms_api
  */
 function hook_vocab_get_root_terms($vocabulary) {
-
+  // See the tripal_chado_vocab_get_root_terms() function for an example.
 }
+
 /**
  * Hook used by the default term storage backend to provide details for a vocab.
  *
@@ -231,6 +258,7 @@ function hook_vocab_get_root_terms($vocabulary) {
  *       prefix does not support appending then the exact location for the
  *       position of the short_name and the term accession will be
  *       specified with the {db} and {accession} tags respectively.
+ * 
  * @ingroup tripal_terms_api
  */
 function hook_vocab_get_vocabulary($vocabulary) {
@@ -244,16 +272,19 @@ function hook_vocab_get_vocabulary($vocabulary) {
  *   An array of vocabularies where each entry in the array is compatible
  *   with the array returned by the tripal_get_vocabulary_details()
  *   function.
+ * 
+ * @ingroup tripal_terms_api
  */
 function hook_vocab_get_vocabularies() {
   // See the tripal_chado_vocab_get_vocabularies() function for an example.
 }
+
 /**
  * Hook used by the default term storage backend to add new terms.
  *
  * @param $details
  *   An array with at least the following keys:
- *     -vocabulary : An associative array with the following keys
+ *     -vocabulary : An associative array with the following keys:
  *       -name:  The short name for the vocabulary (e.g. SO, PATO, etc).
  *       -description: The description of this vocabulary.
  *       -url: The URL for the vocabulary.
@@ -268,15 +299,14 @@ function hook_vocab_get_vocabularies() {
  *     -definition : The term's description.
  * @return
  *   TRUE if the term was added, FALSE otherwise.  If the term already exists
- *   it will be updated and the return value will be TRUE,
+ *   it will be updated and the return value will be TRUE.
+ * 
  * @ingroup tripal_terms_api
  */
 function hook_vocab_add_term($details) {
   // See the tripal_chado_vocab_set_term() function for an example.
 }
 
-
-
 /**
  * Adds a term to the vocabulary storage backend.
  *
@@ -295,7 +325,8 @@ function hook_vocab_add_term($details) {
  *     -definition : The term's description.
  * @return
  *   TRUE if the term was added, FALSE otherwise.  If the term already exists
- *   it will be updated and the return value will be TRUE,
+ *   it will be updated and the return value will be TRUE.
+ * 
  * @ingroup tripal_terms_api
  */
 function tripal_add_term($details) {
@@ -362,6 +393,7 @@ function tripal_get_term_details($vocabulary, $accession) {
     }
   }
 }
+
 /**
  * Retrieves the immediate children of the given term.
  *
@@ -394,6 +426,7 @@ function tripal_get_vocabulary_root_terms($vocabulary) {
     }
   }
 }
+
 /**
  * Retrieves the immediate children of the given term.
  *
@@ -423,6 +456,7 @@ function tripal_get_term_children($vocabulary, $accession) {
     }
   }
 }
+
 /**
  * Retrieves full information about a vocabulary.
  *
@@ -477,6 +511,8 @@ function tripal_get_vocabulary_details($vocabulary) {
  * @param $element
  *   The pager element. This is equivalent to the element from the
  *   pager_default_initialize() function of Drupal.
+ * 
+ * @ingroup tripal_terms_api
  */
 function tripal_get_vocabulary_terms($vocabulary, $limit = 25, $element = 0) {
   $stores = module_invoke_all('vocab_storage_info');
@@ -497,6 +533,8 @@ function tripal_get_vocabulary_terms($vocabulary, $limit = 25, $element = 0) {
  *   An array of vocabularies where each entry in the array is compatible
  *   with the array returned by the tripal_get_vocabulary_details()
  *   function.
+ * 
+ * @ingroup tripal_terms_api
  */
 function tripal_get_vocabularies() {
   $stores = module_invoke_all('vocab_storage_info');
@@ -520,7 +558,7 @@ function tripal_get_vocabularies() {
  * multiple vocabularies and the user would need to select the proper term.
  *
  * This function will add the form elements necessary to provide a lookup form.
- * The form elements should work with a flat fortm (no #tree set for the form)
+ * The form elements should work with a flat form (no #tree set for the form)
  * or with a form in a TripalField.
  *
  * Use the tripal_get_term_lookup_form_result() function to retreive the
@@ -716,4 +754,4 @@ function tripal_get_term_lookup_form_ajax_callback($form, $form_state) {
   else {
     return $form['term_match'];
   }
-}
+}

+ 3 - 2
tripal/api/tripal.upload.api.inc

@@ -90,7 +90,8 @@
  * file by querying for the file category for the current project.
  *
  * @code
- *   $seq_files = TripalFeature::getFilesByTypes($user->uid, array('sequence_file'), $project_id);
+ *   $seq_files = TripalFeature::getFilesByTypes($user->uid, 
+ *                   array('sequence_file'), $project_id);
  * @endcode
  *
  * 4) If the 'target_id' was used in array for step #2 above, then the
@@ -140,4 +141,4 @@ function hook_file_upload_check($action, $details, &$message){
       break;
   }
   return TRUE;
-}
+}

+ 4 - 10
tripal/includes/TripalFieldDownloaders/TripalFieldDownloader.inc

@@ -160,16 +160,10 @@ abstract class TripalFieldDownloader {
       $collection_bundle->fields = unserialize($collection_bundle->fields);
       $this->collection_bundles[] = $collection_bundle;
     }
-
-    if (!file_prepare_directory($user_dir, FILE_CREATE_DIRECTORY)) {
-      $message = 'Could not access the directory on the server for storing this file.';
-      watchdog('tripal', $message, array(), WATCHDOG_ERROR);
-      drupal_json_output(array(
-        'status'  => 'failed',
-        'message' => $message,
-        'file_id' => '',
-      ));
-      return;
+ 
+    $user_dir = tripal_get_user_files_dir($user);
+    if (!tripal_is_user_files_dir_writeable($user)) {
+      throw new Exception(t("The user's data directory is not writeable: !user_dir.", array('!user_dir' => $user_dir)));
     }
 
     // Map the fields to their term accessions.

+ 568 - 0
tripal/includes/tripal.admin_files.inc

@@ -0,0 +1,568 @@
+<?php
+
+/**
+ * Form for adding a file quota for a user.
+ **/
+function tripal_admin_add_custom_form($form, &$form_state) {
+
+  $username = '';
+  $default_quota = variable_get('tripal_default_file_quota', pow(20,6));
+  $default_expiration = variable_get('tripal_default_file_expiration', '60');
+
+  if (array_key_exists('values', $form_state)) {
+    $username = $form_state['values']['username'];
+    $default_quota = $form_state['values']['default_quota'];
+    $default_expiration = $form_state['values']['default_expiration_date'];
+  }
+
+
+  // Textfield (ajax call based off of existing users) for users on the site
+  $form['username'] = array (
+    '#type' => 'textfield',
+    '#title' => 'User',
+    '#autocomplete_path' => 'admin/tripal/files/quota/user/autocomplete',
+    '#default_value' => $username,
+  );
+
+  // Custom quota textfield (prepopulated with defualt value)
+  $form['quota'] = array (
+    '#type' => 'textfield',
+    '#title' => 'Custom User Quota',
+    '#description' => 'Set the number of megabytes that a user can consume. The number must be followed by the suffix "MB" (megabytes) or "GB" (gigabytes) with no space between the number and the suffix (e.g.: 200MB).',
+    '#default_value' => tripal_format_bytes($default_quota),
+  );
+
+  // Custom exp date textfield (prepopulated with defualt value)
+  $form['expiration'] = array (
+    '#type' => 'textfield',
+    '#title' => 'Days to Expire',
+    '#description' => 'The number of days that a user uploaded file can remain on the server before it is automatically removed.',
+    '#default_value' => $default_expiration,
+  );
+
+  // Submit button
+  $form['button'] = array (
+    '#type' => 'submit',
+    '#value' => t('Submit'),
+  );
+  $form['cancel'] = array(
+    '#type' => 'markup',
+    '#markup' => l('Cancel', 'admin/tripal/files/quota'),
+  );
+
+  return $form;
+
+}
+
+/**
+ * Validates the tripal_admin_add_custom_form form.
+ **/
+function tripal_admin_add_custom_form_validate($form, &$form_state) {
+
+  $username = $form_state['values']['username'];
+  $quota = $form_state['values']['quota'];
+  $expiration = $form_state['values']['expiration'];
+
+  // Make sure the username is a valid user.
+  $sql = "SELECT uid FROM {users} WHERE name = :name";
+  $uid = db_query($sql,array(':name' => $username))->fetchField();
+  if (!$uid) {
+    form_set_error('username', 'Cannot find this username');
+  }
+
+  // Does a quota already exist for this user? If so, then don't add it again
+  $check = db_select('tripal_custom_quota', 'tgcq')
+    ->fields('tgcq', array('uid'))
+    ->condition('uid', $uid)
+    ->execute()
+    ->fetchField();
+  if ($check) {
+    form_set_error('username', 'The user "' . $username . '" already has a custom quota set.');
+  }
+
+  // Validate the quota string.
+  if (!preg_match("/^\d+(MB|GB|TB)$/", $quota)) {
+    form_set_error('quota', t('Please provide a quota size in the format indicated.'));
+  }
+
+  // Validate the expiration time.
+  if (!preg_match("/^\d+$/", $expiration)) {
+    form_set_error('expiration', t('Please providate a positive non-decimal numeric value for the days to expire'));
+  }
+}
+
+
+/**
+ * Submiter for the tripal_admin_add_custom_form form.
+ **/
+function tripal_admin_add_custom_form_submit($form, &$form_state) {
+
+  $username = $form_state['values']['username'];
+  $quota = $form_state['values']['quota'];
+  $expiration = $form_state['values']['expiration'];
+
+  // if the 2nd element of the qutoa string occupied by a valid suffix we need to check to see
+  // what we have to multiply the value by (1024 for GB 1024^2 for TB because
+  // we assume that the initial number is already in MB)
+  $matches = array();
+  $multiplier = 'MB';
+  $size = $quota;
+  if (preg_match("/^(\d+)(MB|GB|TB)$/", $quota, $matches)) {
+    $multiplier = $matches[2];
+    $size = $matches[1];
+  }
+
+  switch ($multiplier) {
+    case 'GB':
+      $size = (int) $quota * pow(10,9);
+      break;
+    case 'TB':
+      $size = (int) $quota * pow(10,12);
+      break;
+    default:
+      $size = (int) $quota * pow(10,6);
+      break;
+  }
+
+  // Get the UID of the given user.
+  $sql = "SELECT uid FROM {users} WHERE name = :name";
+  $uid = db_query($sql,array(':name' => $username))->fetchField();
+
+  // Stripaluota.
+  tripal_set_user_quota($uid, $size, $expiration);
+
+  // TODO: check to make sure that the quota was actually set, can we assume
+  // it will always work?
+
+  drupal_set_message(t('Custom quota set for the user: @username', array('@username' => $username)));
+  drupal_goto('admin/tripal/files/quota');
+}
+
+/**
+ * Edit an existing users' quota and/or expiration date
+ **/
+function tripal_admin_edit_quota_form($form, &$form_state, $uid) {
+
+  $quota = tripal_get_user_quota($uid);
+  $default_quota = $quota->custom_quota;
+  $default_expiration = $quota->custom_expiration;
+
+  if (array_key_exists('values', $form_state)) {
+    $default_quota = $form_state['values']['default_quota'];
+    $default_expiration = $form_state['values']['default_expiration_date'];
+  }
+
+  $user = user_load($uid);
+
+  $form['uid'] = array(
+    '#type' => 'value',
+    '#value' => $uid
+  );
+
+  // Textfield (ajax call based off of existing users) for users on the site
+  $form['username'] = array (
+    '#type' => 'item',
+    '#title' => 'User',
+    '#markup' => $user->name,
+  );
+
+  // Custom quota textfield (prepopulated with defualt value)
+  $form['quota'] = array (
+    '#type' => 'textfield',
+    '#title' => 'Custom User Quota',
+    '#description' => 'Set the number of megabytes that a user can consume. The number must be followed by the suffix "MB" (megabytes) or "GB" (gigabytes) with no space between the number and the suffix (e.g.: 200MB).',
+    '#default_value' => tripal_format_bytes($default_quota),
+  );
+
+  // Custom exp date textfield (prepopulated with defualt value)
+  $form['expiration'] = array (
+    '#type' => 'textfield',
+    '#title' => 'Days to Expire',
+    '#description' => 'The number of days that a user uploaded file can remain on the server before it is automatically removed.',
+    '#default_value' => $default_expiration,
+  );
+
+  // Submit button
+  $form['button'] = array (
+    '#type' => 'submit',
+    '#value' => t('Submit'),
+  );
+  $form['cancel'] = array(
+    '#type' => 'markup',
+    '#markup' => l('Cancel', 'admin/tripal/files/quota'),
+  );
+
+  return $form;
+}
+
+/**
+ * Same validate as the add user with the exception of no duplicate entry
+ **/
+function tripal_admin_edit_quota_form_validate($form, &$form_state){
+
+  $uid = $form_state['values']['uid'];
+  $quota = $form_state['values']['quota'];
+  $expiration = $form_state['values']['expiration'];
+
+  // Validate the quota string.
+  if (!preg_match("/^\d+(MB|GB|TB)$/", $quota)) {
+    form_set_error('quota', t('Please provide a quota size in the format indicated.'));
+  }
+
+  // Validate the expiration time.
+  if (!preg_match("/^\d+$/", $expiration)) {
+    form_set_error('expiration', t('Please providate a positive non-decimal numeric value for the days to expire'));
+  }
+}
+
+/**
+ * Same submit as the quota overwrite function
+ **/
+function tripal_admin_edit_quota_form_submit($form, &$form_state) {
+  $uid = $form_state['values']['uid'];
+  $quota = $form_state['values']['quota'];
+  $expiration = $form_state['values']['expiration'];
+
+  // if the 2nd element of the qutoa string occupied by a valid suffix we need to check to see
+  // what we have to multiply the value by (1024 for GB 1024^2 for TB because
+  // we assume that the initial number is already in MB)
+  $matches = array();
+  $multiplier = 'MB';
+  $size = $quota;
+  if (preg_match("/^\d+(\.\d+)*(MB|GB|TB)$/", $quota, $matches)) {
+    $multiplier = $matches[2];
+    $size = $matches[1];
+  }
+
+  switch ($multiplier) {
+    case 'GB':
+      $size = (int) $quota * pow(10,9);
+      break;
+    case 'TB':
+      $size = (int) $quota * pow(10,12);
+      break;
+    default:
+      $size = (int) $quota * pow(10,6);
+      break;
+  }
+
+  // Set the user quota.
+  tripal_remove_user_quota($uid);
+  tripal_set_user_quota($uid, $size, $expiration);
+
+  $user = user_load($uid);
+
+  drupal_set_message(t('Custom quota set for the user: @username', array('@username' => $user->name)));
+  drupal_goto('admin/tripal/files/quota');
+}
+
+/**
+ * Implements the form for setting the default file settings.
+ */
+function tripal_admin_manage_files_form($form, &$form_state) {
+  
+  if (array_key_exists('values', $form_state)) {
+    $upload_max = $form_state['values']['upload_max'];
+  }
+  else {
+    $upload_max = tripal_format_bytes(variable_get('tripal_upload_max_size', 10000000000));
+  }
+  
+  $form['php_defaults'] = [
+    '#type' => 'item',
+    '#title' => 'PHP Maximum Upload Size',
+    '#description' => t('Your php.ini file is currently configured with this size as the maximum size allowed for a single file during upload. However, Tripal uses an HTML5 uploader that supports much larger file sizes.  It works by breaking the file into chunks and uploading each chunk separately. Therefore this becomes the maximum allowed size of a chunk.'),
+    '#markup' => ini_get("upload_max_filesize"),
+  ];
+  
+  $form['upload_max'] = [
+    '#type' => 'textfield',
+    '#title' => 'Maximum file size',
+    '#description' => t('Set the maximum size that a file can have for upload. The number must be followed by the suffix "MB" (megabytes) or "GB" (gigabytes) with no space between the number and the suffix (e.g.: 200MB).  No user will be allowed to upload a file larger than this when Tripal\'s file upload tool is used.'),
+    '#default_value' => $upload_max,
+  ];
+  
+  $form['update_defaults'] = [
+    '#type' => 'submit',
+    '#value' => t('Save'),
+  ];
+  return $form;
+}
+
+/**
+ * Validate the form's values: proper numbers and/or MB, GB, TB for quota field.
+ **/
+function tripal_admin_manage_files_form_validate($form, &$form_state) {
+  $upload_max = $form_state['values']['upload_max'];
+  
+  // Validate the quota string.
+  if (!preg_match("/^\d+(\.\d+)*(MB|GB|TB)$/", $upload_max)) {
+    form_set_error('upload_max', t('Please provide a maximum size in the format indicated.'));
+  }
+}
+/**
+ * Implements the submit function of the tripal_admin_manage_files_form.
+ **/
+function tripal_admin_manage_files_form_submit($form, &$form_state) {
+  $upload_max = $form_state['values']['upload_max'];
+    
+  // if the 2nd element of the qutoa string occupied by a valid suffix we need to check to see
+  // what we have to multiply the value by (1024 for GB 1024^2 for TB because
+  // we assume that the initial number is already in MB)
+  $matches = array();
+  $multiplier = 'MB';
+  $size = $upload_max;
+  if (preg_match("/^(\d+(?:\.\d+)*)(MB|GB|TB)$/", $upload_max, $matches)) {
+    $multiplier = $matches[2];
+    $size = $matches[1];
+  }
+  
+  switch ($multiplier) {
+    case 'GB':
+      $size = (int) ($size * pow(10,9));
+      break;
+    case 'TB':
+      $size = (int) ($size * pow(10,12));
+      break;
+    default:
+      $size = (int) ($size * pow(10,6));
+      break;
+  }
+  variable_set('tripal_upload_max_size', $size);
+    
+  drupal_set_message('Default settings have been set.');
+}
+
+/**
+ * Provides the means of setting quotas and seeing server consumption.
+ *
+ * @return A table of the current users with custom quotas, fieldsets for
+ *         adding new users to the custom quotas, and fieldsets for setting
+ *         site wide quota and expiration date.
+ */
+function tripal_admin_manage_quota_form($form, &$form_state) {
+  // Provide overall server consumption (and space remaining)
+  $total_size = 0;
+  
+  $default_quota = variable_get('tripal_default_file_quota', pow(20,6));
+  $default_expiration = variable_get('tripal_default_file_expiration', '60');
+
+  if (array_key_exists('values', $form_state)) {
+    $default_quota = $form_state['values']['default_quota'];
+    $default_expiration = $form_state['values']['default_expiration_date'];
+  }
+
+  // Query file usage table for the fids that the module uses
+  // Iterate through all of the files managed by the tripal module
+  // and calculate the total.
+  $sql = "SELECT DISTINCT fid FROM {file_usage} WHERE module = 'tripal'";
+  $fids = db_query($sql);
+  while($fid = $fids->fetchObject()) {
+    $sql = "SELECT filesize FROM {file_managed} WHERE fid = :fid";
+    $total_size += db_query($sql, array (':fid' => $fid->fid))->fetchObject()->filesize;
+  }
+  $form['total_size'] = array (
+    '#type' => 'item',
+    '#title' => t('Total Current Usage'),
+    '#description' => t('The total amount of space consumed by user file uploads.'),
+    '#markup' => tripal_format_bytes($total_size),
+  );
+
+  // TODO: add a D3 chart showing the amount of storage used by each user.
+
+  $form['default_quota'] = array (
+    '#type' => 'textfield',
+    '#title' => 'Default System-Wide User Quota',
+    '#description' => t('Set the number of megabytes that a user can consume. The number must be followed by the suffix "MB" (megabytes) or "GB" (gigabytes) with no space between the number and the suffix (e.g.: 200MB).'),
+    '#default_value' => tripal_format_bytes($default_quota),
+  );
+
+  $form['default_expiration_date'] = array (
+    '#type' => 'textfield',
+    '#title' => 'Default System-Wide Expiration Date',
+    '#description' => t('The number of days that a user uploaded file can remain on the server before it is automatically removed'),
+    '#default_value' => $default_expiration,
+  );
+
+  // Populate the table from the custom quota db table (users, quota, exp date).
+  $header = array(
+    'uid' => t('UID'),
+    'user' => t('Users'),
+    'custom_quota' => t('Custom Quota'),
+    'exp_date' => t('Expiration Date'),
+    'actions' => t('Actions'),
+  );
+
+  // API call to the gather the users that have a custom quota
+  $rows = array();
+  $query = "SELECT * FROM {tripal_custom_quota}";
+  $data = db_query($query);
+  while($entry = $data->fetchObject()) {
+    $user = user_load($entry->uid);
+    $rows[] = array(
+      'uid' => $user->uid,
+      'user' => $user->name,
+      'custom_quota' => tripal_format_bytes($entry->custom_quota),
+      'exp_date' => $entry->custom_expiration,
+    );
+  }
+
+  // Add the Actions links
+  foreach($rows as $key => $entry){
+    $rows[$key]['actions'] = l('Edit', 'admin/tripal/files/quota/edit/' . $entry['uid']) . ' | ' .
+      l('Remove', 'admin/tripal/files/quota/remove/' . $entry['uid']);
+  }
+
+  $form['custom'] = array(
+    '#type' => 'fieldset',
+    '#title' => 'Custom Settings',
+    '#description' => t('The settings above apply to all users.  The following allows for custom user settings that override the defaults set above.'),
+    '#collapsed' => TRUE,
+    '#collapsible' => FALSE,
+  );
+
+  $form['custom']['links'] = array(
+    '#type' => 'markup',
+    '#markup' => '<br>' . l('Add Custom User Quota', 'admin/tripal/files/quota/add'),
+  );
+
+  $form['custom']['custom_quotas'] = array(
+    '#type' => 'item',
+    '#title' => t('Custom User Quotas'),
+
+    '#markup' => theme_table(array(
+      'header' => $header,
+      'rows' => $rows,
+      'attributes' => array(),
+      'caption' => '',
+      'sticky' => TRUE,
+      'empty' => 'There are no custom user quotas.',
+      'colgroups' => array(),
+    )),
+  );
+
+  $form['update_defaults'] = array (
+    '#type' => 'submit',
+    '#value' => t('Save'),
+  );
+
+  return $form;
+}
+
+
+/**
+ * Validate the form's values: proper numbers and/or MB, GB, TB for quota field.
+ **/
+function tripal_admin_manage_quota_form_validate($form, &$form_state) {
+  $quota = $form_state['values']['default_quota'];
+  $expiration = $form_state['values']['default_expiration_date'];
+
+  // Validate the quota string.
+  if (!preg_match("/^\d+(\.\d+)*(MB|GB|TB)$/", $quota)) {
+    form_set_error('default_quota', t('Please provide a quota size in the format indicated.'));
+  }
+
+  // Validate the expiration time.
+  if (!preg_match("/^\d+$/", $expiration)) {
+    form_set_error('default_expiration', t('Please providate a positive non-decimal numeric value for the days to expire'));
+  }
+
+}
+
+/**
+ * Write to the two drupal variables the site wide defualt quota and exp date.
+ **/
+function tripal_admin_manage_quota_form_submit($form, &$form_state) {
+  $quota = $form_state['values']['default_quota'];
+  $expiration = $form_state['values']['default_expiration_date'];
+
+  // if the 2nd element of the qutoa string occupied by a valid suffix we need to check to see
+  // what we have to multiply the value by (1024 for GB 1024^2 for TB because
+  // we assume that the initial number is already in MB)
+  $matches = array();
+  $multiplier = 'MB';
+  $size = $quota;
+  if (preg_match("/^(\d+(?:\.\d+)*)(MB|GB|TB)$/", $quota, $matches)) {
+    $multiplier = $matches[2];
+    $size = $matches[1];
+  }
+
+  switch ($multiplier) {
+    case 'GB':
+      $size = (int) ($size * pow(10,9));
+      break;
+    case 'TB':
+      $size = (int) ($size * pow(10,12));
+      break;
+    default:
+      $size = (int) ($size * pow(10,6));
+      break;
+  }
+
+  // Grab the quota value and exp_date to write to the drupal variables
+  variable_set('tripal_default_file_quota', $size);
+  variable_set('tripal_default_file_expiration', $expiration);
+
+  drupal_set_message('Default quota settings have been set.');
+}
+
+/**
+ * API call to remove a user from the custom quota table
+ *
+ * @return Boolean value to confirm removal from the table.
+ **/
+function tripal_admin_remove_quota_form($form, &$form_state, $uid) {
+  $form = array();
+
+  $form['uid'] = array(
+    '#type' => 'value',
+    '#value' => $uid,
+  );
+
+  $user = user_load($uid);
+  if (!$user) {
+    drupal_set_message('There was a problem finding this user\'s account. Could not remove the quota', 'error');
+    drupal_goto('admin/tripal/files/quota');
+    return $form;
+  }
+
+  return confirm_form($form,
+    t('Confirm removal of the custom quota for the user: "' . $user->name . '"?'),
+    'admin/tripal/files/quota',
+    t('Removal of the custom quota will enforce default quotas for the user. If the user\'s current usage exceeds the defaults the user must then remove files before more may be uploaded.')
+  );
+}
+
+/**
+ * Implements submit hook for the tripal_admin_remove_quota_form form.
+ */
+function tripal_admin_remove_quota_form_submit($form, &$form_state) {
+  $uid = $form_state['values']['uid'];
+  tripal_remove_user_quota($uid);
+
+  $user = user_load($uid);
+  drupal_set_message('The custom quota for user, "' . $user->name . '", has been removed.');
+
+  drupal_goto('admin/tripal/files/quota');
+}
+
+/**
+ * Provides contents for the File Usgae page.
+ */
+function tripal_admin_file_usage_page() {
+  // set the breadcrumb
+  $breadcrumb = array();
+  $breadcrumb[] = l('Home', '<front>');
+  $breadcrumb[] = l('Administration', 'admin');
+  $breadcrumb[] = l('Tripal', 'admin/tripal');
+  $breadcrumb[] = l('User File Management', 'admin/tripal/files');
+  drupal_set_breadcrumb($breadcrumb);
+  
+  $content = [
+    [
+      '#type' => 'markup',
+      '#markup' => 'Usage reports coming in the future...',
+    ],
+  ];
+  return $content;
+}

+ 2 - 2
tripal/includes/tripal.extensions.inc

@@ -361,7 +361,7 @@ function tripal_extension_form_add_extensions(&$form, $form_state, $extensions,
           }
           break;
         case 'Materialized View':
-          $mview_id = tripal_get_mview_id($extension[$namespace]['mview_name']);
+          $mview_id = chado_get_mview_id($extension[$namespace]['mview_name']);
           if ($mview_id) {
             $is_installed = '<li>A materialized view with this name is already installed.</li>';
           }
@@ -570,7 +570,7 @@ function tripal_extensions_form_submit($form, &$form_state) {
         if ($error) {
           drupal_set_message("Cannot import Materialized View: $error", "error");
         }
-        tripal_add_mview($mview_name, $module_name, $schema_array, $mview_sql);
+        chado_add_mview($mview_name, $module_name, $schema_array, $mview_sql);
         break;
       case 'Extension Module':
         if (array_key_exists('drupal_project', $extension[$namespace])) {

+ 18 - 0
tripal/includes/tripal.fields.inc

@@ -246,6 +246,8 @@ function tripal_field_no_delete() {
  * the table to let the user know where fields are storing their data.
  */
 function tripal_form_field_ui_field_overview_form_alter(&$form, &$form_state, $form_id) {
+  
+  $used_terms = [];
 
   // If this isn't a TripalEntity content type then skip this form.
   if ($form['#entity_type'] != 'TripalEntity') {
@@ -262,6 +264,22 @@ function tripal_form_field_ui_field_overview_form_alter(&$form, &$form_state, $f
 
     $field = field_info_field($field_name);
     $instance = field_info_instance('TripalEntity', $field_name, $form['#bundle']);
+    
+    // Warn users if any of the terms are not unique.
+    if ($instance and array_key_exists('settings', $instance) and is_array($instance['settings']) and 
+        array_key_exists('term_vocabulary', $instance['settings'])) {
+      $term = $instance['settings']['term_vocabulary'] . ':' . $instance['settings']['term_accession'];
+      if (array_key_exists($term, $used_terms)) {
+        $used_terms[$term][] = $field_name;
+        drupal_set_message(t('The term !term is in use by multiple fields: !fields. 
+          This is not allowed. Every field must have a different controlled vocabulary term. 
+          Please correct the term assignments.', 
+          array('!term' => $term, '!fields' => implode(', ', $used_terms[$term]))), 'error');
+      }
+      $used_terms[$term][] = $field_name;
+    }
+    
+    
     // For rows in the tables that aren't fields, just add an empty value
     // for the storage column.
     if (!$field) {

+ 33 - 7
tripal/includes/tripal.importer.inc

@@ -5,6 +5,7 @@
  * Build the form for a TripalImporter implementation.
  */
 function tripal_get_importer_form($form, &$form_state, $class) {
+  global $user;
 
   tripal_load_include_importer_class($class);
 
@@ -24,6 +25,20 @@ function tripal_get_importer_form($form, &$form_state, $class) {
   }
 
   if (array_key_exists('file_upload', $class::$methods) and $class::$methods['file_upload'] == TRUE) {
+    
+    $existing_files = tripal_get_user_uploads($user->uid, $class::$file_types);
+    if (count($existing_files) > 0) {
+      $fids = [0 => '--Select a file--'];
+      foreach ($existing_files as $fid => $file) {
+        $fids[$fid] = $file->filename . ' (' . tripal_format_bytes($file->filesize) . ') ';
+      }
+      $form['file']['file_upload_existing'] = [
+        '#type' => 'select',
+        '#title' => t('Existing Files'),
+        '#description' => t('You may select a file that is already uploaded.'),
+        '#options' => $fids,
+      ];
+    }
     $form['file']['file_upload']= array(
       '#type' => 'html5_file',
       '#title' => '',
@@ -102,7 +117,8 @@ function tripal_get_importer_form_validate($form, &$form_state) {
   $file_local = NULL;
   $file_upload = NULL;
   $file_remote = NULL;
-
+  $file_existing = NULL;
+  
   // Get the form values for the file.
   if (array_key_exists('file_local', $class::$methods) and $class::$methods['file_local'] == TRUE) {
     $file_local = trim($form_state['values']['file_local']);
@@ -123,15 +139,16 @@ function tripal_get_importer_form_validate($form, &$form_state) {
   }
   if (array_key_exists('file_upload', $class::$methods) and $class::$methods['file_upload'] == TRUE) {
     $file_upload = trim($form_state['values']['file_upload']);
+    if (array_key_exists('file_upload_existing', $form_state['values']) and $form_state['values']['file_upload_existing']) {
+      $file_existing = $form_state['values']['file_upload_existing'];
+    }
   }
   if (array_key_exists('file_remote', $class::$methods) and $class::$methods['file_remote'] == TRUE) {
     $file_remote = trim($form_state['values']['file_remote']);
   }
 
-
-
   // The user must provide at least an uploaded file or a local file path.
-  if ($class::$file_required == TRUE and !$file_upload and !$file_local and !$file_remote) {
+  if ($class::$file_required == TRUE and !$file_upload and !$file_local and !$file_remote and !$file_existing) {
     form_set_error('file_local', t("You must provide a file."));
   }
 
@@ -154,6 +171,7 @@ function tripal_get_importer_form_submit($form, &$form_state) {
   // full file path and the fid instead.
   unset($run_args['file_local']);
   unset($run_args['file_upload']);
+  unset($run_args['file_upload_existing']);
   unset($run_args['form_build_id']);
   unset($run_args['form_token']);
   unset($run_args['form_id']);
@@ -163,6 +181,7 @@ function tripal_get_importer_form_submit($form, &$form_state) {
   $file_local = NULL;
   $file_upload = NULL;
   $file_remote = NULL;
+  $file_existing = NULL;
 
   // Get the form values for the file.
   if (array_key_exists('file_local', $class::$methods) and $class::$methods['file_local'] == TRUE) {
@@ -170,23 +189,30 @@ function tripal_get_importer_form_submit($form, &$form_state) {
   }
   if (array_key_exists('file_upload', $class::$methods) and $class::$methods['file_upload'] == TRUE) {
     $file_upload = trim($form_state['values']['file_upload']);
+    if (array_key_exists('file_upload_existing', $form_state['values']) and $form_state['values']['file_upload_existing']) {
+      $file_existing = trim($form_state['values']['file_upload_existing']);
+    }
   }
   if (array_key_exists('file_remote', $class::$methods) and $class::$methods['file_remote'] == TRUE) {
     $file_remote = trim($form_state['values']['file_remote']);
   }
 
+
   // Sumbit a job for this loader.
   $fname = '';
   $fid = NULL;
   $file_details = array();
-  if ($file_local) {
+  if ($file_existing) {
+    $file_details['fid'] = $file_existing;
+  }
+  elseif ($file_local) {
     $fname = preg_replace("/.*\/(.*)/", "$1", $file_local);
     $file_details['file_local'] = $file_local;
   }
-  if ($file_upload) {
+  elseif ($file_upload) {
     $file_details['fid'] = $file_upload;
   }
-  if ($file_remote) {
+  elseif ($file_remote) {
     $file_details['file_remote'] = $file_remote;
   }
   try {

+ 85 - 30
tripal/includes/tripal.upload.inc

@@ -7,11 +7,10 @@ function tripal_file_upload($type, $filename, $action = NULL, $chunk = 0) {
   $file_size = array_key_exists('file_size', $_GET) ? $_GET['file_size'] : '';
   $chunk_size = array_key_exists('chunk_size', $_GET) ? $_GET['chunk_size'] : '';
 
-  $user_dir = 'public://tripal/users/' . $user->uid;
-
-  if (!file_prepare_directory($user_dir, FILE_CREATE_DIRECTORY)) {
-    $message = 'Could not access the directory on the server for storing this file.';
-    watchdog('tripal', $message, array(), WATCHDOG_ERROR);
+  $user_dir = tripal_get_user_files_dir($user);
+  if (!tripal_is_user_files_dir_writeable($user)) {
+    $message = 'The user\'s data directory is not writeable: !user_dir.';
+    watchdog('tripal', $message, array('!user_dir' => $user_dir), WATCHDOG_ERROR);
     drupal_json_output(array(
       'status'  => 'failed',
       'message' => $message,
@@ -19,6 +18,38 @@ function tripal_file_upload($type, $filename, $action = NULL, $chunk = 0) {
     ));
     return;
   }
+  
+  // Make sure we don't go over the user's quota, but only do this check
+  // before loading the first chunk so we don't repeat it over and over again.
+  if ($action == 'check' and $chunk == 0) {
+    $usage = tripal_get_user_usage($user->uid);
+    $quota = tripal_get_user_quota($user->uid);
+    $quota_size = $quota->custom_quota;
+    if ($file_size + $usage > $quota_size) {
+      drupal_json_output(array(
+        'status' => 'failed',
+        'message' => t("Unfortunately, you can not upload this file as the size exceeds the remainder of your quota. See your account page under the 'Uploads' tab to manage your uploaded files."),
+        'file_id' => '',
+      ));
+      return;
+    }
+    
+    // Make sure we don't go over the max file upload size.
+    $upload_max = variable_get('tripal_upload_max_size', 10000000000);
+    if ($file_size > $upload_max) {
+      $message = t("Unfortunately, you can not upload this file as the size exceeds the the maximum file size allowed by this site: " . tripal_format_bytes($upload_max) . '. ');
+      
+      if (user_access('administer tripal')) {
+        $message .= t('You can manage the file upload by visiting: Home » Administration » Tripal » User File Management.');
+      }
+      drupal_json_output(array(
+        'status' => 'failed',
+        'message' => $message,
+        'file_id' => '',
+      ));
+      return;
+    }
+  }
 
   // Allow the module that will own the file to make some checks. The module
   // is allowed to stop the upload as needed.
@@ -42,7 +73,7 @@ function tripal_file_upload($type, $filename, $action = NULL, $chunk = 0) {
   }
 
   switch ($action) {
-    // If the action is 'put' then the callee is sending a chunk of the file
+    // If the action is 'save' then the callee is sending a chunk of the file
     case 'save':
       tripal_file_upload_put($filename, $chunk, $user_dir);
       break;
@@ -56,7 +87,6 @@ function tripal_file_upload($type, $filename, $action = NULL, $chunk = 0) {
 }
 /**
  * Merges all chunks into a single file
- * @param unknown $filename
  */
 function tripal_file_upload_merge($filename, $type, $user_dir) {
   global $user;
@@ -127,33 +157,58 @@ function tripal_file_upload_merge($filename, $type, $user_dir) {
     $status = 'failed';
     $message = 'Merge file is missing after upload ' . $merge_file . '.';
   }
+  
   $file_id = NULL;
 
-  // If the file has been successfully merged then let the calling module
-  // deal with it.
-  if ($status != 'failed') {
-    $function = $module . '_handle_uploaded_file';
-    if(function_exists($function)) {
-      $file_id = $function($filename, $merge_file, $type);
-      if ($file_id) {
-        $file = file_load($file_id);
-        $status = 'completed';
-        $full_path = drupal_realpath($file->uri);
-        $md5sum = md5_file($full_path);
-        $md5sum_file = fopen("$full_path.md5", "w");
-        fwrite($md5sum_file, $md5sum);
-        fclose($md5sum_file);
-        unlink($temp_dir);
-      }
-      else {
-        $status = 'failed';
-        $message = 'Could not add file to the database.';
-      }
+  // If the file has been successfully merged then do a few other things...
+  if ($status != 'failed') {   
+    
+    // See if this file is already managed if so, then it has been uploaded
+    // before and we don't need to add a managed item again.
+    $fid = db_select('file_managed', 'fm')
+      ->fields('fm', ['fid'])
+      ->condition('uri', $merge_file)
+      ->execute()
+      ->fetchField();
+    
+    // Add the file if it is not already managed.
+    if (!$fid) {
+      $file = new stdClass();
+      $file->uri = $merge_file;
+      $file->filename = $filename;
+      $file->filemime = file_get_mimetype($merge_file);
+      $file->uid = $user->uid;
+      $file->status = FILE_STATUS_PERMANENT;
+      $file = file_save($file);
+      $fid = $file->fid;
     }
-    else {
-      $status = 'failed';
-      $message = 'Cannot find the function: ' . $function . '().';
+    
+    // Reload the file object to get a full object.
+    $file_id = $fid;
+    $file = file_load($fid);
+    
+    // Set the file as being managed by Tripal.
+    file_usage_add($file, 'tripal', $type, 0);
+    
+    // Set the file expiration.
+    tripal_reset_file_expiration($fid);
+    
+    // Generate an md5 file the uploaded file.
+    $full_path = drupal_realpath($file->uri);
+    $md5sum = md5_file($full_path);
+    $md5sum_file = fopen("$full_path.md5", "w");
+    fwrite($md5sum_file, $md5sum);
+    fclose($md5sum_file);
+    
+    // Remove the temporary directory.
+    file_unmanaged_delete_recursive($temp_dir);
+    
+    // Now let the submitting module deal with it.
+    $function = $module . '_handle_uploaded_file';
+    if (function_exists($function)) {
+      $function($file, $type);
     }
+    $status = 'completed';
   }
 
   if ($status == 'failed') {

+ 328 - 0
tripal/includes/tripal.user.inc

@@ -0,0 +1,328 @@
+<?php
+
+
+/**
+ * Provides the page with a list of files uploaded by the user.
+ *
+ * @param $uid
+ *   The user ID.
+ *
+ * @return
+ *   A Drupal render array.
+ */
+ function tripal_user_files_page($uid) {
+
+   // Get all of the files that have been uploaded by the user.
+   // TODO: we should make this a paged query in case a user has a huge
+   // numbef of uploaded files.
+   $sql = "
+     SELECT FM.fid, FM.filename, TGEF.expiration_date
+     FROM {file_managed} FM
+       INNER JOIN {file_usage} FU on FM.fid = FU.fid and FM.uid = :user_id
+       LEFT JOIN {tripal_expiration_files} TGEF on TGEF.fid = FU.fid
+     WHERE FU.module = 'tripal'
+     GROUP BY FM.fid, TGEF.expiration_date
+     ORDER BY FM.filename
+   ";
+   $files = db_query($sql, array(':user_id' => $uid));
+   $rows = array();
+   While ($entry = $files->fetchObject()) {
+    $file = file_load($entry->fid);
+
+    // Don't list files that don't exist on the file system.
+    if (!file_exists($file->uri)) {
+      continue;
+    }
+
+    $date_uploaded = date('Y-m-d H:i:s', $file->timestamp);
+    $expiration = $entry->expiration_date ? date('Y-m-d H:i:s', $entry->expiration_date) : '';
+    $actions = l('Delete', "user/$uid/files/$file->fid/delete") . ' | ' .
+               l('Renew', "user/$uid/files/$file->fid/renew");
+
+    $rows[] = array(
+      $entry->fid,
+      l($file->filename,"/user/$uid/files/$file->fid"),
+      $date_uploaded,
+      $expiration,
+      tripal_format_bytes($file->filesize),
+      $actions,
+    );
+  }
+  $header = array('ID', 'File Name', 'Upload Date', 'Expiration', 'Size', 'Actions');
+
+  // Get the user quota settings.
+  $quota = tripal_get_user_quota($uid);
+  $usage = tripal_get_user_usage($uid);
+
+  $content = array(
+    'page_title' => array(
+      '#type' => 'markup',
+      '#markup' => '<h2>Your Uploaded Files</h2>',
+    ),
+    'page_description' => array(
+      '#type' => 'markup',
+      '#markup' => '<p>' . t('Each user is allowed to consume a limited amount of space with uploaded files. This page provides details about your current usage, your limits and files you\'ve uploaded.') . '</p>',
+    ),
+    'usage' => array(
+      '#type' => 'item',
+      '#title' => 'Current Usage',
+      '#markup' => tripal_format_bytes($usage),
+      '#description' => t('The total number of bytes you currently consume.'),
+    ),
+    'quota' => array(
+      '#type' => 'item',
+      '#title' => 'Current Quota',
+      '#markup' => tripal_format_bytes($quota->custom_quota),
+      '#description' => t('The maximum number of bytes of files you can upload.')
+    ),
+    'expiration' => array(
+      '#type' => 'item',
+      '#title' => 'Current Days to Expire',
+      '#markup' => $quota->custom_expiration,
+      '#description' => t('The number of days a file will remain on the server before deletion. The expiration of date of a file can be renewed using the "Renew" link in the table below.')
+    ),
+    'file_list' => array(
+      '#type' => 'item',
+      '#title' => 'Uploaded Files',
+      '#markup' => theme_table(array(
+        'header' => $header,
+        'rows' => $rows,
+        'attributes' => array(),
+        'caption' => t('Click a file name for more details.'),
+        'colgroups' => array(),
+        'sticky' => TRUE,
+        'empty' => 'You currently have no uploaded files.',
+      )),
+    )
+  );
+
+
+  if ($usage < $quota->custom_quota) {
+    drupal_set_message('Your file usage is currently below the file quota limit.');
+  }
+  else {
+    drupal_set_message('Your file usage is currently over your file quota limit. Please remove some files before uploading more', 'warning');
+  }
+
+  return $content;
+}
+
+/**
+ * User action to renew the expiration of a file.
+ *
+ * Adds the current time and the expiration date (either from default or if
+ * the user has a custom expiration date) to tripal_expiration_files
+ * table.
+ *
+ **/
+function tripal_renew_file($fid) {
+  $file = file_load($fid);
+  $success = tripal_reset_file_expiration($fid);
+
+  if ($success) {
+    drupal_set_message('Successfully updated expiration date.');
+  }
+  drupal_goto('user/' . $file->uid . '/files/');
+}
+
+/**
+ * Downloads a file.
+ *
+ * @param $fid
+ *   The File ID of the file to be downloaded.
+ */
+function tripal_download_file($fid) {
+  $file = file_load($fid);
+  if (file_exists($file->uri)) {
+    $headers = array();
+    $headers['Content-Type'] = $file->filemime;
+    $headers['Content-Disposition']  = 'attachment; filename=' . $file->filename;
+    $headers['Content-Length'] = $file->filesize;
+    file_transfer($file->uri, $headers);
+  }
+  else {
+    drupal_set_message('Can not download. The file no longer exists on the server.', 'error');
+    drupal_goto('user/' . $file->uid . '/files/');
+  }
+}
+
+/**
+ * Provides a confirmation form for deleting a galaxy workflow uploaded file.
+ */
+function tripal_delete_file_form($form, $form_state, $uid, $fid) {
+  $form = array();
+
+  $file = file_load($fid);
+
+  $form['uid'] = array(
+    '#type' => 'value',
+    '#value' => $uid,
+  );
+  $form['fid'] = array(
+    '#type' => 'value',
+    '#value' => $fid,
+  );
+
+  return confirm_form($form,
+      t('Confirm deletion of the file named "' . $file->filename . '"?'),
+      'user/' . $uid . '/files/',
+      t('Warning.  If this file is intended to be used with a analysis workflow submission that has not yet started then the workflow will fail. Once deleted, the file can no longer be used for new workflow submissions without uploading again.')
+  );
+}
+
+/**
+ * Implements a form submit for deleting a galaxy workflow uploaded file.
+ */
+function tripal_delete_file_form_submit($form, &$form_state) {
+  $fid = $form_state['values']['fid'];
+  $uid = $form_state['values']['uid'];
+  $file = file_load($fid);
+
+  // Remove the file from the file_usage table for all entries that link
+  // to the tripal module.
+  file_usage_delete($file, 'tripal', NULL, NULL, 0);
+
+  // Get any remaining usage for other modules
+  $file_usage = file_usage_list($file);
+
+  // If this file is still used by the tripal module then something
+  // didn't work right.
+  if (in_array('tripal', $file_usage)) {
+    drupal_set_message('The file could not be removed.  Please contact the site administrator.', 'error');
+  }
+
+  // If there is no other usage of this file from other modules then delete it.
+  if (count(array_keys($file_usage)) == 0) {
+    if (file_unmanaged_delete($file->uri)) {
+
+      // Also remove the md5 checksum.
+      if (file_exists(file_unmanaged_delete($file->uri . '.md5'))) {
+        file_unmanaged_delete($file->uri . '.md5');
+      }
+      drupal_set_message('The file has been fully removed.');
+    }
+    else {
+      drupal_set_message('The file has removed from this list and does not count against your quota, but other components of this site rely on this file. Thus it has not been fully removed.');
+    }
+  }
+  drupal_goto('user/' . $file->uid . '/files/');
+}
+
+/**
+ * Provides details about a file.
+ */
+function tripal_view_file($uid, $fid) {
+  $file = file_load($fid);
+
+  $headers = array();
+  $rows = array();
+
+  $actions = l('Delete', "user/$uid/files/$file->fid/delete") . '<br>' .
+             l('Download', "user/$uid/files/$file->fid/download");
+
+  // Name row
+  $rows[] = array(
+    array(
+      'data' => 'File Name',
+      'header' => TRUE,
+      'width' => '20%',
+    ),
+    $file->filename
+  );
+
+  $date_uploaded = date('Y-m-d H:i:s', $file->timestamp);
+  $rows[] = array(
+    array(
+      'data' => 'Upload Date',
+      'header' => TRUE,
+      'width' => '20%',
+    ),
+    $date_uploaded
+  );
+
+  $expiration_date = db_select('tripal_expiration_files', 'tgef')
+    ->fields('tgef', array('expiration_date'))
+    ->condition('fid', $fid)
+    ->execute()
+    ->fetchField();
+  $expiration = $expiration_date ? date('Y-m-d H:i:s', $expiration_date) : '';
+  $rows[] = array(
+    array(
+      'data' => 'Expiration Date',
+      'header' => TRUE,
+      'width' => '20%',
+    ),
+    $expiration
+  );
+
+  // Find which workflow submissions are using this file.
+  $usage = file_usage_list($file);
+  $usage = $usage['tripal'];
+  $workflow_nids = array();
+  foreach ($usage as $step => $nid) {
+    $nid = array_keys($nid)[0];
+    if (!in_array($nid, $workflow_nids)) {
+      $workflow_nids[] = $nid;
+    }
+  }
+  $wf_links = array();
+  foreach ($workflow_nids as $i => $nid) {
+    $query = db_select('tripal_workflow', 'tgw');
+    $query->fields('tgw', array('workflow_name'));
+    $query->innerJoin('tripal_workflow_submission', 'tgws', 'tgw.galaxy_workflow_id = tgws.galaxy_workflow_id');
+    $query->fields('tgws', array('sid'));
+    $query->condition('tgw.nid', $nid, '=');
+    $results = $query->execute();
+    $workflow = $results->fetchObject();
+    if ($workflow) {
+      $wf_links[] = l($workflow->workflow_name . ' (submission ID: ' . $workflow->sid . ')', "user/$uid/galaxy-jobs/$workflow->sid");
+    }
+  }
+  $rows[] = array(
+    array(
+      'data' => 'Usage',
+      'header' => TRUE,
+      'width' => '20%',
+    ),
+    theme_item_list(array(
+      'items' => $wf_links,
+      'title' => '',
+      'type' => 'ul',
+      'attributes' => array(),
+    )),
+  );
+  $rows[] = array(
+    array(
+      'data' => 'Actions',
+      'header' => TRUE,
+      'width' => '20%',
+    ),
+    $actions
+  );
+
+  $content = array(
+    'description' => array(
+      '#type' => 'markup',
+      '#markup' => '<p>' . t('The following file has been uploaded for use in an analytical workflow.') . '</p>',
+    ),
+    'return' => array(
+      '#type' => 'markup',
+      '#markup' => '<p>' . l('View all Uploaded Files', "user/$uid/files") . '</p>',
+    ),
+    'file_details' => array(
+      '#type' => 'markup',
+      '#markup' => theme_table(array(
+        'header' => $headers,
+        'rows' => $rows,
+        'attributes' => array(),
+        'sticky' => FALSE,
+        'caption' => '',
+        'colgroups' => array(),
+        'empty' => '',
+      )),
+    ),
+  );
+  return $content;
+}
+
+

+ 84 - 0
tripal/tripal.install

@@ -154,6 +154,8 @@ function tripal_schema() {
   $schema['tripal_jobs'] = tripal_tripal_jobs_schema();
   $schema['tripal_token_formats'] = tripal_tripal_token_formats_schema();
   $schema['tripal_variables'] = tripal_tripal_variables_schema();
+  $schema['tripal_custom_quota'] = tripal_tripal_custom_quota_schema();
+  $schema['tripal_expiration_files'] = tripal_tripal_expiration_files_schema();
 
 
   // Adds a table for managing TripalEntity entities.
@@ -835,6 +837,71 @@ function tripal_tripal_bundle_variables_schema() {
   return $schema;
 }
 
+/**
+ * Provides the schema for the tripal_custom_quota table.
+ */
+function tripal_tripal_custom_quota_schema() {
+  $schema = array(
+    'table' => 'tripal_custom_quota',
+    'fields' => array(
+      'uid' => array(
+        'type' => 'int',
+        'size' => 'big',
+        'not NULL' => TRUE,
+      ),
+      'custom_quota' => array(
+        'type' => 'int',
+        'size' => 'big',
+        'not NULL' => TRUE,
+      ),
+      'custom_expiration' => array(
+        'type' => 'int',
+        'size' => 'big',
+        'not NULL' => TRUE,
+      ),
+    ),
+    'primary key' => array('uid'),
+    'unique keys' => array(
+      'tripal_custom_quota_uq1' => array('uid'),
+    ),
+    'indexes' => array(
+      'tripal_custom_quota_idx1' => array('uid'),
+    ),
+  );
+  return $schema;
+}
+
+/**
+ * Provides the schema for the tripal_expiration_files table.
+ */
+function tripal_tripal_expiration_files_schema() {
+  $schema = array (
+    'table' => 'tripal_expiration_files',
+    'fields' => array (
+      'fid' => array(
+        'type' => 'int',
+        'not NULL' => TRUE
+      ),
+      'expiration_date' => array(
+        'type' => 'int',
+        'size' => 'big',
+        'not NULL' => TRUE
+      ),
+    ),
+    'primary key' => array(
+      0 => 'fid'
+    ),
+    'unique keys' => array(
+      'tripal_expiration_files_uq1' => array('fid'),
+    ),
+    'indexes' => array(
+      'tripal_expiration_files_idx1' => array('fid'),
+    ),
+  );
+  return $schema;
+}
+
+
 /**
  * Additional Tripal Admin Notification Information.
  *
@@ -1096,3 +1163,20 @@ function tripal_update_7310() {
     throw new DrupalUpdateException('Could not add the tripal_collection_bundle table:' . $error);
   }
 }
+
+/**
+ * Adds support for file quotas.
+ */
+function tripal_update_7311() {
+  try {
+    $schema = array();
+    $schema['tripal_custom_quota'] = tripal_tripal_custom_quota_schema();
+    $schema['tripal_expiration_files'] = tripal_tripal_expiration_files_schema();
+    db_create_table('tripal_custom_quota', $schema['tripal_custom_quota']);
+    db_create_table('tripal_expiration_files', $schema['tripal_expiration_files']);
+  }
+  catch (\PDOException $e) {
+    $error = $e->getMessage();
+    throw new DrupalUpdateException('Could not perform update: '. $error);
+  }
+}

+ 233 - 61
tripal/tripal.module

@@ -424,10 +424,213 @@ function tripal_menu() {
     'file' => 'includes/tripal.admin.inc',
     'file path' => drupal_get_path('module', 'tripal'),
   );
-
+  
+  
+  //
+  // USER FILE MANAGEMENT
+  //
+  $items['admin/tripal/files'] = [
+    'title' => 'User File Management',
+    'description' => 'Set maximum upload sizes, quotas and view usage.',
+    'page callback' => 'drupal_get_form',
+    'page arguments' => ['tripal_admin_manage_files_form'],
+    'access arguments' => ['administer tripal'],
+    'type' => MENU_NORMAL_ITEM,
+    'file' => 'includes/tripal.admin_files.inc',
+    'file path' => drupal_get_path('module', 'tripal'),
+    'weight' => 30,
+  ];
+  
+  $items['admin/tripal/files/quota'] = [
+    'title' => 'User Quotas',
+    'description' => 'Set default quota, expiration date, and custom quotas',
+    'page callback' => 'drupal_get_form',
+    'page arguments' => ['tripal_admin_manage_quota_form'],
+    'access arguments' => ['administer tripal'],
+    'type' => MENU_LOCAL_TASK,
+    'file' => 'includes/tripal.admin_files.inc',
+    'file path' => drupal_get_path('module', 'tripal'),
+    'weight' => 10,
+  ];
+  
+  // Admin remove user quota
+  $items['admin/tripal/files/quota/remove/%'] = [
+    'title' => 'Remove custom user quota',
+    'description' => "Revert's a user's quota and expiration of files to the site wide defaults.",
+    'page callback' => 'drupal_get_form',
+    'page arguments' => ['tripal_admin_remove_quota_form', 5],
+    'access arguments' => ['administer tripal'],
+    'type' => MENU_CALLBACK,
+    'file' => 'includes/tripal.admin_files.inc',
+    'file path' => drupal_get_path('module', 'tripal'),
+  ];
+  
+  // Add user quota
+  $items['admin/tripal/files/quota/add'] = [
+    'title' => 'Add Custom Quota',
+    'description' => 'Gives the user a new quota and expiration date',
+    'page callback' => 'drupal_get_form',
+    'page arguments' => ['tripal_admin_add_custom_form'],
+    'access arguments' => ['administer tripal'],
+    // TODO: Ask Stephen is this is fine as a link at the top of the form
+    // as well as a link in the table
+    'type' => MENU_CALLBACK,
+    'file' => 'includes/tripal.admin_files.inc',
+    'file path' => drupal_get_path('module', 'tripal'),
+  ];
+  
+  // Autocomplete path for the users on the site
+  $items['admin/tripal/files/quota/user/autocomplete'] = [
+    'title' => 'Autocomplete for existing users',
+    'description' => 'Provide a list of existing users on the site.',
+    'page callback' => 'tripal_users_autocomplete',
+    'access arguments' => ['administer tripal'],
+    'type' => MENU_CALLBACK,
+    'file' => 'includes/tripal.admin_files.inc',
+    'file path' => drupal_get_path('module', 'tripal'),
+  ];
+  
+  // Edit user quota
+  $items['admin/tripal/files/quota/edit/%'] = [
+    'title' => 'Edit Custom Quota',
+    'description' => 'Edit an existing user\'s quota and/or expiration date.',
+    'page callback' => 'drupal_get_form',
+    'page arguments' => ['tripal_admin_edit_quota_form', 5],
+    'access arguments' => ['administer tripal'],
+    'type' => MENU_CALLBACK,
+    'file' => 'includes/tripal.admin_files.inc',
+    'file path' => drupal_get_path('module', 'tripal'),
+  ];
+  
+  $items['admin/tripal/files/usage'] = [
+    'title' => 'File Usage',
+    'description' => 'Set default quota, expiration date, and custom quotas',
+    'page callback' => 'drupal_get_form',
+    'page arguments' => ['tripal_admin_file_usage_page'],
+    'access arguments' => ['administer tripal'],
+    'type' => MENU_LOCAL_TASK,
+    'file' => 'includes/tripal.admin_files.inc',
+    'file path' => drupal_get_path('module', 'tripal'),
+    'weight' => 15
+  ];
+
+  
+  //
+  // USER FILES
+  //
+  
+  // User view quota (Tab)
+  $items['user/%/files'] = [
+    'title' => 'Uploads',
+    'description' => 'Monitors what files that have been uploaded by user through the tripal module',
+    'page callback' => 'tripal_user_files_page',
+    'page arguments' => [1],
+    'access callback' => 'tripal_access_user_uploads',
+    'access arguments' => ['view', 1],
+    'type' => MENU_LOCAL_TASK,
+    'file' => 'includes/tripal.user.inc',
+    'file path' => drupal_get_path('module', 'tripal'),
+    'weight' => 10,
+  ];
+  
+  $items['user/%/files/%'] = [
+    'title' => 'File Details',
+    'description' => "View details about the file",
+    'page callback' => 'tripal_view_file',
+    'page arguments' => [1, 3],
+    'access callback' => 'tripal_access_user_uploads',
+    'access arguments' => ['renew', 1, 3],
+    'type' => MENU_CALLBACK,
+    'file' => 'includes/tripal.user.inc',
+    'file path' => drupal_get_path('module', 'tripal'),
+  ];
+  // User file renew.
+  $items['user/%/files/%/renew'] = [
+    'title' => 'Renew File',
+    'description' => "Renew a user's file",
+    'page callback' => 'tripal_renew_file',
+    'page arguments' => [3],
+    'access callback' => 'tripal_access_user_uploads',
+    'access arguments' => ['renew', 1, 3],
+    'type' => MENU_CALLBACK,
+    'file' => 'includes/tripal.user.inc',
+    'file path' => drupal_get_path('module', 'tripal'),
+  ];
+  // User file download.
+  $items['user/%/files/%/download'] = [
+    'title' => 'Download File',
+    'description' => "Download a user's file based off of the link clicked in the table",
+    'page callback' => 'tripal_download_file',
+    'page arguments' => [3],
+    'access arguments' => ['download', 1, 3],
+    'access callback' => 'tripal_access_user_uploads',
+    'type' => MENU_CALLBACK,
+    'file' => 'includes/tripal.user.inc',
+    'file path' => drupal_get_path('module', 'tripal'),
+  ];
+  // User file delete.
+  $items['user/%/files/%/delete'] = [
+    'title' => 'Delete File',
+    'description' => "Delete a user's file based on either user action or expired file",
+    'page callback' => 'drupal_get_form',
+    'page arguments' => ['tripal_delete_file_form', 1, 3],
+    'access callback' => 'tripal_access_user_uploads',
+    'access arguments' => ['delete', 1, 3],
+    'type' => MENU_CALLBACK,
+    'file' => 'includes/tripal.user.inc',
+    'file path' => drupal_get_path('module', 'tripal'),
+  ];
   return $items;
 }
 
+/**
+ * Checks if the current user has permissions to perform an action on a file.
+ *
+ * @param $op
+ *   The operation to perform.  These include 'view', 'download', 'renew' and 
+ *   'delete'
+ * @param $uid
+ *   The user ID of the user's account that owns the file.
+ * @param $fid
+ *   The file ID.
+ */
+function tripal_access_user_uploads($op, $uid, $fid = NULL) {
+  global $user;
+  
+  // The site admin can do anything.
+  if (in_array('administrator', $user->roles)) {
+    return TRUE;
+  }
+  
+  // Only the user that owns the files can see them.
+  if ($uid != $user->uid) {
+    return FALSE;
+  }
+  
+  // If no file ID is provided and the user wants to view then
+  // this is the case where the user wants to see all the files.
+  if (!$fid and $op == 'view') {
+    return TRUE;
+  }
+    
+  $file = file_load($fid);
+  switch ($op) {
+    case 'view':
+    case 'download':
+    case 'renew':
+    case 'delete':
+      if ($user->uid == $file->uid) {
+        return TRUE;
+      }
+      break;
+  }
+  return FALSE;
+}
+/**
+ * An access function for data collections.
+ * 
+ * @return boolean
+ */
 function tripal_accesss_user_collections($uid) {
   if (!tripal_access_user_data($uid)) {
     return FALSE;
@@ -439,6 +642,24 @@ function tripal_accesss_user_collections($uid) {
   return TRUE;
 }
 
+/**
+ * Autocomplete function for listing existing users on the site.
+ *
+ * @return json array of users that match the query in the textfield
+ **/
+function tripal_users_autocomplete($string) {
+  $matches = [];
+  $result = db_select('users', 'u')
+    ->fields('u', ['name'])
+    ->condition('name', '%' . db_like($string) . '%', 'LIKE')
+    ->execute();
+  
+  foreach ($result as $row) {
+    $matches[$row->name] = check_plain($row->name);
+  }
+  drupal_json_output($matches);
+}
+
 /**
  * Access callback for accessing a user's Tripal-added private data.
  *
@@ -770,6 +991,7 @@ function tripal_import_api() {
   module_load_include('inc', 'tripal', 'api/tripal.variables.api');
   module_load_include('inc', 'tripal', 'api/tripal.upload.api');
   module_load_include('inc', 'tripal', 'api/tripal.collections.api');
+  module_load_include('inc', 'tripal', 'api/tripal.quotas.api');
   module_load_include('inc', 'tripal', 'api/tripal.DEPRECATED.api');
 }
 
@@ -1105,37 +1327,25 @@ function tripal_block_configure($delta = '') {
 function tripal_cron() {
 
   // Add jobs to the Tripal queue for commong tasks.
-  $args = array();
-  $includes = array();
+  $args = [];
+  $includes = [];
 
   if (variable_get('tripal_admin_notification_creation_during_cron', TRUE)) {
     $modules = module_implements('tripal_cron_notification');
     foreach ($modules as $module) {
       $function = $module . '_tripal_cron_notification';
-      tripal_add_job(
-        "Cron: Checking for '$module' notifications.",    // Job Name
-        'tripal',                                         // Module Name
-        $function,                                        // Callback
-        $args,                                            // Arguements
-        1,                                                // User UID
-        1,                                                // Priority (1-10)
-        $includes,                                        // Includes
-        TRUE                                              // Ignore Duplicates
-      );
+      tripal_add_job("Cron: Checking for '$module' notifications.", 'tripal',                                         // Module Name
+        $function, $args, 1, 1, $includes, TRUE);
     }
   }
 
   // Check for expired collections.
-  tripal_add_job(
-    'Cron: Checking expired collections',             // Job Name
-    'tripal',                                         // Module Name
-    'tripal_expire_collections',                      // Callback
-    $args,                                            // Arguements
-    1,                                                // User UID
-    1,                                                // Priority (1-10)
-    $includes,                                        // Includes
-    TRUE                                              // Ignore Duplicates
-  );
+  tripal_add_job('Cron: Checking expired collections', 'tripal',
+    'tripal_expire_collections', $args, 1, 1, $includes, TRUE);
+  
+  tripal_add_job('Cron: Checking expired files', 'tripal',
+    'tripal_expire_files', $args, 1, 1, $includes, TRUE);
+
 }
 
 /**
@@ -1310,44 +1520,6 @@ function tripal_html5_file_value($element, $input = FALSE, &$form_state) {
   }
 }
 
-
-/**
- * Implements hook_handle_uploaded_file().
- */
-function tripal_handle_uploaded_file($filename, $filepath, $type) {
-
-  global $user;
-
-  // Split the type into a node ID and form_key
-  list($id, $form_key) = explode('-', $type);
-
-
-  // See if this file is already managed then add another entry fin the
-  // usage table.
-  $fid = db_select('file_managed', 'fm')
-    ->fields('fm', array('fid'))
-    ->condition('uri', $filepath)
-    ->execute()
-    ->fetchField();
-
-  // Create a file object.
-  if (!$fid) {
-    $file = new stdClass();
-    $file->uri = $filepath;
-    $file->filename = $filename;
-    $file->filemime = file_get_mimetype($filepath);
-    $file->uid = $user->uid;
-    $file->status = FILE_STATUS_PERMANENT;
-    $file = file_save($file);
-    $fid = $file->fid;
-  }
-
-  $file = file_load($fid);
-  file_usage_add($file, 'tripal', $form_key, $id);
-  return $fid;
-
-}
-
 /**
  * Implements hook_field_display_alter().
  *

+ 45 - 0
tripal/tripal_views_query.inc

@@ -132,6 +132,42 @@ class tripal_views_query extends views_plugin_query {
       $this->cquery->fieldCondition($field_name, $element_name, $value, $operator);
     }
   }
+  
+  /**
+   * Add's a where exression clause to a query.
+   * 
+   * @param $group
+   *   The WHERE group to add these to; groups are used to create AND/OR
+   *   sections. Groups cannot be nested. Use 0 as the default group. If the
+   *   group does not yet exist it will be created as an AND group.
+   * @param $snippet
+   *   The snippet to check. This can be either a column or a complex 
+   *   expression like "UPPER(table.field) = 'value'".
+   * @param $args
+   *   An associative array of arguments.
+   */
+  public function add_where_expression($group, $snippet, $args = array()) {
+    
+    // Ensure all variants of 0 are actually 0. Thus '', 0 and NULL are all
+    // the default group.
+    if (empty($group)) {
+      $group = 0;
+    }
+    
+    // TODO: this function needs to be adjusted to pull out the element from
+    // snippet (see the code for the add_where function above for an example.
+    // for now this function will not properly work.
+    
+    // Check for a group.
+    if (!isset($this->where[$group])) {
+      $this->set_where_group('AND', $group);
+    }
+    $this->where[$group]['conditions'][] = array(
+      'field' => $snippet,
+      'value' => $args,
+      'operator' => 'formula',
+    );
+  }
 
   /**
    * Overrides add_orderby().
@@ -326,4 +362,13 @@ class tripal_views_query extends views_plugin_query {
     $view->execute_time = microtime(TRUE) - $start;
   }
 
+  /**
+   * Provides a unique placeholders for handlers.
+   */
+  public function placeholder() {
+    // TODO: this function doesn't currently work. It is used by the
+    // words, all words, shorter than, longer than filters, but those
+    // are currently commented out.
+    //return $this->query->placeholder($this->options['table'] . '_' . $this->options['field']);
+  }
 }

+ 30 - 24
tripal/views_handlers/tripal_views_handler_filter_string.inc

@@ -36,18 +36,20 @@ class tripal_views_handler_filter_string extends tripal_views_handler_filter {
         'method' => 'op_contains',
         'values' => 1,
       ),
-      'word' => array(
-        'title' => t('Contains any word'),
-        'short' => t('has word'),
-        'method' => 'op_word',
-        'values' => 1,
-      ),
-      'allwords' => array(
-        'title' => t('Contains all words'),
-        'short' => t('has all'),
-        'method' => 'op_word',
-        'values' => 1,
-      ),
+      // TODO: These two filters are a bit problematic with fields.
+      // The require a tripal_views_query::placeholder() function
+//       'word' => array(
+//         'title' => t('Contains any word'),
+//         'short' => t('has word'),
+//         'method' => 'op_word',
+//         'values' => 1,
+//       ),
+//       'allwords' => array(
+//         'title' => t('Contains all words'),
+//         'short' => t('has all'),
+//         'method' => 'op_word',
+//         'values' => 1,
+//       ),
       'starts' => array(
         'title' => t('Starts with'),
         'short' => t('begins'),
@@ -78,18 +80,22 @@ class tripal_views_handler_filter_string extends tripal_views_handler_filter {
         'method' => 'op_not',
         'values' => 1,
       ),
-      'shorterthan' => array(
-        'title' => t('Length is shorter than'),
-        'short' => t('shorter than'),
-        'method' => 'op_shorter',
-        'values' => 1,
-      ),
-      'longerthan' => array(
-        'title' => t('Length is longer than'),
-        'short' => t('longer than'),
-        'method' => 'op_longer',
-        'values' => 1,
-      ),
+      // TODO: These two filters are a bit problematic with fields.
+      // The require a tripal_views_query::add_where_expression function
+      // that can properly separate the field out of the "snippet". For now
+      // we'll just comment them out.
+//       'shorterthan' => array(
+//         'title' => t('Length is shorter than'),
+//         'short' => t('shorter than'),
+//         'method' => 'op_shorter',
+//         'values' => 1,
+//       ),
+//       'longerthan' => array(
+//         'title' => t('Length is longer than'),
+//         'short' => t('longer than'),
+//         'method' => 'op_longer',
+//         'values' => 1,
+//       ),
     );
     // if the definition allows for the empty operator, add it.
     if (!empty($this->definition['allow empty'])) {

+ 18 - 11
tripal_bulk_loader/api/tripal_bulk_loader.api.templates.inc

@@ -10,7 +10,8 @@
  * @defgroup tripal_bulk_loader_api Bulk Loader
  * @ingroup tripal_api
  * @{
- * All functions in this file provide an API to administrative management of bulk loader templates
+ * All functions in this file provide an API to administrative management of 
+ * bulk loader templates.
  * @}
  */
 
@@ -21,10 +22,10 @@
  *   The type of validation. Can be either 'insert' or 'update'.
  * @param $options
  *   An array of key/value pairs containing the following keys:
- *     'template_name':   The name of the template.
- *     'template_array':  The JSON array representing the template.
- *   Optional:
- *     'strict':          If set then only JSON formatted templates are allowed.
+ *     template_name: The name of the template.
+ *     template_array: The JSON array representing the template.
+ *     Optional:
+ *      strict: If set then only JSON formatted templates are allowed.
  * @param $errors
  *   An empty array where validation error messages will be set. The keys
  *   of the array will be name of the field from the options array and the
@@ -42,6 +43,7 @@
  *   the option and the value being the error message.  If validation
  *   is successful then TRUE is returned.
  *
+ *  @ingroup tripal_bulk_loader_api
  */
 function tripal_validate_bulk_loader_template($val_type, &$options, &$errors, &$warnings = array()) {
   $template_array = trim($options['template_array']);
@@ -105,7 +107,7 @@ function tripal_validate_bulk_loader_template($val_type, &$options, &$errors, &$
 /**
  * Inserts a bulk loader template record.
  *
- * This function validates the options passed prior to insertion of the record,
+ * This function validates the options passed prior to insertion of the record.
  *
  * @param $options
  *   An array of key/value pairs containing the following keys:
@@ -125,6 +127,8 @@ function tripal_validate_bulk_loader_template($val_type, &$options, &$errors, &$
  *   value is the error message.
  * @return
  *   TRUE for success and FALSE for failure.
+ * 
+ *  @ingroup tripal_bulk_loader_api
  */
 function tripal_insert_bulk_loader_template($options, &$errors, &$warnings) {
 
@@ -178,20 +182,23 @@ function tripal_insert_bulk_loader_template($options, &$errors, &$warnings) {
 }
 
 /**
- * Meant to be called from a form_validate function to ensure a newly added bulk loader record
- * name is unique and not empty.
+ * Meant to be called from a form_validate function to ensure a newly added bulk 
+ * loader record name is unique and not empty.
  *
  * @param $new_record_name
  *   The record name to check for uniqueness
  * @param $template_id
  *   The template_id of the template to add the record to
  * @param $template_array
- *   The array describing the template. Optional -will be loaded using template_id if not provided
+ *   The array describing the template. Optional -will be loaded using 
+ *   template_id if not provided
  * @param $current_priority
- *   The priority of the already existing record -checks that the name only occurs on this particular record
+ *   The priority of the already existing record -checks that the name only 
+ *   occurs on this particular record
  *
  * @return
- *   TRUE if the record name is not empty and not already in the template_array; FALSE otherwise
+ *   TRUE if the record name is not empty and not already in the template_array; 
+ *   FALSE otherwise
  *
  * @ingroup tripal_bulk_loader_api
  */

+ 10 - 10
tripal_chado/api/generate_chado_schema_file.php

@@ -11,16 +11,16 @@
  *
  * @code
  *'chado' => array(
-    'default' => array(
-      'database' => 'd7x_t2x_c13',
-      'username' => 'chado',
-      'password' => 'testing123',
-      'host' => 'localhost',
-      'port' => '',
-      'driver' => 'pgsql',
-      'prefix' => '',
-    ),
-  ),
+ *   'default' => array(
+ *     'database' => 'd7x_t2x_c13',
+ *     'username' => 'chado',
+ *     'password' => 'testing123',
+ *     'host' => 'localhost',
+ *     'port' => '',
+ *     'driver' => 'pgsql',
+ *     'prefix' => '',
+ *   ),
+ * ),
  * @endcode
  *
  * This script requires a single argument (-v) which is the Chado version.

+ 37 - 32
tripal_chado/api/modules/tripal_chado.analysis.api.inc

@@ -1,7 +1,7 @@
 <?php
 /**
  * @file
- * Provides functions for managing analysis'.
+ * Provides API functions specificially for managing analysis records in Chado.
  *
  * @ingroup tripal_chado
  */
@@ -10,45 +10,47 @@
  * @defgroup tripal_analysis_api Chado Analysis
  * @ingroup tripal_chado_api
  * @{
-
+ * Provides API functions for working with analysis records in Chado that
+ * go beyond the generic Chado API functions.
  * @}
  */
 
 
 /**
- * Retrieves an chado analysis variable
+ * Retrieves a chado analysis variable.
  *
  * @param $itentifier
- *   an array with the key stating what the identifier is. Supported keys (only on of the
- *   following unique keys is required):
- *    - analysis_id: the chado analysis.analysis_id primary key
- *    - nid: the drupal node.nid primary key
+ *   an array with the key stating what the identifier is. Supported keys 
+ *   (only on of the following unique keys is required):
+ *    - analysis_id: the chado analysis.analysis_id primary key.
+ *    - nid: the drupal node.nid primary key.
  *   There are also some specially handled keys. They are:
- *    - property: An array/object describing the property to select records for. It
- *      should at least have either a type_name (if unique across cvs) or type_id. Other
- *      supported keys include: cv_id/cv_name (of the type), value and rank
+ *    - property: An array/object describing the property to select records for. 
+ *      It should at least have either a type_name (if unique across cvs) or 
+ *      type_id. Other supported keys include: cv_id/cv_name (of the type), 
+ *      value and rank.
+ *   NOTE: the $identifier parameter can be any array similar to $values 
+ *   passed into chado_select_record(). It should fully specify the stock record 
+ *   to be returned.
  * @param $options
  *   An array of options. Supported keys include:
- *     - Any keys supported by chado_generate_var(). See that function definition for
- *       additional details.
- *
- * NOTE: the $identifier parameter can really be any array similar to $values passed into
- *   chado_select_record(). It should fully specify the stock record to be returned.
+ *     - Any keys supported by chado_generate_var(). See that function 
+ *       definition for additional details.
  *
  * @return
  *   the analysis node matching the passed in identifier
  *
  * @ingroup tripal_analysis_api
  */
-function tripal_get_analysis($identifier, $options) {
+function chado_get_analysis($identifier, $options) {
 
   // Set Defaults
   if (!isset($options['include_fk'])) {
-    // Tells chado_generate_var not to follow any foreign keys
+    // Tells chado_generate_var not to follow any foreign keys.
     $options['include_fk'] = array();
   }
 
-  // Error Checking of parameters
+  // Error Checking of parameters.
   if (!is_array($identifiers)) {
     tripal_report_error(
       'tripal_stock_api',
@@ -73,7 +75,7 @@ function tripal_get_analysis($identifier, $options) {
     );
   }
 
-  // If one of the identifiers is property then use chado_get_record_with_property()
+  // If one of the identifiers is property then use chado_get_record_with_property().
   if (isset($identifiers['property'])) {
     $property = $identifiers['property'];
     unset($identifiers['property']);
@@ -83,7 +85,8 @@ function tripal_get_analysis($identifier, $options) {
     );
   }
 
-  // Else we have a simple case and we can just use chado_generate_var to get the analysis
+  // Else we have a simple case and we can just use chado_generate_var to get 
+  // the analysis.
   else {
 
     // Try to get the analysis
@@ -94,24 +97,25 @@ function tripal_get_analysis($identifier, $options) {
     );
   }
 
-  // Ensure the analysis is singular. If it's an array then it is not singular
+  // Ensure the analysis is singular. If it's an array then it is not singular.
   if (is_array($analysis)) {
     tripal_report_error(
       'tripal_analysis_api',
       TRIPAL_ERROR,
-      "tripal_get_analysis: The identifiers you passed in were not unique. You passed in %identifier.",
+      "chado_get_analysis: The identifiers you passed in were not unique. You passed in %identifier.",
       array(
         '%identifier'=> print_r($identifiers, TRUE)
       )
     );
   }
 
-  // Report an error if $analysis is FALSE since then chado_generate_var has failed
+  // Report an error if $analysis is FALSE since then chado_generate_var has 
+  // failed.
   elseif ($analysis === FALSE) {
     tripal_report_error(
       'tripal_analysis_api',
       TRIPAL_ERROR,
-      "tripal_get_analysis: chado_generate_var() failed to return a analysis based on the identifiers
+      "chado_get_analysis: chado_generate_var() failed to return a analysis based on the identifiers
         you passed in. You should check that your identifiers are correct, as well as, look
         for a chado_generate_var error for additional clues. You passed in %identifier.",
       array(
@@ -126,18 +130,19 @@ function tripal_get_analysis($identifier, $options) {
   }
 }
 /**
- * Returns a list of analyses that are currently synced with Drupal to use in select lists
+ * Returns a list of analyses that are currently synced with Drupal to use in 
+ * select lists.
  *
  * @param $syncd_only
- *   Whether or not to return all chado analyses or just those sync'd with drupal. Defaults
- *   to TRUE (only sync'd analyses)
+ *   Whether or not to return all chado analyses or just those sync'd with 
+ *   drupal. Defaults to TRUE (only sync'd analyses).
  * @return
- *   An array of analyses sync'd with Drupal where each value is the analysis scientific
- *   name and the keys are analysis_id's
+ *   An array of analyses sync'd with Drupal where each value is the analysis 
+ *   scientific name and the keys are analysis_id's.
  *
  * @ingroup tripal_analysis_api
  */
-function tripal_get_analysis_select_options($syncd_only = TRUE) {
+function chado_get_analysis_select_options($syncd_only = TRUE) {
   $analysis_list = array();
   $analysis_list[] = 'Select an analysis';
 
@@ -150,7 +155,7 @@ function tripal_get_analysis_select_options($syncd_only = TRUE) {
     ";
     $analyses = chado_query($sql);
 
-    // iterate through the analyses and build an array of those that are synced
+    // iterate through the analyses and build an array of those that are synced.
     foreach ($analyses as $analysis) {
       $analysis_list[$analysis->analysis_id] = $analysis->name;
     }
@@ -160,7 +165,7 @@ function tripal_get_analysis_select_options($syncd_only = TRUE) {
     $csql =  "SELECT * FROM {analysis} ORDER BY name";
     $analyses = chado_query($csql);
 
-    // iterate through the analyses and build an array of those that are synced
+    // iterate through the analyses and build an array of those that are synced.
     foreach ($analyses as $analysis) {
       $analysis_list[$analysis->analysis_id] = $analysis->name;
     }

+ 18 - 15
tripal_chado/api/modules/tripal_chado.contact.api.inc

@@ -1,7 +1,7 @@
 <?php
 /**
  * @file
- * Functions to interact with contacts.
+ * Provides API functions specificially for managing contact records in Chado.
  *
  * @ingroup tripal_chado
  */
@@ -10,29 +10,32 @@
  * @defgroup tripal_contact_api Chado Contact
  * @ingroup tripal_chado_api
  * @{
+ * Provides API functions for working with chado records in Chado that
+ * go beyond the generic Chado API functions.
  * @}
  */
 
 /**
- * Adds a contact to the Chado contact table
+ * Adds a contact to the Chado contact table.
  *
  * @param $values
  *   An array of values to be inserted. Valid keys include:
- *   - name: The name of the contact
- *   - description: Text describing the contact
- *   - type_name: The type of contact.  Must be a term in the tripal_contact vocabulary
- *   - properties: An associative array containing a list of key value pairs for the properites.
- *     The key's must be valid terms in the tripal_contact vocabulary (e.g. Affiliation,
- *     Address, etc).
+ *   - name: The name of the contact.
+ *   - description: Text describing the contact.
+ *   - type_name: The type of contact.  Must be a term in the tripal_contact 
+ *     vocabulary.
+ *   - properties: An associative array containing a list of key value pairs for
+ *     the properites. The key's must be valid terms in the tripal_contact 
+ *     vocabulary (e.g. Affiliation, Address, etc).
  *
  * @return
  *   On success, an array is returned containing the fields of the contact
  *   record including the newly added contact_id. On failure, FALSE is
- *   returned
+ *   returned.
  *
  * @ingroup tripal_contact_api
  */
-function tripal_insert_contact($values) {
+function chado_insert_contact($values) {
 
   $name = $values['name'];
   $description = $values['description'];
@@ -45,7 +48,7 @@ function tripal_insert_contact($values) {
   $contact = chado_select_record('contact', array('contact_id'), $values, $options);
 
   if (count($contact) == 0) {
-    $cvterm = tripal_get_cvterm(array(
+    $cvterm = chado_get_cvterm(array(
       'name' => $type,
       'cv_id' => array('name' => 'tripal_contact')
     ));
@@ -115,14 +118,14 @@ function tripal_insert_contact($values) {
  * This function is intended to be used in autocomplete forms for contacts.
  *
  * @param $text
- *   The string to search for
+ *   The string to search for.
  *
  * @return
- *   A json array of terms that begin with the provided string
+ *   A json array of terms that begin with the provided string.
  *
  * @ingroup tripal_contact_api
  */
-function tripal_autocomplete_contact($text) {
+function chado_autocomplete_contact($text) {
   $matches = array();
 
   $sql = "SELECT * FROM {contact} WHERE lower(name) like lower(:name) ";
@@ -140,4 +143,4 @@ function tripal_autocomplete_contact($text) {
     $items[$contact->name] = $contact->name;
   }
   drupal_json_output($items);
-}
+}

+ 199 - 168
tripal_chado/api/modules/tripal_chado.cv.api.inc

@@ -1,9 +1,9 @@
 <?php
 /**
  * @file
- * This module provides a set of functions to simplify working with
- * controlled vocabularies.
- *
+ * Provides API functions specificially for managing controlled vocabulary
+ * records in Chado.  
+ * 
  * @ingroup tripal_chado
  */
 
@@ -11,6 +11,12 @@
  * @defgroup tripal_chado_cv_api Chado CV
  * @ingroup tripal_chado_api
  * @{
+ * Provides API functions specificially for managing controlled vocabulary
+ * records in Chado. Please note that Tripal v3 provides a generic set of 
+ * API functions for working with controlled vocabularies (CVs). This allows for
+ * CVs to be stored using any back-end.  By default CV's continue to be housed
+ * in Chado.  Therefore, if you are working directly with controlled vocabulary
+ * records inside of a Chado-aware module then these functions can be used. 
  * @}
  */
 
@@ -18,39 +24,40 @@
  * Retrieves a chado controlled vocabulary variable
  *
  * @param $identifier
- *   An array with the key stating what the identifier is. Supported keys (only on of the
- *   following unique keys is required):
- *    - cv_id: the chado cv.cv_id primary key
- *    - name: the chado cv.name field (assume unique)
+ *   An array with the key stating what the identifier is. Supported keys (only 
+ *   on of the following unique keys is required):
+ *    - cv_id: the chado cv.cv_id primary key.
+ *    - name: the chado cv.name field (assume unique).
  * @param $options
  *   An array of options. Supported keys include:
- *     - Any keys supported by chado_generate_var(). See that function definition for
- *       additional details.
+ *     - Any keys supported by chado_generate_var(). See that function 
+ *       definition fot additional details.
  *
- * NOTE: the $identifier parameter can really be any array similar to $values passed into
- *   chado_select_record(). It should fully specify the cv record to be returned.
+ * NOTE: the $identifier parameter can really be any array similar to $values 
+ * passed into chado_select_record(). It should fully specify the cv record to 
+ * be returned.
  *
  * @return
- *   If unique values were passed in as an identifier then an object describing the cv
- *   will be returned (will be a chado variable from chado_generate_var()). Otherwise,
- *   FALSE will be returned.
+ *   If unique values were passed in as an identifier then an object describing 
+ *   the cv will be returned (will be a chado variable from 
+ *   chado_generate_var()). Otherwise, FALSE will be returned.
  *
  * @ingroup tripal_chado_cv_api
  */
-function tripal_get_cv($identifiers, $options = array()) {
+function chado_get_cv($identifiers, $options = array()) {
 
-  // Set Defaults
+  // Set Defaults.
   if (!isset($options['include_fk'])) {
-    // Tells chado_generate_var not to follow any foreign keys
+    // Tells chado_generate_var not to follow any foreign keys.
     $options['include_fk'] = array();
   }
 
-  // Error Checking of parameters
+  // Error Checking of parameters.
   if (!is_array($identifiers)) {
     tripal_report_error(
       'tripal_chado_api',
       TRIPAL_ERROR,
-      "tripal_get_cv: The identifier passed in is expected to be an array with the key
+      "chado_get_cv: The identifier passed in is expected to be an array with the key
         matching a column name in the cv table (ie: cv_id or name). You passed in %identifier.",
       array(
         '%identifier'=> print_r($identifiers, TRUE)
@@ -61,7 +68,7 @@ function tripal_get_cv($identifiers, $options = array()) {
     tripal_report_error(
       'tripal_chado_api',
       TRIPAL_ERROR,
-      "tripal_get_cv: You did not pass in anything to identify the cv you want. The identifier
+      "chado_get_cv: You did not pass in anything to identify the cv you want. The identifier
         is expected to be an array with the key matching a column name in the cv table
         (ie: cv_id or name). You passed in %identifier.",
       array(
@@ -70,31 +77,31 @@ function tripal_get_cv($identifiers, $options = array()) {
     );
   }
 
-  // Try to get the cv
+  // Try to get the cv.
   $cv = chado_generate_var(
     'cv',
     $identifiers,
     $options
   );
 
-  // Ensure the cv is singular. If it's an array then it is not singular
+  // Ensure the cv is singular. If it's an array then it is not singular.
   if (is_array($cv)) {
     tripal_report_error(
       'tripal_chado_api',
       TRIPAL_ERROR,
-      "tripal_get_cv: The identifiers you passed in were not unique. You passed in %identifier.",
+      "chado_get_cv: The identifiers you passed in were not unique. You passed in %identifier.",
       array(
         '%identifier'=> print_r($identifiers, TRUE)
       )
     );
   }
 
-  // Report an error if $cv is FALSE since then chado_generate_var has failed
+  // Report an error if $cv is FALSE since then chado_generate_var has failed.
   elseif ($cv === FALSE) {
     tripal_report_error(
       'tripal_chado_api',
       TRIPAL_ERROR,
-      "tripal_get_cv: chado_generate_var() failed to return a cv based on the identifiers
+      "chado_get_cv: chado_generate_var() failed to return a cv based on the identifiers
         you passed in. You should check that your identifiers are correct, as well as, look
         for a chado_generate_var error for additional clues. You passed in %identifier.",
       array(
@@ -111,14 +118,14 @@ function tripal_get_cv($identifiers, $options = array()) {
 
 /**
  * Create an options array to be used in a form element which provides a
- * list of all chado cvs
+ * list of all chado cvs.
  *
  * @return
- *   An array(cv_id => name) for each cv in the chado cv table
+ *   An array(cv_id => name) for each cv in the chado cv table.
  *
  * @ingroup tripal_chado_cv_api
  */
-function tripal_get_cv_select_options() {
+function chado_get_cv_select_options() {
 
   $results = chado_select_record('cv', array('cv_id', 'name'), array(), array('order_by' => array('name' => 'ASC')));
 
@@ -134,7 +141,7 @@ function tripal_get_cv_select_options() {
 }
 
 /**
- * Retrieves a chado controlled vocabulary term variable
+ * Retrieves a chado controlled vocabulary term variable.
  *
  * @param $identifier
  *   An array apropriate for use with the chado_generate_var for uniquely
@@ -146,11 +153,11 @@ function tripal_get_cv_select_options() {
  *      name of the cv.
  *    - synonym: an array with 'name' => the name of the synonym of the cvterm
  *      you want returned; 'cv_id' => the cv_id of the synonym; 'cv_name' =>
- *      the name of the cv of the synonym
+ *      the name of the cv of the synonym.
  *    - property: An array/object describing the property to select records
  *      for. It should at least have either a type_name (if unique across cvs)
  *      or type_id. Other supported keys include: cv_id/cv_name (of the type),
- *      value and rank
+ *      value and rank.
  * @param $options
  *   An array of options. Supported keys include:
  *     - Any keys supported by chado_generate_var(). See that function
@@ -167,32 +174,33 @@ function tripal_get_cv_select_options() {
  *
  * @ingroup tripal_chado_cv_api
  */
-function tripal_get_cvterm($identifiers, $options = array()) {
+function chado_get_cvterm($identifiers, $options = array()) {
 
-  // Set Defaults
+  // Set Defaults.
   if (!isset($options['include_fk'])) {
-    // Tells chado_generate_var to only get the cv
+    // Tells chado_generate_var to only get the cv.
     $options['include_fk'] = array('cv_id' => TRUE);
   }
 
-  // Error Checking of parameters
+  // Error Checking of parameters.
   if (!is_array($identifiers)) {
     tripal_report_error('tripal_cv_api', TRIPAL_ERROR,
-      "tripal_get_cvterm: The identifier passed in is expected to be an array with the key
+      "chado_get_cvterm: The identifier passed in is expected to be an array with the key
         matching a column name in the cvterm table (ie: cvterm_id or name). You passed in %identifier.",
       array('%identifier'=> print_r($identifiers, TRUE))
     );
   }
   elseif (empty($identifiers)) {
     tripal_report_error('tripal_cv_api', TRIPAL_ERROR,
-      "tripal_get_cvterm: You did not pass in anything to identify the cvterm you want. The identifier
+      "chado_get_cvterm: You did not pass in anything to identify the cvterm you want. The identifier
         is expected to be an array with the key matching a column name in the cvterm table
         (ie: cvterm_id or name). You passed in %identifier.",
       array('%identifier'=> print_r($identifiers, TRUE))
     );
   }
 
-  // If synonym was passed in, then process this first before calling chado_generate_var()
+  // If synonym was passed in, then process this first before calling 
+  // chado_generate_var().
   if (isset($identifiers['synonym'])) {
     $synonym = $identifiers['synonym']['name'];
 
@@ -208,7 +216,8 @@ function tripal_get_cvterm($identifiers, $options = array()) {
     );
     $result = chado_select_record('cvtermsynonym', array('cvterm_id'), $values, $options);
 
-    // if the synonym doens't exist or more than one record is returned then return false
+    // if the synonym doens't exist or more than one record is returned then 
+    // return false.
     if (count($result) == 0) {
       return FALSE;
     }
@@ -219,7 +228,7 @@ function tripal_get_cvterm($identifiers, $options = array()) {
     $identifiers = array('cvterm_id' => $result[0]->cvterm_id);
   }
 
-  // If one of the identifiers is property then use chado_get_record_with_property()
+  // If one of the identifiers is property then use chado_get_record_with_property().
   if (isset($identifiers['property'])) {
     $property = $identifiers['property'];
     unset($identifiers['property']);
@@ -241,30 +250,32 @@ function tripal_get_cvterm($identifiers, $options = array()) {
     ));
   }
 
-  // Else we have a simple case and we can just use chado_generate_var to get the cvterm
+  // Else we have a simple case and we can just use chado_generate_var to get 
+  // the cvterm.
   else {
-    // Try to get the cvterm
+    // Try to get the cvterm.
     $cvterm = chado_generate_var('cvterm', $identifiers, $options);
   }
 
-  // Ensure the cvterm is singular. If it's an array then it is not singular
+  // Ensure the cvterm is singular. If it's an array then it is not singular.
   if (is_array($cvterm)) {
     tripal_report_error(
       'tripal_cv_api',
       TRIPAL_ERROR,
-      "tripal_get_cvterm: The identifiers you passed in were not unique. You passed in %identifier.",
+      "chado_get_cvterm: The identifiers you passed in were not unique. You passed in %identifier.",
       array(
         '%identifier'=> print_r($identifiers, TRUE)
       )
     );
   }
 
-  // Report an error if $cvterm is FALSE since then chado_generate_var has failed
+  // Report an error if $cvterm is FALSE since then chado_generate_var has 
+  // failed.
   elseif ($cvterm === FALSE) {
     tripal_report_error(
       'tripal_cv_api',
       TRIPAL_ERROR,
-      "tripal_get_cvterm: chado_generate_var() failed to return a cvterm based on the identifiers
+      "chado_get_cvterm: chado_generate_var() failed to return a cvterm based on the identifiers
         you passed in. You should check that your identifiers are correct, as well as, look
         for a chado_generate_var error for additional clues. You passed in %identifier.",
       array(
@@ -282,10 +293,10 @@ function tripal_get_cvterm($identifiers, $options = array()) {
 
 /**
  * Create an options array to be used in a form element
- *   which provides a list of all chado cvterms
+ *   which provides a list of all chado cvterms.
  *
  * @param $cv_id
- *   The chado cv_id; only cvterms with the supplied cv_id will be returned
+ *   The chado cv_id; only cvterms with the supplied cv_id will be returnedl.
  * @param $rel_type
  *   Set to TRUE if the terms returned should only be relationship types in
  *   the vocabulary.  This is useful for creating drop-downs of terms
@@ -293,11 +304,11 @@ function tripal_get_cvterm($identifiers, $options = array()) {
  *
  * @return
  *   An associative array with the cvterm_id's as keys. The first
- *   element in the array has a key of '0' and a value of 'Select a Type'
+ *   element in the array has a key of '0' and a value of 'Select a Type'.
  *
  * @ingroup tripal_chado_cv_api
  */
-function tripal_get_cvterm_select_options($cv_id, $rel_type = FALSE) {
+function chado_get_cvterm_select_options($cv_id, $rel_type = FALSE) {
   $columns = array('cvterm_id', 'name');
   $values = array('cv_id' => $cv_id);
   if ($rel_type) {
@@ -321,20 +332,20 @@ function tripal_get_cvterm_select_options($cv_id, $rel_type = FALSE) {
  * Updates the cvtermpath table of Chado for the specified CV.
  *
  * @param $cv_id
- *   The chado cv_id;
+ *   The chado cv_id.
  * @param $job_id
  *   This function is intended to be used with the Tripal Jobs API.
  *   When this function is called as a job the $job_id is automatically
  *   passed to this function.
  * @return
- *   TRUE on success FALSE on failure
+ *   TRUE on success FALSE on failure.
  *
  * @ingroup tripal_chado_cv_api
  */
 function tripal_update_cvtermpath_old($cv_id, $job_id = NULL) {
   // TODO: need better error checking in this function
 
-  // first get the controlled vocabulary name:
+  // First get the controlled vocabulary name:
   $sql = "SELECT * FROM {cv} WHERE cv_id = :cv_id";
   $cv = chado_query($sql, array(':cv_id' => $cv_id))->fetchObject();
 
@@ -363,7 +374,7 @@ function tripal_update_cvtermpath_old($cv_id, $job_id = NULL) {
  *
  * Identifies all of the root terms of the controlled vocabulary. These
  * root terms are then processed by calling the
- * tripal_update_cvtermpath_root_loop() function on each one.
+ * _chado_update_cvtermpath_root_loop() function on each one.
  *
  * @param $cvid
  *   The controlled vocabulary ID from the cv table of Chado (i.e. cv.cv_id).
@@ -371,7 +382,7 @@ function tripal_update_cvtermpath_old($cv_id, $job_id = NULL) {
  *
  * @ingroup tripal_chado_cv_api
  */
-function tripal_update_cvtermpath($cv_id, $job_id = NULL){
+function chado_update_cvtermpath($cv_id, $job_id = NULL){
   // TODO: there's a function to determine the current Chado instance.
   // we should use that.
   $prev_db = chado_set_active('chado');
@@ -390,7 +401,7 @@ function tripal_update_cvtermpath($cv_id, $job_id = NULL){
     $roots = [];
 
     foreach ($record as $item){
-      tripal_update_cvtermpath_root_loop($item->cvterm_id, $item->cv_id, $roots);
+      _chado_update_cvtermpath_root_loop($item->cvterm_id, $item->cv_id, $roots);
     }
   }
   catch (Exception $e) {
@@ -416,14 +427,7 @@ function tripal_update_cvtermpath($cv_id, $job_id = NULL){
  *
  * @ingroup tripal_chado_cv_api
  */
-function tripal_update_cvtermpath_root_loop($rootid, $cvid, &$roots) {
-  // Get's the cvterm record for this "root".
-  // $ttype = db_select('cvterm', 'cv')
-  //         ->fields('cv', array('cvterm_id'));
-  // $db_or = db_or();
-  // $db_or->condition('cv.name', "isa", '=');
-  // $db_or->condition('cv.name', "is_a", '=');
-  // $ttype->condition($db_or);
+function _chado_update_cvtermpath_root_loop($rootid, $cvid, &$roots) {
   $ttype = db_query(
     'SELECT cv.cvterm_id 
     FROM cvterm cv
@@ -450,7 +454,7 @@ function tripal_update_cvtermpath_root_loop($rootid, $cvid, &$roots) {
   $matched_rows = [];
   $possible_start_of_loop = [];
   $depth = 0;
-  tripal_update_cvtermpath_loop($rootid, $rootid, $cvid, $result->cvterm_id, $depth,
+  _chado_update_cvtermpath_loop($rootid, $rootid, $cvid, $result->cvterm_id, $depth,
                                 0, $tree_path, FALSE, $matched_rows, $possible_start_of_loop, FALSE);
 
   // Get's the children terms of this "root" term and then recursively calls
@@ -463,7 +467,7 @@ function tripal_update_cvtermpath_root_loop($rootid, $cvid, &$roots) {
     [':rootid' => $rootid]
   );
   while ($cterm_result = $cterm->fetchAssoc()) {
-    tripal_update_cvtermpath_root_loop($cterm_result['subject_id'], $cvid, $roots);
+    _chado_update_cvtermpath_root_loop($cterm_result['subject_id'], $cvid, $roots);
   }
 }
 
@@ -481,7 +485,7 @@ function tripal_update_cvtermpath_root_loop($rootid, $cvid, &$roots) {
  * @param $depth
  *   The depth of the recursion.
  * @param $increment_of_depth.
- *   An integer ??
+ *   An integer tailing the number of children that have been walked down.
  * @param $tree_path.
  *   The array of every term between the current child and the origin. Each
  *   element in the array is an associative array with the keys:
@@ -494,8 +498,8 @@ function tripal_update_cvtermpath_root_loop($rootid, $cvid, &$roots) {
  *    An array of rows that are currently in the cvtermpath table that match the
  *    build_id of the current term trying to be written to the table
  * @param $possible_start_of_ loop
- *    The array of the possible loop item between the current child and the origin.
- *    Each element in the array is an associative array with the keys:
+ *    The array of the possible loop item between the current child and the 
+ *    origin. Each element in the array is an associative array with the keys:
  *     - cvid : $cv_id
  *     - subject_id:
  *     - child_id : $child_id,
@@ -503,9 +507,11 @@ function tripal_update_cvtermpath_root_loop($rootid, $cvid, &$roots) {
  *     - depth : $depth,
  * @param $no_loop_skip_test
  *     A boolean used when the possible loop has been ruled out as a loop.
- * @return multitype:
+ * 
+ * 
+ * @ingroup tripal_chado_cv_api
  */
-function tripal_update_cvtermpath_loop(
+function _chado_update_cvtermpath_loop(
   $origin,
   $child_id,
   $cv_id,
@@ -551,7 +557,7 @@ function tripal_update_cvtermpath_loop(
         // and confirmed that this is a loop.
         $possible_loop == FALSE;
         $matched_rows = [];
-        tripal_update_cvtermpath_loop_increment($origin, $child_id, $cv_id,
+        _chado_update_cvtermpath_loop_increment($origin, $child_id, $cv_id,
         $type_id, $depth + 1, $increment_of_depth, $tree_path, $possible_loop,
         $new_match_rows, $possible_start_of_loop, $no_loop_skip_test);
 
@@ -588,7 +594,7 @@ function tripal_update_cvtermpath_loop(
           // and confirmed that this is a loop.
           $possible_loop == FALSE;
           $matched_rows = [];
-          tripal_update_cvtermpath_loop_increment($origin, $child_id, $cv_id,
+          _chado_update_cvtermpath_loop_increment($origin, $child_id, $cv_id,
           $type_id, $depth + 1, $increment_of_depth, $tree_path, $possible_loop,
           $new_match_rows, $possible_start_of_loop, $no_loop_skip_test);
 
@@ -603,7 +609,7 @@ function tripal_update_cvtermpath_loop(
       $no_loop_skip_test = TRUE;
       // There is not loop so pass it back the possible_start_of_loop info
       // and a flag telling it to skip the loop check.
-      tripal_update_cvtermpath_loop_increment($possible_start_of_loop->subject_id,
+      _chado_update_cvtermpath_loop_increment($possible_start_of_loop->subject_id,
       $possible_start_of_loop->child_id, $possible_start_of_loop->cvid,
       $possible_start_of_loop->type_id, $possible_start_of_loop->depth,
       $increment_of_depth, $tree_path, $possible_loop, $matched_rows,
@@ -611,13 +617,13 @@ function tripal_update_cvtermpath_loop(
     }
     // If $match_rows is not empty we need to keep trying rows.
     else {
-      tripal_update_cvtermpath_loop_increment($origin, $child_id, $cv_id,
+      _chado_update_cvtermpath_loop_increment($origin, $child_id, $cv_id,
       $type_id, $depth + 1, $increment_of_depth, $tree_path, $possible_loop,
       $match_rows, $possible_start_of_loop, $no_loop_skip_test);
     }
   }
   elseif ($possible_loop === FALSE) {
-    tripal_update_cvtermpath_loop_increment($origin, $child_id, $cv_id,
+    _chado_update_cvtermpath_loop_increment($origin, $child_id, $cv_id,
     $type_id, $depth + 1, $increment_of_depth, $tree_path, $possible_loop,
     $matched_rows, $possible_start_of_loop, $no_loop_skip_test);
   }
@@ -637,7 +643,7 @@ function tripal_update_cvtermpath_loop(
  * @param $depth
  *   The depth of the recursion.
  * @param $increment_of_depth.
- *   An integer ??
+ *   An integer.
  * @param $tree_path.
  *   The array of every term between the current child and the origin. Each
  *   element in the array is an associative array with the keys:
@@ -659,9 +665,12 @@ function tripal_update_cvtermpath_loop(
  *     - depth : $depth,
  * @param $no_loop_skip_test
  *     A boolean used when the possible loop has been ruled out as a loop.
- * @return multitype:
+ * @return multitype: Either a number that represents the row count of existing 
+ * rows that already match these specification or a Boolean false.
+ * 
+ * @ingroup tripal_chado_cv_api
  */
-function tripal_update_cvtermpath_loop_increment(
+function _chado_update_cvtermpath_loop_increment(
   $origin,
   $child_id,
   $cv_id,
@@ -701,17 +710,19 @@ function tripal_update_cvtermpath_loop_increment(
     $term_id = $origin . '|' . $child_id . '|' . $cv_id . '|' . $type_id;
 
     if ($no_loop_skip_test === FALSE) {
-      // If the increment of depth is 0 then it's the first time and we need to skip
-      // the test so we can build the tree_path which will be tested against.
+      // If the increment of depth is 0 then it's the first time and we need to 
+      // skip the test so we can build the tree_path which will be tested against.
       if ($increment_of_depth != 0) {
         // Search the $tree_path for the new $child_id in the build_id column.
         foreach ($tree_path as $parent) {
           // If this child is the same as a parent term that has already been
           // processed then we have a potential loop.
           if ($parent['build_id'] == $term_id) {
-            // Tell the function this is a possible loop and to stop writing to the table.
+            // Tell the function this is a possible loop and to stop writing to 
+            // the table.
             $possible_loop = TRUE;
-            // Find all the results in the table that might be the start of the loop.
+            // Find all the results in the table that might be the start of the 
+            // loop.
             $matching_rows = db_query(
               ' SELECT *
                 FROM cvtermpath
@@ -739,21 +750,30 @@ function tripal_update_cvtermpath_loop_increment(
         }
       }
 
-      $query = db_insert('cvtermpath')
-        ->fields([
-          'object_id' => $origin,
-          'subject_id' => $child_id,
-          'cv_id' => $cv_id,
-          'type_id' => $type_id,
-          'pathdistance' => $depth,
-        ]);
-
-      try {
-        $rows = $query->execute();
-      } catch (Exception $e) {
-        $error = $e->getMessage();
-        tripal_report_error('tripal_chado', TRIPAL_ERROR, "Could not fill cvtermpath term: @error", array('@error' => $error));
-        return false;
+      $find_query = db_select('chado.cvtermpath', 'CVTP');
+      $find_query->fields('CVTP', ['subject_id']);
+      $find_query->condition('object_id', $origin);
+      $find_query->condition('subject_id', $child_id);
+      $find_query->condition('type_id', $type_id);
+      $find_query->condition('pathdistance', $depth);
+      $exists = $find_query->execute()->fetchObject();
+
+      if(!$exists){
+        $query = db_insert('cvtermpath')
+          ->fields([
+            'object_id' => $origin,
+            'subject_id' => $child_id,
+            'cv_id' => $cv_id,
+            'type_id' => $type_id,
+            'pathdistance' => $depth,
+          ]);
+        try {
+          $rows = $query->execute();
+        } catch (Exception $e) {
+          $error = $e->getMessage();
+          tripal_report_error('tripal_chado', TRIPAL_ERROR, "Could not fill cvtermpath term: @error", array('@error' => $error));
+          return false;
+        }
       }
 
       // Then add that new entry to the $tree_path.
@@ -767,7 +787,7 @@ function tripal_update_cvtermpath_loop_increment(
     $possible_start_of_loop = [];
 
     // Get all of the relationships of this child term, and recursively
-    // call the tripal_update_cvtermpath_loop_increment() function to continue
+    // call the _chado_update_cvtermpath_loop_increment() function to continue
     // descending down the tree.
     $query = db_select('cvterm_relationship', 'cvtr')
       ->fields('cvtr')
@@ -777,7 +797,7 @@ function tripal_update_cvtermpath_loop_increment(
 
     foreach ($cterm_relationships as $item) {
       $increment_of_depth++;
-      tripal_update_cvtermpath_loop_increment($origin, $item->subject_id, $cv_id,
+      _chado_update_cvtermpath_loop_increment($origin, $item->subject_id, $cv_id,
         $item->type_id, $depth + 1, $increment_of_depth, $tree_path, $possible_loop,
         $matched_rows, $possible_start_of_loop, $no_loop_skip_test);
     }
@@ -789,7 +809,7 @@ function tripal_update_cvtermpath_loop_increment(
   }
   elseif ($possible_loop === TRUE) {
     // Get all of the relationships of this child term, and recursively
-    // call the tripal_update_cvtermpath_loop() function to continue
+    // call the _chado_update_cvtermpath_loop() function to continue
     // descending down the tree.
     $query = db_select('cvterm_relationship', 'cvtr')
       ->fields('cvtr')
@@ -798,15 +818,17 @@ function tripal_update_cvtermpath_loop_increment(
     $cterm_relationships = $query->fetchAll();
     foreach ($cterm_relationships as $item) {
       $increment_of_depth++;
-      tripal_update_cvtermpath_loop($origin, $item->subject_id, $cv_id,
+      _chado_update_cvtermpath_loop($origin, $item->subject_id, $cv_id,
         $item->type_id, $depth + 1, $increment_of_depth, $tree_path, $possible_loop,
         $matched_rows, $possible_start_of_loop, $no_loop_skip_test);
     }
   }
+
+
 }
 
 /**
- * Adds a controlled vocabular to the CV table of Chado.
+ * Adds a controlled vocabulary to the CV table of Chado.
  *
  * @param $name
  *   The name of the controlled vocabulary. These are typically all lower case
@@ -817,21 +839,21 @@ function tripal_update_cvtermpath_loop_increment(
  * @return
  *   An object populated with fields from the newly added database.
  *
- * @ingroup tripal_chado_api
+ * @ingroup tripal_chado_cv_api
  */
-function tripal_insert_cv($name, $definition) {
+function chado_insert_cv($name, $definition) {
 
-  // insert/update values
+  // Insert/update values.
   $ins_values = array(
     'name'       => $name,
     'definition' => $definition
   );
 
-  // see if the CV default exists already in the database
+  // See if the CV default exists already in the database.
   $sel_values = array('name' => $name);
   $results = chado_select_record('cv', array('*'), $sel_values);
 
-  // if it does not exists then add it
+  // If it does not exists then add it.
   if (count($results) == 0) {
     $success = chado_insert_record('cv', $ins_values);
     if (!$success) {
@@ -840,7 +862,7 @@ function tripal_insert_cv($name, $definition) {
     }
     $results = chado_select_record('cv', array('*'), $sel_values);
   }
-  // if it already exists then do an update
+  // If it already exists then do an update.
   else {
     $success = chado_update_record('cv', $sel_values, $ins_values);
     if (!$success) {
@@ -850,7 +872,7 @@ function tripal_insert_cv($name, $definition) {
     $results = chado_select_record('cv', array('*'), $sel_values);
   }
 
-  // return the cv object
+  // Return the cv object.
   return $results[0];
 }
 
@@ -875,13 +897,13 @@ function tripal_insert_cv($name, $definition) {
  *      <DB> is the name of the database to which the cvterm belongs and the
  *      <ACCESSION> is the term's accession number in the database.
  *    - name: the name of the term. usually meant to be human-readable.
- *    - is_obsolete: is present and set to 1 if the term is defunct
- *    - definition: the definition of the term
+ *    - is_obsolete: is present and set to 1 if the term is defunct.
+ *    - definition: the definition of the term.
  *    - cv_name: The CV name to which the term belongs.  If this arugment is
  *        null or not provided then the function tries to find a record in the
  *        CV table with the same name provided in the $term[namespace].  If
  *        this field is provided then it overrides what the value in
- *        $term[namespace]
+ *        $term[namespace].
  *    - is_relationship: If this term is a relationship term then this value
  *        should be 1.
  *    - db_name: In some cases the database name will not be part of the
@@ -896,11 +918,11 @@ function tripal_insert_cv($name, $definition) {
  * @return
  *   A cvterm object
  *
- * @ingroup tripal_chado_api
+ * @ingroup tripal_chado_cv_api
  */
-function tripal_insert_cvterm($term, $options = array()) {
+function chado_insert_cvterm($term, $options = array()) {
 
-  // get the term properties
+  // Get the term properties.
   $id = (isset($term['id'])) ? $term['id'] : '';
   $name = '';
   $cvname = '';
@@ -908,7 +930,7 @@ function tripal_insert_cvterm($term, $options = array()) {
   $is_obsolete = 0;
   $accession = '';
 
-  // Set Defaults
+  // Set Defaults.
   if (isset($term['cv_name'])) {
     $cvname = $term['cv_name'];
   }
@@ -916,7 +938,7 @@ function tripal_insert_cvterm($term, $options = array()) {
     $cvname = 'local';
   }
   // Namespace is deprecated but must be supported for backwards
-  // compatability
+  // compatability.
   if (array_key_exists('namespace', $term)) {
     $cvname = $term['namespace'];
   }
@@ -991,10 +1013,10 @@ function tripal_insert_cvterm($term, $options = array()) {
     return 0;
   }
 
-  // Make sure the CV name exists
-  $cv = tripal_get_cv(array('name' => $cvname));
+  // Make sure the CV name exists.
+  $cv = chado_get_cv(array('name' => $cvname));
   if (!$cv) {
-    $cv = tripal_insert_cv($cvname, '');
+    $cv = chado_insert_cv($cvname, '');
   }
   if (!$cv) {
     tripal_report_error('tripal_cv', TRIPAL_WARNING, "Cannot find namespace '$cvname' when adding/updating $id", NULL);
@@ -1017,9 +1039,9 @@ function tripal_insert_cvterm($term, $options = array()) {
 
   // Add the database. The function will just return the DB object if the
   // database already exists.
-  $db = tripal_get_db(array('name' => $dbname));
+  $db = chado_get_db(array('name' => $dbname));
   if (!$db) {
-    $db = tripal_insert_db(array('name' => $dbname));
+    $db = chado_insert_db(array('name' => $dbname));
   }
   if (!$db) {
     tripal_report_error('tripal_cv', TRIPAL_WARNING, "Cannot find database '$dbname' in Chado.", NULL);
@@ -1098,7 +1120,7 @@ function tripal_insert_cvterm($term, $options = array()) {
     if ($dbxref->accession != $accession) {
 
       // Get/add the dbxref for his term.
-      $dbxref_new =  tripal_insert_dbxref(array(
+      $dbxref_new = chado_insert_dbxref(array(
         'db_id' => $db->db_id,
         'accession' => $accession
       ));
@@ -1128,7 +1150,7 @@ function tripal_insert_cvterm($term, $options = array()) {
           return 0;
         }
       }
-      // get the original cvterm with the same name and return that.
+      // Get the original cvterm with the same name and return that.
       $result = chado_query($cvtermsql, array(':accession' => $dbxref->accession, ':name' => $dbname));
       $cvterm = $result->fetchObject();
       return $cvterm;
@@ -1137,13 +1159,13 @@ function tripal_insert_cvterm($term, $options = array()) {
     // We can now perform and updated if we need to.
   }
 
-  // get the CVterm record
+  // Get the CVterm record.
   $result = chado_query($cvtermsql, array(':accession' => $accession, ':name' => $dbname));
   $cvterm = $result->fetchObject();
   if (!$cvterm) {
 
     // Check to see if the dbxref exists if not, add it.
-    $dbxref =  tripal_insert_dbxref(array(
+    $dbxref = chado_insert_dbxref(array(
       'db_id' => $db->db_id,
       'accession' => $accession
     ));
@@ -1203,7 +1225,8 @@ function tripal_insert_cvterm($term, $options = array()) {
       return 0;
     }
 
-    // Second, check that the dbxref has not changed and if it has then update it.
+    // Second, check that the dbxref has not changed and if it has then update 
+    // it.
     $checksql = "
       SELECT cvterm_id
       FROM {cvterm} CVT
@@ -1215,8 +1238,8 @@ function tripal_insert_cvterm($term, $options = array()) {
     $check = chado_query($checksql, array(':accession' => $accession, ':dbname' => $dbname, ':term' => $name, ':cvname' => $cvname))->fetchObject();
     if (!$check) {
 
-      // check to see if the dbxref exists if not, add it.
-      $dbxref =  tripal_insert_dbxref(array(
+      // Check to see if the dbxref exists if not, add it.
+      $dbxref = chado_insert_dbxref(array(
         'db_id' => $db->db_id,
         'accession' => $accession
       ));
@@ -1242,9 +1265,9 @@ function tripal_insert_cvterm($term, $options = array()) {
     $cvterm = $result->fetchObject();
   }
   else {
-    // do nothing, we have the cvterm but we don't want to update
+    // Do nothing, we have the cvterm but we don't want to update.
   }
-  // return the cvterm
+  // Return the cvterm.
   return $cvterm;
 }
 
@@ -1252,6 +1275,8 @@ function tripal_insert_cvterm($term, $options = array()) {
 /**
  * TODO: deprecate this function
  *
+ * Avoid using this function as it will be deprecated in future releases.
+ * 
  * This function allows other modules to programatically
  * submit an ontology for loading into Chado.
  *
@@ -1266,7 +1291,7 @@ function tripal_insert_cvterm($term, $options = array()) {
  * @param $obo_id
  *   If the ontology is already loaded into the Tripal tables then
  *   use this argument to specify the unique ID for the ontology
- *   that will be loaded
+ *   that will be loaded.
  * @param $obo_name
  *   If the OBO has not been added before then use this argument
  *   to specify the human readable name of the ontology.
@@ -1280,9 +1305,9 @@ function tripal_insert_cvterm($term, $options = array()) {
  * @return
  *   returns the job_id of the submitted job or FALSE if the job was not added
  *
- * @ingroup tripal_chado_api
+ * @ingroup tripal_chado_cv_api
  */
-function tripal_submit_obo_job($obo) {
+function chado_submit_obo_job($obo) {
   global $user;
 
   // Set Defaults
@@ -1330,17 +1355,17 @@ function tripal_submit_obo_job($obo) {
  * If the OBO name already exists in the table then the path is updated.
  *
  * @param $name
- *   The human readable name of this ontology
+ *   The human readable name of this ontology.
  * @param $path
- *   The file path or URL of the ontology
+ *   The file path or URL of the ontology.
  *
  * @return
- *   Returns the ontology ID
+ *   Returns the ontology ID.
  *
- * @ingroup tripal_chado_api
+ * @ingroup tripal_chado_cv_api
  */
-function tripal_insert_obo($name, $path) {
-  // make sure an OBO with the same name doesn't already exist
+function chado_insert_obo($name, $path) {
+  // Make sure an OBO with the same name doesn't already exist.
   $obo_id = db_select('tripal_cv_obo', 'tco')
     ->fields('tco', array('obo_id'))
     ->condition('name', $name)
@@ -1371,12 +1396,14 @@ function tripal_insert_obo($name, $path) {
  * Retrieves an OBO record.
  *
  * @param $values
- *   An associate array with the following allowed keys: obo_id, name
+ *   An associate array with the following allowed keys: obo_id, name.
  *
  * @return
  *   An instance of an OBO record object.
+ * 
+ * @ingroup tripal_chado_cv_api
  */
-function tripal_get_obo($values) {
+function chado_get_obo($values) {
   $query = db_select('tripal_cv_obo', 'tco')
     ->fields('tco');
 
@@ -1388,20 +1415,21 @@ function tripal_get_obo($values) {
   }
   return $query->execute()->fetchObject();
 }
+
 /**
  * This function is intended to be used in autocomplete forms.
  *
  * This function searches for a matching controlled vobulary name.
  *
  * @param $string
- * The string to search for
+ * The string to search for.
  *
  * @return
- * A json array of terms that begin with the provided string
+ * A json array of terms that begin with the provided string.
  *
- * @ingroup tripal_chado_api
+ * @ingroup tripal_chado_cv_api
  */
-function tripal_autocomplete_cv($string = '') {
+function chado_autocomplete_cv($string = '') {
   $sql = "
     SELECT CV.cv_id, CV.name
     FROM {cv} CV
@@ -1417,21 +1445,22 @@ function tripal_autocomplete_cv($string = '') {
 
   drupal_json_output($items);
 }
+
 /**
  * This function is intended to be used in autocomplete forms
- * for searching for CV terms that begin with the provided string
+ * for searching for CV terms that begin with the provided string.
  *
  * @param $cv_id
- * The CV ID in which to search for the term
+ * The CV ID in which to search for the term.
  * @param $string
- * The string to search for
+ * The string to search for.
  *
  * @return
- * A json array of terms that begin with the provided string
+ * A json array of terms that begin with the provided string.
  *
- * @ingroup tripal_chado_api
+ * @ingroup tripal_chado_cv_api
  */
-function tripal_autocomplete_cvterm($cv_id, $string = '') {
+function chado_autocomplete_cvterm($cv_id, $string = '') {
   if ($cv_id) {
     $sql = "
       SELECT CVT.cvterm_id, CVT.name
@@ -1479,13 +1508,15 @@ function tripal_autocomplete_cvterm($cv_id, $string = '') {
 }
 
 /**
- * Add a record to a cvterm linking table (ie: feature_cvterm)
+ * Add a record to a cvterm linking table (ie: feature_cvterm).
  *
  * @param $basetable
- *   The base table to which the cvterm should be linked/associated. Thus to associate a
- *   cvterm to a feature the basetable=feature and cvterm_id is added to the feature_cvterm table.
+ *   The base table to which the cvterm should be linked/associated. Thus to 
+ *   associate a cvterm to a feature the basetable=feature and cvterm_id is
+ *   added to the feature_cvterm table.
  * @param $record_id
- *   The primary key of the basetable to associate the cvterm with. This should be in integer.
+ *   The primary key of the basetable to associate the cvterm with. This should 
+ *   be in integer.
  * @param $cvterm
  *   An associative array describing the cvterm. Valid keys include:
  *     - name: the name for the cvterm,
@@ -1493,18 +1524,20 @@ function tripal_autocomplete_cvterm($cv_id, $string = '') {
  *     - cv_id: the primary key of the cv the cvterm belongs to.
  * @param $options
  *   An associative array of options. Valid keys include:
- *     - insert_cvterm: Insert the cvterm if it doesn't already exist. FALSE is the default
+ *     - insert_cvterm: Insert the cvterm if it doesn't already exist. FALSE is 
+ *       the default.
  *
- * @ingroup tripal_chado_api
+ * @ingroup tripal_chado_cv_api
  */
-function tripal_associate_cvterm($basetable, $record_id, $cvterm, $options = array()) {
+function chado_associate_cvterm($basetable, $record_id, $cvterm, $options = array()) {
   $linking_table = $basetable . '_cvterm';
   $foreignkey_name = $basetable . '_id';
 
   // Default Values
   $options['insert_cvterm'] = (isset($options['insert_cvterm'])) ? $options['insert_cvterm'] : FALSE;
 
-  // If the cvterm_id is not set then find the cvterm record using the name and cv_id
+  // If the cvterm_id is not set then find the cvterm record using the name and 
+  // cv_id.
   if (!isset($cvterm['cvterm_id'])) {
     $values = array(
       'name' => $cvterm['name'],
@@ -1519,7 +1552,7 @@ function tripal_associate_cvterm($basetable, $record_id, $cvterm, $options = arr
     }
     else {
       tripal_report_error('tripal_chado_api', TRIPAL_WARNING,
-        "tripal_associate_cvterm: The cvterm needs to have either the cv_name or cv_id
+        "chado_associate_cvterm: The cvterm needs to have either the cv_name or cv_id
           supplied. You were trying to associate a cvterm with the %base %record_id
           and supplied the cvterm values: %cvterm.",
         array('%base' => $basetable, '%record_id' => $record_id, '%cvterm' => print_r($cvterm,TRUE))
@@ -1535,13 +1568,13 @@ function tripal_associate_cvterm($basetable, $record_id, $cvterm, $options = arr
     }
     elseif ($options['insert_cvterm']) {
       // Insert the cvterm
-      $insert = tripal_insert_cvterm($values);
+      $insert = chado_insert_cvterm($values);
       if (isset($insert->cvterm_id)) {
         $cvterm['cvterm_id'] = $insert->cvterm_id;
       }
       else {
         tripal_report_error('tripal_chado_api', TRIPAL_WARNING,
-          "tripal_associate_cvterm: Unable to insert the cvterm using the cvterm values: %cvterm.",
+          "chado_associate_cvterm: Unable to insert the cvterm using the cvterm values: %cvterm.",
           array('%cvterm' => print_r($cvterm,TRUE))
         );
         return FALSE;
@@ -1549,14 +1582,14 @@ function tripal_associate_cvterm($basetable, $record_id, $cvterm, $options = arr
     }
     else {
       tripal_report_error('tripal_api', TRIPAL_WARNING,
-        "tripal_associate_cvterm: The cvterm doesn't already exist. You supplied the cvterm values: %cvterm.",
+        "chado_associate_cvterm: The cvterm doesn't already exist. You supplied the cvterm values: %cvterm.",
         array('%cvterm' => print_r($cvterm,TRUE))
       );
       return FALSE;
     }
   }
 
-  // Now add the link between the record & cvterm
+  // Now add the link between the record & cvterm.
   if ($cvterm['cvterm_id'] > 0) {
     $values = array(
       'cvterm_id' => $cvterm['cvterm_id'],
@@ -1588,5 +1621,3 @@ function tripal_associate_cvterm($basetable, $record_id, $cvterm, $options = arr
 
   return FALSE;
 }
-
-

+ 150 - 129
tripal_chado/api/modules/tripal_chado.db.api.inc

@@ -1,72 +1,81 @@
 <?php
 /**
  * @file
- * Provides an application programming interface (API) to manage references to
- * external databases
+ * Provides API functions specificially for managing external database reference
+ * records in Chado. 
  */
 
 /**
  * @defgroup tripal_chado_database_api Chado DB
  * @ingroup tripal_chado_api
  * @{
+ * External databases can be used to indicate the source for a variety of data.
+ * The most common use is with controlled vocabularies (CV).  Chado expects that
+ * every CV have an external database record, where the database name must be
+ * the short name of the CV.  In other cases, records such as features, stocks,
+ * libraries, etc., can also be present in remote databases and these
+ * associations can be made through dbxref linker tables.  The API functions
+ * provided here provide tools to easily work with external databases.
  * @}
  */
 
 /**
- * Retrieves a chado db variable
+ * Retrieves a chado db variable.
  *
  * Example Usage:
  * @code
-    $select_values = array(
-      'name' => 'SOFP'
-    );
-    $db_object = tripal_get_db($select_values);
+ *   $select_values = array(
+ *     'name' => 'SOFP'
+ *   );
+ *   $db_object = chado_get_db($select_values);
  * @endcode
+ * 
  *  The above code selects the SOFP db and returns the following object:
  * @code
-    $db_object = stdClass Object (
-      [db_id] => 49
-      [name] => SOFP
-      [description] =>
-      [urlprefix] =>
-      [url] =>
-    );
+ *   $db_object = stdClass Object (
+ *     [db_id] => 49
+ *     [name] => SOFP
+ *     [description] =>
+ *     [urlprefix] =>
+ *     [url] =>
+ *   );
  * @endcode
  *
  * @param $identifier
- *   An array with the key stating what the identifier is. Supported keys (only on of the
- *   following unique keys is required):
- *    - db_id: the chado db.db_id primary key
- *    - name: the chado db.name field (assume unique)
+ *   An array with the key stating what the identifier is. Supported keys (only 
+ *   on of the following unique keys is required):
+ *    - db_id: the chado db.db_id primary key.
+ *    - name: the chado db.name field (assume unique).
  * @param $options
  *   An array of options. Supported keys include:
- *     - Any keys supported by chado_generate_var(). See that function definition for
- *       additional details.
+ *     - Any keys supported by chado_generate_var(). See that function 
+ *       definition for additional details.
  *
- * NOTE: the $identifier parameter can really be any array similar to $values passed into
- *   chado_select_record(). It should fully specify the db record to be returned.
+ * NOTE: the $identifier parameter can really be any array similar to $values 
+ * passed into chado_select_record(). It should fully specify the db record to 
+ * be returned.
  *
  * @return
- *   If unique values were passed in as an identifier then an object describing the cv
- *   will be returned (will be a chado variable from chado_generate_var()). Otherwise,
- *   an array of objects will be returned.
+ *   If unique values were passed in as an identifier then an object describing 
+ *   the cv will be returned (will be a chado variable from 
+ *   chado_generate_var()). Otherwise, an array of objects will be returned.
  *
  * @ingroup tripal_chado_database_api
  */
-function tripal_get_db($identifiers, $options = array()) {
+function chado_get_db($identifiers, $options = array()) {
 
-  // Set Defaults
+  // Set Defaults.
   if (!isset($options['include_fk'])) {
-    // Tells chado_generate_var not to follow any foreign keys
+    // Tells chado_generate_var not to follow any foreign keys.
     $options['include_fk'] = array();
   }
 
-  // Error Checking of parameters
+  // Error Checking of parameters.
   if (!is_array($identifiers)) {
     tripal_report_error(
       'tripal_chado_database_api',
       TRIPAL_ERROR,
-      "tripal_get_db: The identifier passed in is expected to be an array with the key
+      "chado_get_db: The identifier passed in is expected to be an array with the key
         matching a column name in the db table (ie: db_id or name). You passed in %identifier.",
       array(
         '%identifier'=> print_r($identifiers, TRUE)
@@ -77,7 +86,7 @@ function tripal_get_db($identifiers, $options = array()) {
     tripal_report_error(
       'tripal_chado_database_api',
       TRIPAL_ERROR,
-      "tripal_get_db: You did not pass in anything to identify the db you want. The identifier
+      "chado_get_db: You did not pass in anything to identify the db you want. The identifier
         is expected to be an array with the key matching a column name in the db table
         (ie: db_id or name). You passed in %identifier.",
       array(
@@ -86,31 +95,31 @@ function tripal_get_db($identifiers, $options = array()) {
     );
   }
 
-  // Try to get the db
+  // Try to get the db.
   $db = chado_generate_var(
     'db',
     $identifiers,
     $options
   );
 
-  // Ensure the db is singular. If it's an array then it is not singular
+  // Ensure the db is singular. If it's an array then it is not singular.
   if (is_array($db)) {
     tripal_report_error(
       'tripal_chado_database_api',
       TRIPAL_ERROR,
-      "tripal_get_db: The identifiers you passed in were not unique. You passed in %identifier.",
+      "chado_get_db: The identifiers you passed in were not unique. You passed in %identifier.",
       array(
         '%identifier'=> print_r($identifiers, TRUE)
       )
     );
   }
 
-  // Report an error if $db is FALSE since then chado_generate_var has failed
+  // Report an error if $db is FALSE since then chado_generate_var has failed.
   elseif ($db === FALSE) {
     tripal_report_error(
       'tripal_chado_database_api',
       TRIPAL_ERROR,
-      "tripal_get_db: chado_generate_var() failed to return a db based on the identifiers
+      "chado_get_db: chado_generate_var() failed to return a db based on the identifiers
         you passed in. You should check that your identifiers are correct, as well as, look
         for a chado_generate_var error for additional clues. You passed in %identifier.",
       array(
@@ -127,14 +136,14 @@ function tripal_get_db($identifiers, $options = array()) {
 
 /**
  * Create an options array to be used in a form element
- *   which provides a list of all chado dbs
+ *   which provides a list of all chado dbs.
  *
  * @return
- *   An array(db_id => name) for each db in the chado db table
+ *   An array(db_id => name) for each db in the chado db table.
  *
  * @ingroup tripal_chado_database_api
  */
-function tripal_get_db_select_options() {
+function chado_get_db_select_options() {
 
   $dbs = chado_query("SELECT db_id, name FROM {db} ORDER BY name");
 
@@ -150,81 +159,84 @@ function tripal_get_db_select_options() {
 }
 
 /**
- * Retrieves a chado database reference variable
+ * Retrieves a chado database reference variable.
  *
  * Example Usage:
  * @code
-    $identifiers = array(
-      'accession' => 'synonym',
-      'db_id' => array(
-        'name' => 'SOFP'
-      )
-    );
-    $dbxref_object = tripal_get_dbxref($identifiers);
+ *   $identifiers = array(
+ *     'accession' => 'synonym',
+ *     'db_id' => array(
+ *       'name' => 'SOFP'
+ *     )
+ *   );
+ *   $dbxref_object = chado_get_dbxref($identifiers);
  * @endcode
- *  The above code selects the synonym database reference and returns the following object:
+ *  The above code selects the synonym database reference and returns the 
+ *  following object:
  * @code
-    $dbxref_object = stdClass Object (
-      [dbxref_id] => 2581
-      [accession] => synonym
-      [description] =>
-      [version] =>
-      [db_db_id] => 49
-      [db_name] => SOFP
-      [db_description] =>
-      [db_urlprefix] =>
-      [db_url] =>
-    );
+ *  $dbxref_object = stdClass Object (
+ *     [dbxref_id] => 2581
+ *     [accession] => synonym
+ *     [description] =>
+ *     [version] =>
+ *     [db_db_id] => 49
+ *     [db_name] => SOFP
+ *     [db_description] =>
+ *     [db_urlprefix] =>
+ *     [db_url] =>
+ *   );
  * @endcode
  *
  * @param $identifier
  *   An array apropriate for use with the chado_generate_var for uniquely
  *   identifying a dbxref record. Alternatively, there are also some specially
  *   handled keys. They are:
- *    - property: An array/object describing the property to select records for. It
- *      should at least have either a type_name (if unique across cvs) or type_id. Other
- *      supported keys include: cv_id/cv_name (of the type), value and rank
+ *    - property: An array/object describing the property to select records for. 
+ *      It should at least have either a type_name (if unique across cvs) or 
+ *      type_id. Other supported keys include: cv_id/cv_name (of the type), 
+ *      value and rank.
  * @param $options
  *   An array of options. Supported keys include:
- *     - Any keys supported by chado_generate_var(). See that function definition for
- *       additional details.
+ *     - Any keys supported by chado_generate_var(). See that function 
+ *       definition for additional details.
  *
- * NOTE: the $identifier parameter can really be any array similar to $values passed into
- *   chado_select_record(). It should fully specify the dbxref record to be returned.
+ * NOTE: the $identifier parameter can really be any array similar to $values 
+ * passed into chado_select_record(). It should fully specify the dbxref record 
+ * to be returned.
  *
  * @return
- *   If unique values were passed in as an identifier then an object describing the dbxref
- *   will be returned (will be a chado variable from chado_generate_var()). Otherwise,
- *   FALSE will be returned.
+ *   If unique values were passed in as an identifier then an object describing 
+ *   the dbxref will be returned (will be a chado variable from 
+ *   chado_generate_var()). Otherwise, FALSE will be returned.
  *
- * @ingroup tripal_db_api
+ * @ingroup tripal_chado_database_api
  */
-function tripal_get_dbxref($identifiers, $options = array()) {
+function chado_get_dbxref($identifiers, $options = array()) {
 
-  // Set Defaults
+  // Set Defaults.
   if (!isset($options['include_fk'])) {
-    // Tells chado_generate_var not only expand the db
+    // Tells chado_generate_var not only expand the db.
     $options['include_fk'] = array('db_id' => TRUE);
   }
 
-  // Error Checking of parameters
+  // Error Checking of parameters.
   if (!is_array($identifiers)) {
     tripal_report_error('tripal_db_api', TRIPAL_ERROR,
-      "tripal_get_dbxref: The identifier passed in is expected to be an array with the key
+      "chado_get_dbxref: The identifier passed in is expected to be an array with the key
         matching a column name in the dbxref table (ie: dbxref_id or name). You passed in %identifier.",
       array('%identifier'=> print_r($identifiers, TRUE))
     );
   }
   elseif (empty($identifiers)) {
     tripal_report_error('tripal_db_api', TRIPAL_ERROR,
-      "tripal_get_dbxref: You did not pass in anything to identify the dbxref you want. The identifier
+      "chado_get_dbxref: You did not pass in anything to identify the dbxref you want. The identifier
         is expected to be an array with the key matching a column name in the dbxref table
         (ie: dbxref_id or name). You passed in %identifier.",
       array('%identifier'=> print_r($identifiers, TRUE))
     );
   }
 
-  // If one of the identifiers is property then use chado_get_record_with_property()
+  // If one of the identifiers is property then use chado_get_record_with_property().
   if (isset($identifiers['property'])) {
     $property = $identifiers['property'];
     unset($identifiers['property']);
@@ -235,25 +247,27 @@ function tripal_get_dbxref($identifiers, $options = array()) {
     );
   }
 
-  // Else we have a simple case and we can just use chado_generate_var to get the analysis
+  // Else we have a simple case and we can just use chado_generate_var to get 
+  // the analysis.
   else {
     $dbxref = chado_generate_var('dbxref', $identifiers, $options);
   }
 
-  // Ensure the dbxref is singular. If it's an array then it is not singular
+  // Ensure the dbxref is singular. If it's an array then it is not singular.
   if (is_array($dbxref)) {
     tripal_report_error('tripal_db_api', TRIPAL_ERROR,
-      "tripal_get_dbxref: The identifiers you passed in were not unique. You passed in %identifier.",
+      "chado_get_dbxref: The identifiers you passed in were not unique. You passed in %identifier.",
       array('%identifier'=> print_r($identifiers, TRUE))
     );
   }
 
-  // Report an error if $dbxref is FALSE since then chado_generate_var has failed
+  // Report an error if $dbxref is FALSE since then chado_generate_var has 
+  // failed.
   elseif ($dbxref === FALSE) {
     tripal_report_error(
       'tripal_db_api',
       TRIPAL_ERROR,
-      "tripal_get_dbxref: chado_generate_var() failed to return a dbxref based on the identifiers
+      "chado_get_dbxref: chado_generate_var() failed to return a dbxref based on the identifiers
         you passed in. You should check that your identifiers are correct, as well as, look
         for a chado_generate_var error for additional clues. You passed in %identifier.",
       array(
@@ -283,8 +297,10 @@ function tripal_get_dbxref($identifiers, $options = array()) {
  *
  * @return
  *   A string containing the URL.
+ * 
+ * @ingroup tripal_chado_database_api
  */
-function tripal_get_dbxref_url($dbxref) {
+function chado_get_dbxref_url($dbxref) {
   $final_url = '';
 
   // Create the URL for the term.
@@ -316,13 +332,14 @@ function tripal_get_dbxref_url($dbxref) {
  * Adds a new database to the Chado DB table and returns the DB object.
  *
  * @param $values
- *   An associative array of the values of the db (those to be inserted)
- *   - name: The name of the database. This name is usually used as the prefix for
- *     CV term accessions
- *   - description: (Optional) A description of the database.  By default no description is required.
- *   - url: (Optional) The URL for the database
- *   - urlprefix: (Optional) The URL that is to be used as a prefix when constructing a
- *     link to a database term
+ *   An associative array of the values of the db (those to be inserted):
+ *   - name: The name of the database. This name is usually used as the prefix 
+ *     for CV term accessions.
+ *   - description: (Optional) A description of the database.  By default no 
+ *     description is required.
+ *   - url: (Optional) The URL for the database.
+ *   - urlprefix: (Optional) The URL that is to be used as a prefix when 
+ *     constructing a link to a database term.
  * @param $options
  *   Optional. An associative array of options that can include:
  *   - update_existing: Set this to '1' to force an update of the database if it
@@ -335,16 +352,16 @@ function tripal_get_dbxref_url($dbxref) {
  *
  * @ingroup tripal_chado_database_api
  */
-function tripal_insert_db($values, $options = array()) {
+function chado_insert_db($values, $options = array()) {
 
-  // Default Values
+  // Default Values.
   $dbname = $values['name'];
   $description = (isset($values['description'])) ? $values['description'] : '';
   $url = (isset($values['url'])) ? $values['url'] : '';
   $urlprefix = (isset($values['urlprefix'])) ? $values['urlprefix'] : '';
   $update = (isset($options['update_existing'])) ? $options['update_existing'] : TRUE;
 
-  // build the values array for inserting/updating
+  // Build the values array for inserting/updating.
   $ins_values = array(
     'name' => $dbname,
     'description' => $description,
@@ -352,11 +369,11 @@ function tripal_insert_db($values, $options = array()) {
     'urlprefix' => $urlprefix
   );
 
-  // get the database record if it already exists
+  // Get the database record if it already exists.
   $sel_values = array('name' => $dbname);
   $result = chado_select_record('db', array('*'), $sel_values);
 
-  // if it does not exists then add it
+  // If it does not exists then add it.
   if (count($result) == 0) {
     $ins_options = array('statement_name' => 'ins_db_nadeurur');
     $success = chado_insert_record('db', $ins_values, $ins_options);
@@ -366,7 +383,7 @@ function tripal_insert_db($values, $options = array()) {
     }
     $result = chado_select_record('db', array('*'), $sel_values);
   }
-  // if it exists and update is enabled the do the update
+  // If it exists and update is enabled the do the update.
   elseif ($update) {
     $upd_options = array('statement_name' => 'upd_db_nadeurur');
     $success = chado_update_record('db', $sel_values, $ins_values, $upd_options);
@@ -377,20 +394,20 @@ function tripal_insert_db($values, $options = array()) {
     $result = chado_select_record('db', array('*'), $sel_values);
   }
 
-  // return the database object
+  // Return the database object.
   return $result[0];
 
 }
 
 /**
- * Add a database reference
+ * Add a database reference.
  *
  * @param $values
  *   An associative array of the values to be inserted including:
- *    - db_id: the database_id of the database the reference is from
- *    - accession: the accession
- *    - version: (Optional) The version of the database reference
- *    - description: (Optional) A description of the database reference
+ *    - db_id: the database_id of the database the reference is from.
+ *    - accession: the accession.
+ *    - version: (Optional) The version of the database reference.
+ *    - description: (Optional) A description of the database reference.
  *
  * @return
  *   The newly inserted dbxref as an object, similar to that returned by
@@ -398,7 +415,7 @@ function tripal_insert_db($values, $options = array()) {
  *
  * @ingroup tripal_chado_database_api
  */
-function tripal_insert_dbxref($values) {
+function chado_insert_dbxref($values) {
 
   $db_id = $values['db_id'];
   $accession = $values['accession'];
@@ -412,7 +429,7 @@ function tripal_insert_dbxref($values) {
     'description' => $description
   );
 
-  // check to see if the dbxref exists
+  // Check to see if the dbxref exists.
   $sel_values = array(
     'db_id'     => $db_id,
     'accession' => $accession,
@@ -420,7 +437,7 @@ function tripal_insert_dbxref($values) {
   );
   $result = chado_select_record('dbxref', array('*'), $sel_values);
 
-  // if it doesn't already exist then add it
+  // If it doesn't already exist then add it.
   if (!$result) {
     $success = chado_insert_record('dbxref', $ins_values);
     if (!$success) {
@@ -439,32 +456,36 @@ function tripal_insert_dbxref($values) {
 }
 
 /**
- * Add a record to a database reference linking table (ie: feature_dbxref)
+ * Add a record to a database reference linking table (ie: feature_dbxref).
  *
  * @param $basetable
- *   The base table for which the dbxref should be associated. Thus to associate a dbxref
- *   with a feature the basetable=feature and dbxref_id is added to the feature_dbxref table
+ *   The base table for which the dbxref should be associated. Thus to associate 
+ *   a dbxref with a feature the basetable=feature and dbxref_id is added to the
+ *   feature_dbxref table.
  * @param $record_id
- *   The primary key of the basetable to associate the dbxref with. This should be in integer.
+ *   The primary key of the basetable to associate the dbxref with. This should 
+ *   be in integer.
  * @param $dbxref
- *   An associative array describing the dbxref. Valid keys include: 'accession' => the
- *   accession for the dbxref, 'db_name' => the name of the database the dbxref belongs to;
+ *   An associative array describing the dbxref. Valid keys include: 
+ *   'accession' => the accession for the dbxref, 'db_name' => the name of the 
+ *    database the dbxref belongs to.
  *   'db_id' => the primary key of the database the dbxref belongs to.
  * @param $options
  *   An associative array of options. Valid keys include:
- *    - insert_dbxref: Insert the dbxref if it doesn't already exist. TRUE is the default
+ *    - insert_dbxref: Insert the dbxref if it doesn't already exist. TRUE is 
+ *      the default.
  *
  * @ingroup tripal_chado_database_api
  */
-function tripal_associate_dbxref($basetable, $record_id, $dbxref, $options = array()) {
+function chado_associate_dbxref($basetable, $record_id, $dbxref, $options = array()) {
   $linking_table = $basetable . '_dbxref';
   $foreignkey_name = $basetable . '_id';
 
-  // Default Values
+  // Default Values.
   $options['insert_dbxref'] = (isset($options['insert_dbxref'])) ? $options['insert_dbxref'] : TRUE;
 
-  // If the dbxref_id is set then we know it already exists
-  // Otherwise, select to check
+  // If the dbxref_id is set then we know it already exists.
+  // Otherwise, select to check.
   if (!isset($dbxref['dbxref_id'])) {
     $values = array(
       'accession' => $dbxref['accession'],
@@ -480,7 +501,7 @@ function tripal_associate_dbxref($basetable, $record_id, $dbxref, $options = arr
       tripal_report_error(
         'tripal_chado_database_api',
         TRIPAL_WARNING,
-        "tripal_associate_dbxref: The dbxref needs to have either the db_name or db_id
+        "chado_associate_dbxref: The dbxref needs to have either the db_name or db_id
           supplied. You were trying to associate a dbxref with the %base %record_id
           and supplied the dbxref values: %dbxref.",
         array('%base' => $basetable, '%record_id' => $record_id, '%dbxref' => print_r($dbxref,TRUE))
@@ -492,8 +513,8 @@ function tripal_associate_dbxref($basetable, $record_id, $dbxref, $options = arr
       $dbxref['dbxref_id'] = $select[0]->dbxref_id;
     }
     elseif ($options['insert_dbxref']) {
-      // Insert the dbxref
-      $insert = tripal_insert_dbxref($values);
+      // Insert the dbxref.
+      $insert = chado_insert_dbxref($values);
       if (isset($insert->dbxref_id)) {
         $dbxref['dbxref_id'] = $insert->dbxref_id;
       }
@@ -501,7 +522,7 @@ function tripal_associate_dbxref($basetable, $record_id, $dbxref, $options = arr
         tripal_report_error(
           'tripal_chado_database_api',
           TRIPAL_WARNING,
-          "tripal_associate_dbxref: Unable to insert the dbxref using the dbxref values: %dbxref.",
+          "chado_associate_dbxref: Unable to insert the dbxref using the dbxref values: %dbxref.",
           array('%dbxref' => print_r($dbxref,TRUE))
         );
         return FALSE;
@@ -511,14 +532,14 @@ function tripal_associate_dbxref($basetable, $record_id, $dbxref, $options = arr
       tripal_report_error(
         'tripal_api',
         TRIPAL_WARNING,
-        "tripal_associate_dbxref: The dbxref doesn't already exist. You supplied the dbxref values: %dbxref.",
+        "chado_associate_dbxref: The dbxref doesn't already exist. You supplied the dbxref values: %dbxref.",
         array('%dbxref' => print_r($dbxref,TRUE))
       );
       return FALSE;
     }
   }
 
-  // Now add the link between the record & dbxref
+  // Now add the link between the record & dbxref.
   if ($dbxref['dbxref_id'] > 0) {
     $values = array(
       'dbxref_id' => $dbxref['dbxref_id'],
@@ -527,7 +548,7 @@ function tripal_associate_dbxref($basetable, $record_id, $dbxref, $options = arr
 
     $result = chado_select_record($linking_table, array('*'), $values);
 
-    // if it doesn't already exist then add it
+    // If it doesn't already exist then add it.
     if (!$result) {
       $success = chado_insert_record($linking_table, $values);
       if (!$success) {
@@ -555,19 +576,19 @@ function tripal_associate_dbxref($basetable, $record_id, $dbxref, $options = arr
 
 /**
  * This function is intended to be used in autocomplete forms
- * for searching for accession that begin with the provided string
+ * for searching for accession that begin with the provided string.
  *
  * @param $db_id
- *   The DB ID in which to search for the term
+ *   The DB ID in which to search for the term.
  * @param $string
- *   The string to search for
+ *   The string to search for.
  *
  * @return
- *   A json array of terms that begin with the provided string
+ *   A json array of terms that begin with the provided string.
  *
- * @ingroup tripal_db_api
+ * @ingroup tripal_chado_database_api
  */
-function tripal_autocomplete_dbxref($db_id, $string = '') {
+function chado_autocomplete_dbxref($db_id, $string = '') {
   if (!$db_id) {
     return drupal_json_output(array());
   }

+ 115 - 687
tripal_chado/api/modules/tripal_chado.feature.api.inc

@@ -1,13 +1,17 @@
 <?php
 /**
  * @file
- * Provides an application programming interface (API) for working with features
+ * Provides API functions specificially for managing feature
+ * records in Chado.  
  */
 
 /**
  * @defgroup tripal_feature_api Chado Feature
  * @ingroup tripal_chado_api
  * @{
+ * Provides API functions specificially for managing feature
+ * records in Chado especially retrieving relationships and sequences derived 
+ * from relationships and feature alignments.
  * @}
  */
 /**
@@ -16,14 +20,14 @@
  * @param $field
  *   The field in the publication to search on.
  * @param $string
- *   The string to search for
+ *   The string to search for.
  *
  * @return
- *   A json array of terms that begin with the provided string
+ *   A json array of terms that begin with the provided string.
  *
  * @ingroup tripal_feature_api
  */
-function tripal_autocomplete_feature($string = '') {
+function chado_autocomplete_feature($string = '') {
   $items = array();
   $sql = "
     SELECT
@@ -47,17 +51,17 @@ function tripal_autocomplete_feature($string = '') {
 }
 
 /**
- * Performs a reverse compliment of a nucleotide sequence
+ * Performs a reverse compliment of a nucleotide sequence.
  *
  * @param $sequence
- *   The nucelotide sequence
+ *   The nucelotide sequence.
  *
  * @return
- *   an upper-case reverse complemented sequence
+ *   an upper-case reverse complemented sequence.
  *
  * @ingroup tripal_feature_api
  */
-function tripal_reverse_compliment_sequence($sequence) {
+function chado_reverse_compliment_sequence($sequence) {
 
   $seq = strtoupper($sequence);
   $seq = strrev($seq);
@@ -87,12 +91,13 @@ function tripal_reverse_compliment_sequence($sequence) {
  * @param $feature
  *   An associative array describing the feature. Valid keys include:
  *    - feature_id: The feature_id of the feature for which the sequence will
- *      be retrieved
- *    - name: The feature name. This will appear on the FASTA definition line
+ *      be retrieved.
+ *    - name: The feature name. This will appear on the FASTA definition line.
  *    - parent_id:  (optional) only retrieve a sequence if 'derive_from_parent'
  *      is true and the parent matches this ID.
- *    - featureloc_id: (optional) only retrieve a sequence if 'derive_from_parent' is
- *      true and the alignment is defined with this featureloc_id
+ *    - featureloc_id: (optional) only retrieve a sequence if 
+ *      'derive_from_parent' is true and the alignment is defined with this 
+ *      featureloc_id.
  * @param $options
  *   An associative array of options. Valid keys include:
  *    - width: Indicate the number of bases to use per line.  A new line will
@@ -105,52 +110,52 @@ function tripal_reverse_compliment_sequence($sequence) {
  *      excluding intro sub feature sequence.  For example, set this option to
  *      obtain just the coding sequence of an mRNA.
  *    - upstream: An integer specifing the number of upstream bases to include
- *      in the output
+ *      in the output.
  *    - downstream: An integer specifying the number of downstream bases to
  *      include in the output.
  *    - sub_feature_types: Only include sub features (or child features) of
- *      the types provided in the array
+ *      the types provided in the array.
  *    - relationship_type: If a relationship name is provided (e.g. sequence_of)
  *      then any sequences that are in relationships of this type with matched
- *      sequences are also included
+ *      sequences are also included.
  *    - relationship_part: If a relationship is provided in the preceeding
  *      argument then the rel_part must be either 'object' or 'subject' to
- *      indicate which side of the relationship the matched features belong
+ *      indicate which side of the relationship the matched features belong.
  *
  * @return
  *   an array of matching sequence in the following keys for each sequence:
- *      'types'         => an array of feature types that were used to derive
- *         the sequence (e.g. from an aggregated sequence)
- *      'upstream'      => the number of upstream bases included in the sequence
- *      'downstream'    => the number of downstream bases included in the
- *        sequence
- *      'defline'       => the definintion line used to create a FASTA sequence
- *      'residues'      => the residues
- *      'featureloc_id' => the featureloc_id if the sequences is from an
+ *    - types: an array of feature types that were used to derive
+ *      the sequence (e.g. from an aggregated sequence)
+ *    - upstream: the number of upstream bases included in the sequence
+ *    - downstream: the number of downstream bases included in the
+ *      sequence
+ *    - defline: the definintion line used to create a FASTA sequence
+ *    - residues: the residues
+ *    - featureloc_id: the featureloc_id if the sequences is from an
  *        alignment
  *
  * @ingroup tripal_feature_api
  */
-function tripal_get_feature_sequences($feature, $options) {
+function chado_get_feature_sequences($feature, $options) {
 
   // Default values for finding the feature.
-  $feature_id         = array_key_exists('feature_id', $feature)     ? $feature['feature_id']     : 0;
-  $parent_id          = array_key_exists('parent_id', $feature)      ? $feature['parent_id']      : 0;
-  $featureloc_id      = array_key_exists('featureloc_id', $feature)  ? $feature['featureloc_id']  : 0;
-  $feature_name       = array_key_exists('name', $feature)           ? $feature['name']           : '';
+  $feature_id = array_key_exists('feature_id', $feature) ? $feature['feature_id']     : 0;
+  $parent_id = array_key_exists('parent_id', $feature) ? $feature['parent_id']      : 0;
+  $featureloc_id = array_key_exists('featureloc_id', $feature) ? $feature['featureloc_id']  : 0;
+  $feature_name = array_key_exists('name', $feature) ? $feature['name']           : '';
 
   // Default values for building the sequence.
-  $num_bases_per_line = array_key_exists('width', $options)              ? $options['width']              : 50;
+  $num_bases_per_line = array_key_exists('width', $options) ? $options['width']              : 50;
   $derive_from_parent = array_key_exists('derive_from_parent', $options) ? $options['derive_from_parent'] : 0;
-  $aggregate          = array_key_exists('aggregate', $options)          ? $options['aggregate']          : 0;
-  $upstream           = array_key_exists('upstream', $options)           ? $options['upstream']           : 0;
-  $downstream         = array_key_exists('downstream', $options)         ? $options['downstream']         : 0;
-  $sub_features       = array_key_exists('sub_feature_types', $options)  ? $options['sub_feature_types']  : array();
-  $relationship       = array_key_exists('relationship_type', $options)  ? $options['relationship_type']  : '';
-  $rel_part           = array_key_exists('relationship_part', $options)  ? $options['relationship_part']  : '';
-  $is_html            = array_key_exists('is_html', $options)            ? $options['is_html']            : 0;
-  $is_txt             = array_key_exists('is_txt', $options)             ? $options['is_txt']             : 0;
-  $is_raw             = array_key_exists('is_raw', $options)             ? $options['is_raw']             : 1;
+  $aggregate = array_key_exists('aggregate', $options) ? $options['aggregate']          : 0;
+  $upstream = array_key_exists('upstream', $options) ? $options['upstream']           : 0;
+  $downstream = array_key_exists('downstream', $options) ? $options['downstream']         : 0;
+  $sub_features = array_key_exists('sub_feature_types', $options) ? $options['sub_feature_types']  : array();
+  $relationship = array_key_exists('relationship_type', $options) ? $options['relationship_type']  : '';
+  $rel_part = array_key_exists('relationship_part', $options) ? $options['relationship_part']  : '';
+  $is_html = array_key_exists('is_html', $options) ? $options['is_html']            : 0;
+  $is_txt = array_key_exists('is_txt', $options) ? $options['is_txt']             : 0;
+  $is_raw = array_key_exists('is_raw', $options) ? $options['is_raw']             : 1;
 
   if (!$upstream) {
     $upstream = 0;
@@ -162,7 +167,7 @@ function tripal_get_feature_sequences($feature, $options) {
   // Make sure the sub_features variable is an array.
   if (!is_array($sub_features)) {
     tripal_report_error('tripal_feature', TRIPAL_ERROR,
-      "'sub_features' option must be an array for function tripal_get_feature_sequences().",
+      "'sub_features' option must be an array for function chado_get_feature_sequences().",
       array()
     );
     return array();
@@ -212,7 +217,7 @@ function tripal_get_feature_sequences($feature, $options) {
       if ($rel_part == "object") {
         $defline = "$feature->uniquename $feature->feature_type ($feature->genus $feature->species), $relationship, $feature_name";
       }
-      return tripal_get_feature_sequences(
+      return chado_get_feature_sequences(
         array(
           'feature_id' => $feature->feature_id,
           'name' => $defline,
@@ -341,7 +346,7 @@ function tripal_get_feature_sequences($feature, $options) {
       if ($parent_id and $parent_id != $parent->srcfeature_id) {
         continue;
       }
-      // if the user specified a particular featureloc_id and this one
+      // If the user specified a particular featureloc_id and this one
       // doesn't match then skip it.
       if ($featureloc_id and $featureloc_id != $parent->featureloc_id) {
         continue;
@@ -351,8 +356,8 @@ function tripal_get_feature_sequences($feature, $options) {
       $notes = '';
       $types = array();
 
-      // if we are to aggregate then we will ignore the feature returned
-      // by the query above and rebuild it using the sub features
+      // If we are to aggregate then we will ignore the feature returned
+      // by the query above and rebuild it using the sub features.
       if ($aggregate) {
 
         // now get the sub features that are located on the parent.
@@ -382,13 +387,14 @@ function tripal_get_feature_sequences($feature, $options) {
             continue;
           }
 
-          // keep up with the types
+          // Keep up with the types.
           if (!in_array($child->type_name, $types)) {
             $types[] = $child->type_name;
           }
 
-          // if the first sub feature we need to include the upstream bases. first check if
-          // the feature is in the foward direction or the reverse.
+          // If the first sub feature we need to include the upstream bases. 
+          // First check if the feature is in the foward direction or the 
+          // reverse.
           if ($i == 0 and $parent->strand >= 0) {  // forward direction
             // -------------------------- ref
             //    ....---->  ---->
@@ -402,8 +408,9 @@ function tripal_get_feature_sequences($feature, $options) {
             $q = chado_query($parent_sql, array(':upstream' => 0, ':downstream' => $downstream, ':feature_id' => $child->feature_id));
           }
 
-          // Next, if the last sub feature we need to include the downstream bases. first check if
-          // the feature is in teh forward direction or the reverse
+          // Next, if the last sub feature we need to include the downstream 
+          // bases. First check if the feature is in teh forward direction or 
+          // the reverse.
           elseif ($i == $num_children - 1 and $parent->strand >= 0) {  // forward direction
             // -------------------------- ref
             //        ---->  ---->....
@@ -416,7 +423,7 @@ function tripal_get_feature_sequences($feature, $options) {
             //          1       2  up
             $q = chado_query($parent_sql, array(':upstream' => $upstream, ':downstream' => 0, ':feature_id' => $child->feature_id));
           }
-          // for internal sub features we don't want upstream or downstream bases
+          // For internal sub features we don't want upstream or downstream bases.
           else {
             $q = chado_query($parent_sql, array(':upstream' => 0, ':downstream' => 0, ':feature_id' => $child->feature_id));
           }
@@ -435,7 +442,7 @@ function tripal_get_feature_sequences($feature, $options) {
           $i++;
         }
       }
-      // if this isn't an aggregate then use the parent residues
+      // If this isn't an aggregate then use the parent residues.
       else {
          $seq = $parent->residues;
          if ($parent->upstream > 0) {
@@ -446,14 +453,14 @@ function tripal_get_feature_sequences($feature, $options) {
          }
       }
 
-      // get the reverse compliment if feature is on the reverse strand
+      // Get the reverse compliment if feature is on the reverse strand.
       $dir = 'forward';
       $length = strlen($seq);
       if ($parent->strand < 0) {
-        $seq = tripal_reverse_compliment_sequence($seq);
+        $seq = chado_reverse_compliment_sequence($seq);
         $dir = 'reverse';
       }
-      // now format for display
+      // Now format for display.
       if ($is_html) {
         $seq = wordwrap($seq, $num_bases_per_line, "<br>", TRUE);
       }
@@ -484,7 +491,7 @@ function tripal_get_feature_sequences($feature, $options) {
       $featureloc->srcfeature_id->organism_id->species = $parent->species;
       // Get a proper feature object.
       $f = chado_generate_var('feature', array('feature_id' => $feature_id));
-      $defline = tripal_get_fasta_defline($f, $notes, $featureloc, '', $length);
+      $defline = chado_get_fasta_defline($f, $notes, $featureloc, '', $length);
 
       $sequences[] = array(
         'types'         => $types,
@@ -513,10 +520,10 @@ function tripal_get_feature_sequences($feature, $options) {
       $residues = wordwrap($residues, $num_bases_per_line, "\r\n", TRUE);
     }
 
-    // get the definintion line for this feature
-    $defline = tripal_get_fasta_defline($f, '', NULL, '', $length);
+    // Get the definintion line for this feature.
+    $defline = chado_get_fasta_defline($f, '', NULL, '', $length);
 
-    // add to the sequence array
+    // Add to the sequence array.
     $sequences[] = array(
       'types'      => $f->type_id->name,
       'upstream'   => 0,
@@ -531,6 +538,7 @@ function tripal_get_feature_sequences($feature, $options) {
 }
 
 /**
+ * Retrieves the bulk sequences for a given feature.
  *
  * @param $options
  *   An associative array of options for selecting a feature. Valid keys include:
@@ -580,31 +588,31 @@ function tripal_get_feature_sequences($feature, $options) {
  *
  * @ingroup tripal_feature_api
  */
-function tripal_get_bulk_feature_sequences($options) {
-
-  // default values for building the sequence
-  $org_commonname     = array_key_exists('org_commonname', $options)     ? $options['org_commonname']    : '';
-  $genus              = array_key_exists('genus', $options)              ? $options['genus']             : '';
-  $species            = array_key_exists('species', $options)            ? $options['species']           : '';
-  $analysis_name      = array_key_exists('analysis_name', $options)      ? $options['analysis_name']     : '';
-  $type               = array_key_exists('type', $options)               ? $options['type']              : '';
-  $feature_name       = array_key_exists('feature_name', $options)       ? $options['feature_name']      : '';
-  $feature_uname      = array_key_exists('feature_uname', $options)      ? $options['feature_uname']     : '';
+function chado_get_bulk_feature_sequences($options) {
+
+  // Default values for building the sequence
+  $org_commonname = array_key_exists('org_commonname', $options) ? $options['org_commonname']    : '';
+  $genus = array_key_exists('genus', $options) ? $options['genus']             : '';
+  $species = array_key_exists('species', $options) ? $options['species']           : '';
+  $analysis_name = array_key_exists('analysis_name', $options) ? $options['analysis_name']     : '';
+  $type = array_key_exists('type', $options) ? $options['type']              : '';
+  $feature_name = array_key_exists('feature_name', $options) ? $options['feature_name']      : '';
+  $feature_uname = array_key_exists('feature_uname', $options) ? $options['feature_uname']     : '';
   $derive_from_parent = array_key_exists('derive_from_parent', $options) ? $options['derive_from_parent'] : 0;
-  $aggregate          = array_key_exists('aggregate', $options)          ? $options['aggregate']          : 0;
-  $sub_features       = array_key_exists('sub_feature_types', $options)  ? $options['sub_feature_types']  : array();
-  $relationship       = array_key_exists('relationship_type', $options)  ? $options['relationship_type']  : '';
-  $rel_part           = array_key_exists('relationship_part', $options)  ? $options['relationship_part']  : '';
-  $num_bases_per_line = array_key_exists('width', $options)              ? $options['width']              : 50;
-  $upstream           = array_key_exists('upstream', $options)           ? $options['upstream']       : 0;
-  $downstream         = array_key_exists('downstream', $options)         ? $options['downstream']     : 0;
+  $aggregate = array_key_exists('aggregate', $options) ? $options['aggregate']          : 0;
+  $sub_features = array_key_exists('sub_feature_types', $options) ? $options['sub_feature_types']  : array();
+  $relationship = array_key_exists('relationship_type', $options) ? $options['relationship_type']  : '';
+  $rel_part = array_key_exists('relationship_part', $options) ? $options['relationship_part']  : '';
+  $num_bases_per_line = array_key_exists('width', $options) ? $options['width']              : 50;
+  $upstream = array_key_exists('upstream', $options) ? $options['upstream']       : 0;
+  $downstream = array_key_exists('downstream', $options) ? $options['downstream']     : 0;
 
   if (!$type and !$feature_name and !$genus) {
     print "Please provide a type, feature name or genus\n";
     return;
   }
 
-  // get the list of features
+  // Get the list of features.
   $vars = array();
   $sql  = "
     SELECT DISTINCT F.feature_id, F.name, F.uniquename,
@@ -643,7 +651,7 @@ function tripal_get_bulk_feature_sequences($options) {
         $sql .= ":fname$i, ";
         $vars[":fname$i"] = $fname;
       }
-      // remove the trailing comma and close the paren
+      // Remove the trailing comma and close the parenthesis.
       $sql = substr($sql, 0, -2) . ")";
     }
     else {
@@ -658,7 +666,7 @@ function tripal_get_bulk_feature_sequences($options) {
         $sql .= ":funame$i, ";
         $vars[":funame$i"] = $funame;
       }
-      // remove the trailing comma and close the paren
+      // Remove the trailing comma and close the parenthesis.
       $sql = substr($sql, 0, -2) . ")";
     }
     else {
@@ -677,7 +685,7 @@ function tripal_get_bulk_feature_sequences($options) {
   $sequences = array();
   while ($feature = $q->fetchObject()) {
     // get the sequences
-    $seqs = tripal_get_feature_sequences(array('feature_id' => $feature->feature_id), $options);
+    $seqs = chado_get_feature_sequences(array('feature_id' => $feature->feature_id), $options);
     $sequences = array_merge($sequences, $seqs);
     $num_seqs++;
   }
@@ -686,30 +694,34 @@ function tripal_get_bulk_feature_sequences($options) {
 }
 
 /**
- * Returns a definition line that can be used in a FASTA file
+ * Returns a definition line that can be used in a FASTA file.
  *
  * @param $feature
- *   A single feature object containing all the fields from the chado.feature table.
- *   Best case is to provide an object generated by the chado_generate_var() function.
+ *   A single feature object containing all the fields from the chado.feature 
+ *   table. Best case is to provide an object generated by the 
+ *   chado_generate_var() function.
  * @param $notes
- *   Optional: additional notes to be added to the definition line
+ *   Optional: additional notes to be added to the definition line.
  * @param $featureloc
- *   Optional: a single featureloc object generated using chado_generate_var that
- *   contains a record from the chado.featureloc table. Provide this if the
- *   sequence was obtained by using the alignment rather than from the feature.residues
- *   column
+ *   Optional: a single featureloc object generated using chado_generate_var
+ *   that contains a record from the chado.featureloc table. Provide this if the
+ *   sequence was obtained by using the alignment rather than from the 
+ *   feature.residues column.
  * @param $type
  *   Optional: the type of sequence. By default the feature type is used.
  * @param $length
- *   Optional: the length of the sequence
+ *   Optional: the length of the sequence.
  *
  * @return
  *   A string of the format: uniquename|name|type|feature_id
- *   or if an alignment:  srcfeature_name:fmin..fmax[+-]; alignment of uniquename|name|type|feature_id
+ *   or if an alignment:  srcfeature_name:fmin..fmax[+-]; alignment of 
+ *   uniquename|name|type|feature_id.
+ * 
+ * @ingroup tripal_feature_api
  */
-function tripal_get_fasta_defline($feature, $notes = '', $featureloc = NULL, $type = '', $length = 0) {
+function chado_get_fasta_defline($feature, $notes = '', $featureloc = NULL, $type = '', $length = 0) {
 
-  // make sure the featureloc object has the srcfeature if not, then add it
+  // Make sure the featureloc object has the srcfeature if not, then add it.
   if ($featureloc) {
     if (!is_object($featureloc->srcfeature_id)) {
       $featureloc->srcfeature_id = chado_generate_var('feature', array('feature_id' => $featureloc->srcfeature_id));
@@ -718,17 +730,17 @@ function tripal_get_fasta_defline($feature, $notes = '', $featureloc = NULL, $ty
       $featureloc->srcfeature_id->organism_id = chado_generate_var('organism', array('organism_id' => $featureloc->srcfeature_id->organism_id));
     }
   }
-  // make sure the feature object has the organism if not, then add it
+  // Make sure the feature object has the organism if not, then add it.
   if (!is_object($feature->organism_id)) {
     $feature->organism_id = chado_generate_var('organism', array('organism_id' => $feature->organism_id));
   }
 
-  // if a type is not provided then use the default type
+  // If a type is not provided then use the default type.
   if (!$type) {
     $type = $feature->type_id->name;
   }
 
-  // construct the definition line
+  // Construct the definition line.
   $defline = $feature->uniquename . " " .
              'ID=' . $feature->uniquename . "|" .
              'Name=' . $feature->name . "|" .
@@ -738,7 +750,7 @@ function tripal_get_fasta_defline($feature, $notes = '', $featureloc = NULL, $ty
     $defline .= "length=" . $length . "bp|";
   }
   if ($featureloc) {
-    $defline .= "location=Sequence derived from alignment at " . tripal_get_location_string($featureloc);
+    $defline .= "location=Sequence derived from alignment at " . chado_get_location_string($featureloc);
     $defline .= " (" . $featureloc->srcfeature_id->organism_id->genus . " " . $featureloc->srcfeature_id->organism_id->species . ")|";
   }
   if ($notes) {
@@ -749,13 +761,18 @@ function tripal_get_fasta_defline($feature, $notes = '', $featureloc = NULL, $ty
 }
 
 /**
- * Returns a string representing a feature location in an alignment
+ * Returns a string representing a feature location in an alignment.
  *
- * @param unknown $featureloc
+ * @param $featureloc
  *   A single featureloc object generated using chado_generate_var that
  *   contains a record from the chado.featureloc table.
+ *
+ *  @return
+ *   A string of the format: uniquename:featurelocmin..featurelocmax.strand
+ * 
+ * @ingroup tripal_feature_api
  */
-function tripal_get_location_string($featureloc) {
+function chado_get_location_string($featureloc) {
   $feature = $featureloc->feature_id;
 
   $strand = '';
@@ -769,592 +786,3 @@ function tripal_get_location_string($featureloc) {
   return $featureloc->srcfeature_id->name . ":" . ($featureloc->fmin + 1) . ".." . $featureloc->fmax .  $strand;
 }
 
-
-/**
- * Quickly retrieves relationships for a feature.
- *
- * Using the chado_expand_var function to retrieve a set
- * of relationships can be very slow, especialy if there are many relationships
- * This function is intended to help speed up the retrieval of relationships
- * by only retrieving the base information for the relationship and returning
- * an array with
- *
- * @param $feature
- *   The feature object
-
- * @return
- *   An array with two objects
- *
- * @ingroup tripal_feature_api
- */
-function tripal_get_feature_relationships($feature) {
-  // expand the feature object to include the feature relationships.
-  $options = array(
-    'return_array' => 1,
-    'order_by' => array('rank' => 'ASC'),
-    // we don't want to fully recurse we only need information about the
-    // relationship type and the object and subject features (including feature type
-    // and organism)
-    'include_fk' => array(
-      'type_id' => 1,
-      'object_id' => array(
-        'type_id' => 1,
-        'organism_id' => 1
-      ),
-      'subject_id'  => array(
-        'type_id' => 1,
-        'organism_id' => 1
-      ),
-    ),
-  );
-  $feature = chado_expand_var($feature, 'table', 'feature_relationship', $options);
-
-  // get the subject relationships
-  $srelationships = $feature->feature_relationship->subject_id;
-  $orelationships = $feature->feature_relationship->object_id;
-
-
-  // get alignment as child. The $feature->featureloc element
-  // is already populated from the alignment preprocess function
-  $options = array(
-    'return_array' => 1,
-    'include_fk' => array(
-      'srcfeature_id' => 1,
-      'feature_id' => 1,
-    ),
-  );
-  $feature = chado_expand_var($feature, 'table', 'featureloc', $options);
-  $cfeaturelocs = $feature->featureloc->feature_id;
-  if (!$cfeaturelocs) {
-    $cfeaturelocs = array();
-  }
-  elseif (!is_array($cfeaturelocs)) {
-    $cfeaturelocs = array($cfeaturelocs);
-  }
-
-  // prepare the SQL statement to get the featureloc for the
-  // feature in the relationships.
-  $flrels_sql = "
-    SELECT
-      FL.featureloc_id, F.name as srcfeature_name, FL.srcfeature_id,
-      FL.feature_id, FL.fmin, FL.fmax, FL.strand, FL.phase
-    FROM {featureloc} FL
-      INNER JOIN {feature} F ON F.feature_id = FL.srcfeature_id
-    WHERE FL.feature_id = :feature_id and FL.srcfeature_id = :srcfeature_id
-  ";
-
-  // combine both object and subject relationshisp into a single array
-  $relationships = array();
-  $relationships['object'] = array();
-  $relationships['subject'] = array();
-
-  // iterate through the object relationships
-  if ($orelationships) {
-    foreach ($orelationships as $relationship) {
-      $rel = new stdClass();
-      // get locations where the child feature and this feature overlap with the
-      // same landmark feature.
-      $rel->child_featurelocs = array();
-      foreach ($cfeaturelocs as $featureloc) {
-        $res = chado_query($flrels_sql, array(':feature_id' => $relationship->subject_id->feature_id, ':srcfeature_id' => $featureloc->srcfeature_id->feature_id));
-        while ($loc = $res->fetchObject()) {
-          // add in the node id of the src feature if it exists and save this location
-          if (property_exists($featureloc->srcfeature_id, 'nid')) {
-            $loc->nid = $featureloc->srcfeature_id->nid;
-          }
-          $rel->child_featurelocs[] = $loc;
-        }
-      }
-      $rel->record = $relationship;
-
-      // get the relationship and child types
-      $rel_type = t(preg_replace('/_/', " ", $relationship->type_id->name));
-      $child_type = $relationship->subject_id->type_id->name;
-
-      // get the node id of the subject
-//       $sql = "SELECT nid FROM {chado_feature} WHERE feature_id = :feature_id";
-//       $n = db_query($sql, array(':feature_id' => $relationship->subject_id->feature_id))->fetchObject();
-//       if ($n) {
-//         $rel->record->nid = $n->nid;
-//       }
-
-      if (!array_key_exists($rel_type, $relationships['object'])) {
-        $relationships['object'][$rel_type] = array();
-      }
-      if (!array_key_exists($child_type, $relationships['object'][$rel_type])) {
-        $relationships['object'][$rel_type][$child_type] = array();
-      }
-      $relationships['object'][$rel_type][$child_type][] = $rel;
-    }
-  }
-
-  // now add in the subject relationships
-  if ($srelationships) {
-    foreach ($srelationships as $relationship) {
-      $rel = new stdClass();
-      // get locations where this feature overlaps with the parent
-      $rel->parent_featurelocs = array();
-      foreach ($cfeaturelocs as $featureloc) {
-        $res = chado_query($flrels_sql, array(':feature_id' => $relationship->object_id->feature_id, ':srcfeature_id' => $featureloc->srcfeature_id->feature_id));
-        while ($loc = $res->fetchObject()) {
-          // add in the node id of the src feature if it exists and save this location
-          if (property_exists($featureloc->srcfeature_id, 'nid')) {
-            $loc->nid = $featureloc->srcfeature_id->nid;
-          }
-          $rel->parent_featurelocs[] = $loc;
-        }
-      }
-      $rel->record = $relationship;
-      $rel_type = t(preg_replace('/_/', " ", $relationship->type_id->name));
-      $parent_type = $relationship->object_id->type_id->name;
-
-//       // get the node id of the subject
-//       $sql = "SELECT nid FROM {chado_feature} WHERE feature_id = :feature_id";
-//       $n = db_query($sql, array(':feature_id' => $relationship->object_id->feature_id))->fetchObject();
-//       if ($n) {
-//         $rel->record->nid = $n->nid;
-//       }
-
-      if (!array_key_exists($rel_type, $relationships['subject'])) {
-        $relationships['subject'][$rel_type] = array();
-      }
-      if (!array_key_exists($parent_type, $relationships['subject'][$rel_type])) {
-        $relationships['subject'][$rel_type][$parent_type] = array();
-      }
-      $relationships['subject'][$rel_type][$parent_type][] = $rel;
-    }
-  }
-  return $relationships;
-}
-
-/**
- *
- * @param unknown $feature_id
- * @param unknown $featurelocs
- * @return multitype:|Ambigous <multitype:, an>
- */
-function chado_get_featureloc_sequences($feature_id, $featurelocs) {
-
-  // if we don't have any featurelocs then no point in continuing
-  if (!$featurelocs) {
-    return array();
-  }
-
-  // Get the list of relationships (including any aggregators) and iterate
-  // through each one to find information needed to color-code the reference sequence
-  $relationships = _tripal_feature_get_aggregate_relationships($feature_id);
-  if (!$relationships) {
-    return array();
-  }
-
-
-  // iterate through each of the realtionships features and get their
-  // locations
-  foreach ($relationships as $rindex => $rel) {
-    // get the featurelocs for each of the relationship features
-    $rel_featurelocs = chado_get_featurelocs($rel->subject_id, 'as_child', 0);
-    foreach ($rel_featurelocs as $rfindex => $rel_featureloc) {
-      // keep track of this unique source feature
-      $src = $rel_featureloc->src_feature_id . "-" . $rel_featureloc->src_cvterm_id;
-
-      // copy over the results to the relationship object.  Since there can
-      // be more than one feature location for each relationship feature we
-      // use the '$src' variable to keep track of these.
-      $rel->featurelocs = new stdClass();
-      $rel->featurelocs->$src = new stdClass();
-      $rel->featurelocs->$src->src_uniquename = $rel_featureloc->src_uniquename;
-      $rel->featurelocs->$src->src_cvterm_id  = $rel_featureloc->src_cvterm_id;
-      $rel->featurelocs->$src->src_cvname     = $rel_featureloc->src_cvname;
-      $rel->featurelocs->$src->fmin           = $rel_featureloc->fmin;
-      $rel->featurelocs->$src->fmax           = $rel_featureloc->fmax;
-      $rel->featurelocs->$src->src_name       = $rel_featureloc->src_name;
-
-      // keep track of the individual parts for each relationship
-      $start = $rel->featurelocs->$src->fmin;
-      $end   = $rel->featurelocs->$src->fmax;
-      $type  = $rel->subject_type;
-      $rel_locs[$src]['parts'][$start][$type]['start'] = $start;
-      $rel_locs[$src]['parts'][$start][$type]['end']   = $end;
-      $rel_locs[$src]['parts'][$start][$type]['type']  = $type;
-    }
-  }
-
-  // the featurelocs array provided to the function contains the locations
-  // where this feature is found.   We want to get the sequence for each
-  // location and then annotate it with the parts found from the relationships
-  // locations determiend above.
-  $floc_sequences = array();
-  foreach ($featurelocs as $featureloc) {
-
-    // build the src name so we can keep track of the different parts for each feature
-    $src = $featureloc->srcfeature_id->feature_id . "-" . $featureloc->srcfeature_id->type_id->cvterm_id;
-
-    // orient the parts to the beginning of the feature sequence
-    if (!empty($rel_locs[$src]['parts'])) {
-      $parts = $rel_locs[$src]['parts'];
-      $rparts = array();  // we will fill this up if we're on the reverse strand
-
-      foreach ($parts as $start => $types) {
-        foreach ($types as $type_name => $type) {
-          if ($featureloc->strand >= 0) {
-            // this is on the forward strand.  We need to convert the start on the src feature to the
-            // start on this feature's sequence
-            $parts[$start][$type_name]['start'] = $parts[$start][$type_name]['start'] - $featureloc->fmin;
-            $parts[$start][$type_name]['end']   = $parts[$start][$type_name]['end'] - $featureloc->fmin;
-            $parts[$start][$type_name]['type']  = $type_name;
-          }
-          else {
-            // this is on the reverse strand.  We need to swap the start and stop and calculate from the
-            // begining of the reverse sequence
-            $size = ($featureloc->fmax - $featureloc->fmin);
-            $start_orig = $parts[$start][$type_name]['start'];
-            $end_orig = $parts[$start][$type_name]['end'];
-            $new_start = $size - ($end_orig - $featureloc->fmin);
-            $new_end = $size - ($start_orig - $featureloc->fmin);
-
-            $rparts[$new_start][$type_name]['start'] = $new_start;
-            $rparts[$new_start][$type_name]['end']   = $new_end;
-            $rparts[$new_start][$type_name]['type']  = $type_name;
-          }
-        }
-      }
-
-      // now sort the parts
-      // if we're on the reverse strand we need to resort
-      if ($featureloc->strand >= 0) {
-        usort($parts, 'chado_feature__residues_sort_rel_parts_by_start');
-      }
-      else {
-        usort($rparts, 'chado_feature__residues_sort_rel_parts_by_start');
-        $parts = $rparts;
-      }
-
-      $floc_sequences[$src]['id'] = $src;
-      $floc_sequences[$src]['type'] = $featureloc->feature_id->type_id->name;
-      $args = array(':feature_id' => $featureloc->srcfeature_id->feature_id);
-      $start = $featureloc->fmin + 1;
-      $size = $featureloc->fmax - $featureloc->fmin;
-
-      // TODO: fix the hard coded $start and $size
-      // the $start and $size variables are hard-coded in the SQL statement
-      // because the db_query function places quotes around all placeholders
-      // (e.g. :start & :size) and screws up the substring function
-      $sql = "
-        SELECT substring(residues from $start for $size) as residues
-        FROM {feature}
-        WHERE feature_id = :feature_id
-      ";
-      $sequence = chado_query($sql, $args)->fetchObject();
-      $residues = $sequence->residues;
-      if ($featureloc->strand < 0) {
-        $residues = tripal_reverse_compliment_sequence($residues);
-      }
-      $strand = '.';
-      if ($featureloc->strand == 1) {
-        $strand = '+';
-      }
-      elseif ($featureloc->strand == -1) {
-        $strand = '-';
-      }
-      $floc_sequences[$src]['location'] = tripal_get_location_string($featureloc);
-      $floc_sequences[$src]['defline'] = tripal_get_fasta_defline($featureloc->feature_id, '', $featureloc, '', strlen($residues));
-      $floc_sequences[$src]['featureloc'] = $featureloc;
-      $floc_sequences[$src]['residues'] = $residues;
-      //$floc_sequences[$src]['formatted_seq'] =  tripal_feature_color_sequence($residues, $parts, $floc_sequences[$src]['defline']);
-    }
-  }
-  return $floc_sequences;
-}
-
-/**
- * Get features related to the current feature to a given depth. Recursive function.
- *
- * @param $feature_id
- * @param $substitute
- * @param $levels
- * @param $base_type_id
- * @param $depth
- *
- */
-function chado_get_aggregate_feature_relationships($feature_id, $substitute=1,
-  $levels=0, $base_type_id=NULL, $depth=0) {
-
-  // we only want to recurse to as many levels deep as indicated by the
-  // $levels variable, but only if this variable is > 0. If 0 then we
-  // recurse until we reach the end of the relationships tree.
-  if ($levels > 0 and $levels == $depth) {
-    return NULL;
-  }
-
-  // first get the relationships for this feature
-  return chado_get_feature_relationships($feature_id, 'as_object');
-
-}
-
-/**
- * Get the relationships for a feature.
- *
- * @param $feature_id
- *   The feature to get relationships for
- * @param $side
- *   The side of the relationship this feature is (ie: 'as_subject' or 'as_object')
- *
- */
-function chado_get_feature_relationships($feature_id, $side = 'as_subject') {
-
-  $feature = chado_generate_var('feature', array('feature_id' => $feature_id));
-
-  // get the relationships for this feature.  The query below is used for both
-  // querying the object and subject relationships
-  $sql = "
-    SELECT
-    FS.name as subject_name, FS.uniquename as subject_uniquename,
-      CVTS.name as subject_type, CVTS.cvterm_id as subject_type_id,
-      FR.subject_id, FR.type_id as relationship_type_id, FR.object_id, FR.rank,
-      CVT.name as rel_type,
-      FO.name as object_name, FO.uniquename as object_uniquename,
-      CVTO.name as object_type, CVTO.cvterm_id as object_type_id
-    FROM {feature_relationship} FR
-     INNER JOIN {cvterm} CVT  ON FR.type_id    = CVT.cvterm_id
-     INNER JOIN {feature} FS  ON FS.feature_id = FR.subject_id
-     INNER JOIN {feature} FO  ON FO.feature_id = FR.object_id
-     INNER JOIN {cvterm} CVTO ON FO.type_id    = CVTO.cvterm_id
-     INNER JOIN {cvterm} CVTS ON FS.type_id    = CVTS.cvterm_id
-  ";
-  if (strcmp($side, 'as_object')==0) {
-    $sql .= " WHERE FR.object_id = :feature_id";
-  }
-  if (strcmp($side, 'as_subject')==0) {
-    $sql .= " WHERE FR.subject_id = :feature_id";
-  }
-  $sql .= " ORDER BY FR.rank";
-
-  // get the relationships
-  $results = chado_query($sql, array(':feature_id' => $feature_id));
-
-  // Get the bundle for this feature type, if one exists.
-  $term = tripal_load_term_entity(array(
-    'vocabulary' => $feature->type_id->dbxref_id->db_id->name,
-    'accession' => $feature->type_id->dbxref_id->accession,
-  ));
-  $bundle = tripal_load_bundle_entity(array('term_id' => $term->id));
-
-  // iterate through the relationships, put these in an array and add
-  // in the Drupal node id if one exists
-  $i=0;
-  $relationships = array();
-  while ($rel = $results->fetchObject()) {
-
-    $entity = chado_get_record_entity_by_bundle($bundle, $rel->subject_id);
-    if ($entity) {
-      $rel->subject_entity_id = $entity->entity_id;
-    }
-    $entity = chado_get_record_entity_by_bundle($bundle, $rel->object_id);
-    if ($entity) {
-      $rel->object_entity_id = $entity->entity_id;
-    }
-    $relationships[$i++] = $rel;
-  }
-  return $relationships;
-}
-
-/**
- * Load the locations for a given feature
- *
- * @param $feature_id
- *   The feature to look up locations for
- * @param $side
- *   Whether the feature is the scrfeature, 'as_parent', or feature, 'as_child'
- * @param $aggregate
- *   Whether or not to get the locations for related features
- *
- * @ingroup tripal_feature
- */
-function chado_get_featurelocs($feature_id, $side = 'as_parent', $aggregate = 1) {
-
-  $sql = "
-    SELECT
-       F.name, F.feature_id, F.uniquename,
-       FS.name as src_name, FS.feature_id as src_feature_id, FS.uniquename as src_uniquename,
-       CVT.name as cvname, CVT.cvterm_id,
-       CVTS.name as src_cvname, CVTS.cvterm_id as src_cvterm_id,
-       FL.fmin, FL.fmax, FL.is_fmin_partial, FL.is_fmax_partial,FL.strand, FL.phase
-     FROM {featureloc} FL
-       INNER JOIN {feature} F   ON FL.feature_id = F.feature_id
-       INNER JOIN {feature} FS  ON FS.feature_id = FL.srcfeature_id
-       INNER JOIN {cvterm} CVT  ON F.type_id     = CVT.cvterm_id
-       INNER JOIN {cvterm} CVTS ON FS.type_id    = CVTS.cvterm_id
-       ";
-  if (strcmp($side, 'as_parent')==0) {
-    $sql .= "WHERE FL.srcfeature_id = :feature_id ";
-  }
-  if (strcmp($side, 'as_child')==0) {
-    $sql .= "WHERE FL.feature_id = :feature_id ";
-  }
-
-  $flresults = chado_query($sql, array(':feature_id' => $feature_id));
-
-  // copy the results into an array
-  $i=0;
-  $featurelocs = array();
-  while ($loc = $flresults->fetchObject()) {
-    // if a drupal entity exists for this feature then add the nid to the
-    // results object
-
-
-    // Get the bundle for this feature type, if one exists.
-    $ffeature = chado_generate_var('feature', array('feature_id' => $loc->feature_id));
-    $sfeature = chado_generate_var('feature', array('feature_id' => $loc->src_feature_id));
-    $fterm = tripal_load_term_entity(array(
-      'vocabulary' => $ffeature->type_id->dbxref_id->db_id->name,
-      'accession' => $ffeature->type_id->dbxref_id->accession,
-    ));
-    $sterm = tripal_load_term_entity(array(
-      'vocabulary' => $sfeature->type_id->dbxref_id->db_id->name,
-      'accession' => $sfeature->type_id->dbxref_id->accession,
-    ));
-
-    if($fterm) {
-      $fbundle = tripal_load_bundle_entity(array('term_id' => $fterm->id));
-      $loc->feid = chado_get_record_entity_by_bundle($fbundle, $loc->feature_id);
-    }
-    if ($sterm) {
-      $sbundle = tripal_load_bundle_entity(array('term_id' => $sterm->id));
-      $loc->seid = chado_get_record_entity_by_bundle($sbundle, $loc->src_feature_id);
-    }
-    // add the result to the array
-    $featurelocs[$i++] = $loc;
-  }
-
-  // Add the relationship feature locs if aggregate is turned on
-  if ($aggregate and strcmp($side, 'as_parent')==0) {
-  // get the relationships for this feature without substituting any children
-  // for the parent. We want all relationships
-  $relationships = _tripal_feature_get_aggregate_relationships($feature_id, 0);
-  foreach ($relationships as $rindex => $rel) {
-    // get the featurelocs for each of the relationship features
-    $rel_featurelocs = tripal_feature_load_featurelocs($rel->subject_id, 'as_child', 0);
-      foreach ($rel_featurelocs as $findex => $rfloc) {
-        $featurelocs[$i++] = $rfloc;
-      }
-    }
-  }
-
-  usort($featurelocs, 'chado_feature__residues_sort_locations');
-  return $featurelocs;
-}
-
-/**
- * Get features related to the current feature to a given depth. Recursive function.
- *
- * @param $feature_id
- * @param $substitute
- * @param $levels
- * @param $base_type_id
- * @param $depth
- *
- */
-function _tripal_feature_get_aggregate_relationships($feature_id, $substitute=1,
-    $levels=0, $base_type_id=NULL, $depth=0) {
-
-  // we only want to recurse to as many levels deep as indicated by the
-  // $levels variable, but only if this variable is > 0. If 0 then we
-  // recurse until we reach the end of the relationships tree.
-  if ($levels > 0 and $levels == $depth) {
-    return NULL;
-  }
-
-  // first get the relationships for this feature
-  return _tripal_feature_load_relationships($feature_id, 'as_object');
-
-}
-
-/**
- * Get the relationships for a feature.
- *
- * @param $feature_id
- *   The feature to get relationships for
- * @param $side
- *   The side of the relationship this feature is (ie: 'as_subject' or 'as_object')
- *
- */
-function _tripal_feature_load_relationships($feature_id, $side = 'as_subject') {
-  // Get the relationships for this feature.  The query below is used for both
-  // querying the object and subject relationships
-  $sql = "
-    SELECT
-      FS.name as subject_name, FS.uniquename as subject_uniquename,
-      CVTS.name as subject_type, CVTS.cvterm_id as subject_type_id,
-      FR.subject_id, FR.type_id as relationship_type_id, FR.object_id, FR.rank,
-      CVT.name as rel_type,
-      FO.name as object_name, FO.uniquename as object_uniquename,
-      CVTO.name as object_type, CVTO.cvterm_id as object_type_id
-    FROM {feature_relationship} FR
-     INNER JOIN {cvterm} CVT  ON FR.type_id    = CVT.cvterm_id
-     INNER JOIN {feature} FS  ON FS.feature_id = FR.subject_id
-     INNER JOIN {feature} FO  ON FO.feature_id = FR.object_id
-     INNER JOIN {cvterm} CVTO ON FO.type_id    = CVTO.cvterm_id
-     INNER JOIN {cvterm} CVTS ON FS.type_id    = CVTS.cvterm_id
-  ";
-  if (strcmp($side, 'as_object')==0) {
-    $sql .= " WHERE FR.object_id = :feature_id";
-  }
-  if (strcmp($side, 'as_subject')==0) {
-    $sql .= " WHERE FR.subject_id = :feature_id";
-  }
-  $sql .= " ORDER BY FR.rank";
-
-  // Get the relationships.
-  $results = chado_query($sql, array(':feature_id' => $feature_id));
-
-  // Iterate through the relationships, put these in an array and add
-  // in the Drupal node id if one exists.
-  $i=0;
-  $nodesql = "SELECT nid FROM {chado_feature} WHERE feature_id = :feature_id";
-  $relationships = array();
-  while ($rel = $results->fetchObject()) {
-    $node = db_query($nodesql, array(':feature_id' => $rel->subject_id))->fetchObject();
-    if ($node) {
-      $rel->subject_nid = $node->nid;
-    }
-    $node = db_query($nodesql, array(':feature_id' => $rel->object_id))->fetchObject();
-    if ($node) {
-      $rel->object_nid = $node->nid;
-    }
-    $relationships[$i++] = $rel;
-  }
-  return $relationships;
-}
-/**
-  * Used to sort the list of relationship parts by start position
-  *
-  * @ingroup tripal_feature
-  */
-function chado_feature__residues_sort_rel_parts_by_start($a, $b) {
-  foreach ($a as $type_name => $details) {
-    $astart = $a[$type_name]['start'];
-    break;
-  }
-  foreach ($b as $type_name => $details) {
-    $bstart = $b[$type_name]['start'];
-    break;
-  }
-  return strnatcmp($astart, $bstart);
-}
-/**
- * Used to sort the feature locs by start position
- *
- * @param $a
- *   One featureloc record (as an object)
- * @param $b
- *   The other featureloc record (as an object)
- *
- * @return
- *   Which feature location comes first
- *
- * @ingroup tripal_feature
- */
-function chado_feature__residues_sort_locations($a, $b) {
-  return strnatcmp($a->fmin, $b->fmin);
-}
-

+ 1522 - 0
tripal_chado/api/modules/tripal_chado.module.DEPRECATED.api.inc

@@ -0,0 +1,1522 @@
+<?php
+
+/**
+ * @file
+ *
+ * These api functions are deprecated, if your site is currently using them
+ * please update your code with the newer tripal_chado functions.
+ */
+
+/**
+ * @defgroup tripal_chado_module_DEPRECATED_api
+ * @ingroup tripal_chado_api
+ * @{
+ * Deprecated legacy api code.
+ * @}
+ */
+
+
+/**tripal_analysis_api*/
+/**
+ * Retrieves a chado analysis variable.
+ *
+ * @param $itentifier
+ *   an array with the key stating what the identifier is. Supported keys 
+ *   (only on of the following unique keys is required):
+ *    - analysis_id: the chado analysis.analysis_id primary key.
+ *    - nid: the drupal node.nid primary key.
+ *   There are also some specially handled keys. They are:
+ *    - property: An array/object describing the property to select records for. 
+ *      It should at least have either a type_name (if unique across cvs) or 
+ *      type_id. Other supported keys include: cv_id/cv_name (of the type), 
+ *      value and rank.
+ * @param $options
+ *   An array of options. Supported keys include:
+ *     - Any keys supported by chado_generate_var(). See that function 
+ *       definition for additional details.
+ *
+ * NOTE: the $identifier parameter can really be any array similar to $values 
+ * passed into chado_select_record(). It should fully specify the stock record 
+ * to be returned.
+ *
+ * @return
+ *   the analysis node matching the passed in identifier
+ *
+ * @ingroup tripal_chado_module_DEPRECATED_api
+ */
+function tripal_get_analysis($identifier, $options) {
+  return chado_get_analysis($identifier, $options);
+}
+
+/**
+ * Returns a list of analyses that are currently synced with Drupal to use in 
+ * select lists.
+ *
+ * @param $syncd_only
+ *   Whether or not to return all chado analyses or just those sync'd with 
+ *   drupal. Defaults to TRUE (only sync'd analyses).
+ * @return
+ *   An array of analyses sync'd with Drupal where each value is the analysis 
+ *   scientific name and the keys are analysis_id's.
+ *
+ * @ingroup tripal_chado_module_DEPRECATED_api
+ */
+function tripal_get_analysis_select_options($syncd_only = true) {
+  return chado_get_analysis_select_options($syncd_only);
+}
+
+/**tripal_contact_api*/
+/**
+ * Adds a contact to the Chado contact table.
+ *
+ * @param $values
+ *   An array of values to be inserted. Valid keys include:
+ *   - name: The name of the contact.
+ *   - description: Text describing the contact.
+ *   - type_name: The type of contact.  Must be a term in the tripal_contact 
+ *     vocabulary.
+ *   - properties: An associative array containing a list of key value pairs for
+ *     the properites. The key's must be valid terms in the tripal_contact 
+ *     vocabulary (e.g. Affiliation, Address, etc).
+ *
+ * @return
+ *   On success, an array is returned containing the fields of the contact
+ *   record including the newly added contact_id. On failure, FALSE is
+ *   returned.
+ *
+ * @ingroup tripal_chado_module_DEPRECATED_api
+ */
+function tripal_insert_contact($values) {
+  return chado_insert_contact($values);
+}
+
+/**
+ * This function is intended to be used in autocomplete forms for contacts.
+ *
+ * @param $text
+ *   The string to search for.
+ *
+ * @return
+ *   A json array of terms that begin with the provided string.
+ *
+ * @ingroup tripal_chado_module_DEPRECATED_api
+ */
+function tripal_autocomplete_contact($text) {
+  return chado_autocomplete_contact($text);
+}
+
+/**tripal_chado_cv_api*/
+/**
+ * Retrieves a chado controlled vocabulary variable
+ *
+ * @param $identifier
+ *   An array with the key stating what the identifier is. Supported keys (only 
+ *   on of the following unique keys is required):
+ *    - cv_id: the chado cv.cv_id primary key.
+ *    - name: the chado cv.name field (assume unique).
+ * @param $options
+ *   An array of options. Supported keys include:
+ *     - Any keys supported by chado_generate_var(). See that function 
+ *       definition fot additional details.
+ *
+ * NOTE: the $identifier parameter can really be any array similar to $values 
+ * passed into chado_select_record(). It should fully specify the cv record to 
+ * be returned.
+ *
+ * @return
+ *   If unique values were passed in as an identifier then an object describing 
+ *   the cv will be returned (will be a chado variable from 
+ *   chado_generate_var()). Otherwise, FALSE will be returned.
+ *
+ * @ingroup tripal_chado_module_DEPRECATED_api
+ */
+function tripal_get_cv($identifiers, $options = array()) {
+  return chado_get_cv($identifiers, $options);
+}
+
+/**
+ * Create an options array to be used in a form element which provides a
+ * list of all chado cvs.
+ *
+ * @return
+ *   An array(cv_id => name) for each cv in the chado cv table.
+ *
+ * @ingroup tripal_chado_module_DEPRECATED_api
+ */
+function tripal_get_cv_select_options() {
+  return chado_get_cv_select_options();
+}
+
+/**
+ * Retrieves a chado controlled vocabulary term variable.
+ *
+ * @param $identifier
+ *   An array apropriate for use with the chado_generate_var for uniquely
+ *   identifying a cvterm record. Alternativley, there are also some specially
+ *   handled keys. They are:
+ *    - id: an ID for the term of the for [dbname]:[accession], where [dbname]
+ *      is the short name of the vocabulary and accession is the unique ID.
+ *    - cv_id:  an integer indicating the cv_id or an array with 'name' => the
+ *      name of the cv.
+ *    - synonym: an array with 'name' => the name of the synonym of the cvterm
+ *      you want returned; 'cv_id' => the cv_id of the synonym; 'cv_name' =>
+ *      the name of the cv of the synonym.
+ *    - property: An array/object describing the property to select records
+ *      for. It should at least have either a type_name (if unique across cvs)
+ *      or type_id. Other supported keys include: cv_id/cv_name (of the type),
+ *      value and rank.
+ * @param $options
+ *   An array of options. Supported keys include:
+ *     - Any keys supported by chado_generate_var(). See that function
+ *       definition for additional details.
+ *
+ * NOTE: the $identifier parameter can really be any array similar to $values
+ *   passed into chado_select_record(). It should fully specify the cvterm
+ *   record to be returned.
+ *
+ * @return
+ *   If unique values were passed in as an identifier then an object describing
+ *   the cvterm will be returned (will be a chado variable from
+ *   chado_generate_var()). Otherwise, FALSE will be returned.
+ *
+ * @ingroup tripal_chado_module_DEPRECATED_api
+ */
+function tripal_get_cvterm($identifiers, $options = array()) {
+  return chado_get_cvterm($identifiers, $options);
+}
+
+/**
+ * Create an options array to be used in a form element
+ *   which provides a list of all chado cvterms.
+ *
+ * @param $cv_id
+ *   The chado cv_id; only cvterms with the supplied cv_id will be returnedl.
+ * @param $rel_type
+ *   Set to TRUE if the terms returned should only be relationship types in
+ *   the vocabulary.  This is useful for creating drop-downs of terms
+ *   used for relationship linker tables.
+ *
+ * @return
+ *   An associative array with the cvterm_id's as keys. The first
+ *   element in the array has a key of '0' and a value of 'Select a Type'.
+ *
+ * @ingroup tripal_chado_module_DEPRECATED_api
+ */
+function tripal_get_cvterm_select_options($cv_id, $rel_type = false) {
+  return chado_get_cvterm_select_options($cv_id, $rel_type);
+}
+
+/**
+ * Duplicate of fill_cvtermpath() stored procedure in Chado.
+ *
+ * Identifies all of the root terms of the controlled vocabulary. These
+ * root terms are then processed by calling the
+ * chado_update_cvtermpath_root_loop() function on each one.
+ *
+ * @param $cvid
+ *   The controlled vocabulary ID from the cv table of Chado (i.e. cv.cv_id).
+ * @param $job_id
+ *
+ * @ingroup tripal_chado_module_DEPRECATED_api
+ */
+function tripal_update_cvtermpath($cv_id, $job_id = null) {
+  return chado_update_cvtermpath($cv_id, $job_id);
+}
+
+/**
+ * Adds a controlled vocabulary to the CV table of Chado.
+ *
+ * @param $name
+ *   The name of the controlled vocabulary. These are typically all lower case
+ *   with no special characters other than an undrescore (for spaces).
+ * @param $comment
+ *   A description or definition of the vocabulary.
+ *
+ * @return
+ *   An object populated with fields from the newly added database.
+ *
+ * @ingroup tripal_chado_module_DEPRECATED_api
+ */
+function tripal_insert_cv($name, $definition) {
+  return chado_insert_cv($name, $definition);
+}
+
+/**
+ *  Add's a controlled vocabulary term to Chado.
+ *
+ *  This function will add a cvterm record (and a dbxref record if appropriate
+ *  values are provided). If the parent vocabulary does not exist then
+ *  that also is added to the cv table.  If the cvterm is a relationship term
+ *  then the 'is_relationship' value should be set.  All
+ *  terms must also have a corresponding database.  This is specified in the
+ *  term's ID just before the colon (e.g. GO:003824).  If the database does not
+ *  exist in the DB table then it will be added automatically.  The accession
+ *  (the value just after the colon in the term's ID) will be added to the
+ *  dbxref table.  If the CVterm already exists and $update is set (default)
+ *  then the cvterm is updated.  If the CVTerm already exists and $update is
+ *  not set, then no changes are made and the CVTerm object is returned.
+ *
+ * @param $term
+ *   An associative array with the following keys:
+ *    - id: the term accession. must be of the form <DB>:<ACCESSION>, where
+ *      <DB> is the name of the database to which the cvterm belongs and the
+ *      <ACCESSION> is the term's accession number in the database.
+ *    - name: the name of the term. usually meant to be human-readable.
+ *    - is_obsolete: is present and set to 1 if the term is defunct.
+ *    - definition: the definition of the term.
+ *    - cv_name: The CV name to which the term belongs.  If this arugment is
+ *        null or not provided then the function tries to find a record in the
+ *        CV table with the same name provided in the $term[namespace].  If
+ *        this field is provided then it overrides what the value in
+ *        $term[namespace].
+ *    - is_relationship: If this term is a relationship term then this value
+ *        should be 1.
+ *    - db_name: In some cases the database name will not be part of the
+ *        $term['id'] and it needs to be explicitly set.  Use this argument
+ *        only if the database name cannot be specififed in the term ID
+ *        (e.g. <DB>:<ACCESSION>).
+ * @param $options
+ *   An associative array with the following keys:
+ *    - update_existing: By default this is TRUE.  If the term exists it is
+ *      automatically updated.
+ *
+ * @return
+ *   A cvterm object
+ *
+ * @ingroup tripal_chado_module_DEPRECATED_api
+ */
+function tripal_insert_cvterm($term, $options = array()) {
+  return chado_insert_cvterm($term, $options);
+}
+
+/**
+ * TODO: deprecate this function
+ *
+ * Avoid using this function as it will be deprecated in future releases.
+ * 
+ * This function allows other modules to programatically
+ * submit an ontology for loading into Chado.
+ *
+ * This function will add a job to the Jobs subsystem for parsing the ontology.
+ * You can either pass a known OBO ID to the function or the URL
+ * or full path the the ontology file.  If a URL or file name is
+ * passed then the $obo_name argument must also be provided.  If
+ * this is the first time the ontology has been provided to Tripal
+ * then it will be added to the database and will be assigned a
+ * unique OBO ID.
+ *
+ * @param $obo_id
+ *   If the ontology is already loaded into the Tripal tables then
+ *   use this argument to specify the unique ID for the ontology
+ *   that will be loaded.
+ * @param $obo_name
+ *   If the OBO has not been added before then use this argument
+ *   to specify the human readable name of the ontology.
+ * @param $obo_url
+ *   If the OBO to be loaded is located on a remote server then
+ *   use this argument to provide the URL.
+ * @param $obo_file
+ *   If the OBO is housed on the local file system of the server then
+ *   use this argument to specify the full path.
+ *
+ * @return
+ *   returns the job_id of the submitted job or FALSE if the job was not added
+ *
+ * @ingroup tripal_chado_module_DEPRECATED_api
+ */
+function tripal_submit_obo_job($obo) {
+  return chado_submit_obo_job($obo);
+}
+
+/**
+ * Add the OBO to the tripal_cv_obo table in the Drupal database.
+ *
+ * If the OBO name already exists in the table then the path is updated.
+ *
+ * @param $name
+ *   The human readable name of this ontology.
+ * @param $path
+ *   The file path or URL of the ontology.
+ *
+ * @return
+ *   Returns the ontology ID.
+ *
+ * @ingroup tripal_chado_module_DEPRECATED_api
+ */
+function tripal_insert_obo($name, $path) {
+  return chado_insert_obo($name, $path);
+}
+
+/**
+ * Retrieves an OBO record.
+ *
+ * @param $values
+ *   An associate array with the following allowed keys: obo_id, name.
+ *
+ * @return
+ *   An instance of an OBO record object.
+ * 
+ * @ingroup tripal_chado_module_DEPRECATED_api
+ */
+function tripal_get_obo($values) {
+  return chado_get_obo($values);
+}
+
+/**
+ * This function is intended to be used in autocomplete forms.
+ *
+ * This function searches for a matching controlled vobulary name.
+ *
+ * @param $string
+ * The string to search for.
+ *
+ * @return
+ * A json array of terms that begin with the provided string.
+ *
+ * @ingroup tripal_chado_module_DEPRECATED_api
+ */
+function tripal_autocomplete_cv($string = '') {
+  return chado_autocomplete_cv($string);
+}
+
+/**
+ * This function is intended to be used in autocomplete forms
+ * for searching for CV terms that begin with the provided string.
+ *
+ * @param $cv_id
+ * The CV ID in which to search for the term.
+ * @param $string
+ * The string to search for.
+ *
+ * @return
+ * A json array of terms that begin with the provided string.
+ *
+ * @ingroup tripal_chado_module_DEPRECATED_api
+ */
+function tripal_autocomplete_cvterm($cv_id, $string = '') {
+  return chado_autocomplete_cvterm($cv_id, $string);
+}
+
+/**
+ * Add a record to a cvterm linking table (ie: feature_cvterm).
+ *
+ * @param $basetable
+ *   The base table to which the cvterm should be linked/associated. Thus to 
+ *   associate a cvterm to a feature the basetable=feature and cvterm_id is
+ *   added to the feature_cvterm table.
+ * @param $record_id
+ *   The primary key of the basetable to associate the cvterm with. This should 
+ *   be in integer.
+ * @param $cvterm
+ *   An associative array describing the cvterm. Valid keys include:
+ *     - name: the name for the cvterm,
+ *     - cv_name: the name of the cv the cvterm belongs to.
+ *     - cv_id: the primary key of the cv the cvterm belongs to.
+ * @param $options
+ *   An associative array of options. Valid keys include:
+ *     - insert_cvterm: Insert the cvterm if it doesn't already exist. FALSE is 
+ *       the default.
+ *
+ * @ingroup tripal_chado_module_DEPRECATED_api
+ */
+function tripal_associate_cvterm($basetable, $record_id, $cvterm, $options = array()) {
+  return chado_associate_cvterm($basetable, $record_id, $cvterm, $options);
+}
+
+/**tripal_chado_database_api*/
+/**
+ * Retrieves a chado db variable.
+ *
+ * Example Usage:
+ * @code
+ *   $select_values = array(
+ *     'name' => 'SOFP'
+ *   );
+ *   $db_object = tripal_get_db($select_values);
+ * @endcode
+ *  The above code selects the SOFP db and returns the following object:
+ * @code
+ *   $db_object = stdClass Object (
+ *     [db_id] => 49
+ *     [name] => SOFP
+ *     [description] =>
+ *     [urlprefix] =>
+ *     [url] =>
+ *   );
+ * @endcode
+ *
+ * @param $identifier
+ *   An array with the key stating what the identifier is. Supported keys (only 
+ *   on of the following unique keys is required):
+ *    - db_id: the chado db.db_id primary key.
+ *    - name: the chado db.name field (assume unique).
+ * @param $options
+ *   An array of options. Supported keys include:
+ *     - Any keys supported by chado_generate_var(). See that function 
+ *       definition for additional details.
+ *
+ * NOTE: the $identifier parameter can really be any array similar to $values 
+ * passed into chado_select_record(). It should fully specify the db record to 
+ * be returned.
+ *
+ * @return
+ *   If unique values were passed in as an identifier then an object describing 
+ *   the cv will be returned (will be a chado variable from 
+ *   chado_generate_var()). Otherwise, an array of objects will be returned.
+ *
+ * @ingroup tripal_chado_module_DEPRECATED_api
+ */
+function tripal_get_db($identifiers, $options = array()) {
+  return chado_get_db($identifiers, $options);
+}
+
+/**
+ * Create an options array to be used in a form element
+ *   which provides a list of all chado dbs.
+ *
+ * @return
+ *   An array(db_id => name) for each db in the chado db table.
+ *
+ * @ingroup tripal_chado_module_DEPRECATED_api
+ */
+function tripal_get_db_select_options() {
+  return chado_get_db_select_options();
+}
+
+/**
+ * Retrieves a chado database reference variable.
+ *
+ * Example Usage:
+ * @code
+ *   $identifiers = array(
+ *     'accession' => 'synonym',
+ *     'db_id' => array(
+ *       'name' => 'SOFP'
+ *     )
+ *   );
+ *   $dbxref_object = tripal_get_dbxref($identifiers);
+ * @endcode
+ *  The above code selects the synonym database reference and returns the 
+ *  following object:
+ * @code
+ *  $dbxref_object = stdClass Object (
+ *     [dbxref_id] => 2581
+ *     [accession] => synonym
+ *     [description] =>
+ *     [version] =>
+ *     [db_db_id] => 49
+ *     [db_name] => SOFP
+ *     [db_description] =>
+ *     [db_urlprefix] =>
+ *     [db_url] =>
+ *   );
+ * @endcode
+ *
+ * @param $identifier
+ *   An array apropriate for use with the chado_generate_var for uniquely
+ *   identifying a dbxref record. Alternatively, there are also some specially
+ *   handled keys. They are:
+ *    - property: An array/object describing the property to select records for. 
+ *      It should at least have either a type_name (if unique across cvs) or 
+ *      type_id. Other supported keys include: cv_id/cv_name (of the type), 
+ *      value and rank.
+ * @param $options
+ *   An array of options. Supported keys include:
+ *     - Any keys supported by chado_generate_var(). See that function 
+ *       definition for additional details.
+ *
+ * NOTE: the $identifier parameter can really be any array similar to $values 
+ * passed into chado_select_record(). It should fully specify the dbxref record 
+ * to be returned.
+ *
+ * @return
+ *   If unique values were passed in as an identifier then an object describing 
+ *   the dbxref will be returned (will be a chado variable from 
+ *   chado_generate_var()). Otherwise, FALSE will be returned.
+ *
+ * @ingroup tripal_chado_module_DEPRECATED_api
+ */
+function tripal_get_dbxref($identifiers, $options = array()) {
+  return chado_get_dbxref($identifiers, $options);
+}
+
+/**
+ * Generates a URL for the controlled vocabulary term.
+ *
+ * If the URL and URL prefix are provided for the database record of a cvterm
+ * then a URL can be created for the term.  By default, the db.name and
+ * dbxref.accession are concatenated and appended to the end of the db.urlprefix.
+ * But Tripal supports the use of {db} and {accession} tokens when if present
+ * in the db.urlprefix string will be replaced with the db.name and
+ * dbxref.accession respectively.
+ *
+ * @param $dbxref
+ *   A dbxref object as created by the chado_generate_var() function.
+ *
+ * @return
+ *   A string containing the URL.
+ * 
+ * @ingroup tripal_chado_module_DEPRECATED_api
+ */
+function tripal_get_dbxref_url($dbxref) {
+  return chado_get_dbxref_url($dbxref);
+}
+
+/**
+ * Adds a new database to the Chado DB table and returns the DB object.
+ *
+ * @param $values
+ *   An associative array of the values of the db (those to be inserted):
+ *   - name: The name of the database. This name is usually used as the prefix 
+ *     for CV term accessions.
+ *   - description: (Optional) A description of the database.  By default no 
+ *     description is required.
+ *   - url: (Optional) The URL for the database.
+ *   - urlprefix: (Optional) The URL that is to be used as a prefix when 
+ *     constructing a link to a database term.
+ * @param $options
+ *   Optional. An associative array of options that can include:
+ *   - update_existing: Set this to '1' to force an update of the database if it
+ *     already exists. The default is to not update. If the database exists
+ *     then nothing is added.
+ *
+ * @return
+ *   An object populated with fields from the newly added database.  If the
+ *   database already exists it returns the values in the current entry.
+ *
+ * @ingroup tripal_chado_module_DEPRECATED_api
+ */
+function tripal_insert_db($values, $options = array()) {
+  return chado_insert_db($values, $options);
+}
+
+/**
+ * Add a database reference.
+ *
+ * @param $values
+ *   An associative array of the values to be inserted including:
+ *    - db_id: the database_id of the database the reference is from.
+ *    - accession: the accession.
+ *    - version: (Optional) The version of the database reference.
+ *    - description: (Optional) A description of the database reference.
+ *
+ * @return
+ *   The newly inserted dbxref as an object, similar to that returned by
+ *   the chado_select_record() function.
+ *
+ * @ingroup tripal_chado_module_DEPRECATED_api
+ */
+function tripal_insert_dbxref($values) {
+  return chado_insert_dbxref($values);
+}
+
+/**
+ * Add a record to a database reference linking table (ie: feature_dbxref).
+ *
+ * @param $basetable
+ *   The base table for which the dbxref should be associated. Thus to associate 
+ *   a dbxref with a feature the basetable=feature and dbxref_id is added to the
+ *   feature_dbxref table.
+ * @param $record_id
+ *   The primary key of the basetable to associate the dbxref with. This should 
+ *   be in integer.
+ * @param $dbxref
+ *   An associative array describing the dbxref. Valid keys include: 
+ *   'accession' => the accession for the dbxref, 'db_name' => the name of the 
+ *    database the dbxref belongs to.
+ *   'db_id' => the primary key of the database the dbxref belongs to.
+ * @param $options
+ *   An associative array of options. Valid keys include:
+ *    - insert_dbxref: Insert the dbxref if it doesn't already exist. TRUE is 
+ *      the default.
+ *
+ * @ingroup tripal_chado_module_DEPRECATED_api
+ */
+function tripal_associate_dbxref($basetable, $record_id, $dbxref, $options = array()) {
+  return chado_associate_dbxref($basetable, $record_id, $dbxref, $options);
+}
+
+/**
+ * This function is intended to be used in autocomplete forms
+ * for searching for accession that begin with the provided string.
+ *
+ * @param $db_id
+ *   The DB ID in which to search for the term.
+ * @param $string
+ *   The string to search for.
+ *
+ * @return
+ *   A json array of terms that begin with the provided string.
+ *
+ * @ingroup tripal_chado_module_DEPRECATED_api
+ */
+function tripal_autocomplete_dbxref($db_id, $string = '') {
+  return chado_autocomplete_dbxref($db_id, $string);
+}
+
+/**tripal_feature_api*/
+/**
+ * Used for autocomplete in forms for identifying for publications.
+ *
+ * @param $field
+ *   The field in the publication to search on.
+ * @param $string
+ *   The string to search for.
+ *
+ * @return
+ *   A json array of terms that begin with the provided string.
+ *
+ * @ingroup tripal_chado_module_DEPRECATED_api
+ */
+function tripal_autocomplete_feature($string = '') {
+  return chado_autocomplete_feature($string);
+}
+
+/**
+ * Performs a reverse compliment of a nucleotide sequence.
+ *
+ * @param $sequence
+ *   The nucelotide sequence.
+ *
+ * @return
+ *   an upper-case reverse complemented sequence.
+ *
+ * @ingroup tripal_chado_module_DEPRECATED_api
+ */
+function tripal_reverse_compliment_sequence($sequence) {
+  return chado_reverse_compliment_sequence($sequence);
+}
+
+/**
+ * Retrieves the sequences for a given feature.
+ *
+ * If a feature has multiple alignments or multiple relationships then
+ * multiple sequences will be returned.
+ *
+ * @param $feature
+ *   An associative array describing the feature. Valid keys include:
+ *    - feature_id: The feature_id of the feature for which the sequence will
+ *      be retrieved.
+ *    - name: The feature name. This will appear on the FASTA definition line.
+ *    - parent_id:  (optional) only retrieve a sequence if 'derive_from_parent'
+ *      is true and the parent matches this ID.
+ *    - featureloc_id: (optional) only retrieve a sequence if 
+ *      'derive_from_parent' is true and the alignment is defined with this 
+ *      featureloc_id.
+ * @param $options
+ *   An associative array of options. Valid keys include:
+ *    - width: Indicate the number of bases to use per line.  A new line will
+ *      be added after the specified number of bases on each line.
+ *    - is_html: Set to '1' if  the sequence is meant to be displayed on a web
+ *      page. This will cause a <br> tag to separate lines of the FASTA sequence.
+ *    - derive_from_parent: Set to '1' if the sequence should be obtained from
+ *      the parent to which this feature is aligned.
+ *    - aggregate: Set to '1' if the sequence should only contain sub features,
+ *      excluding intro sub feature sequence.  For example, set this option to
+ *      obtain just the coding sequence of an mRNA.
+ *    - upstream: An integer specifing the number of upstream bases to include
+ *      in the output.
+ *    - downstream: An integer specifying the number of downstream bases to
+ *      include in the output.
+ *    - sub_feature_types: Only include sub features (or child features) of
+ *      the types provided in the array.
+ *    - relationship_type: If a relationship name is provided (e.g. sequence_of)
+ *      then any sequences that are in relationships of this type with matched
+ *      sequences are also included.
+ *    - relationship_part: If a relationship is provided in the preceeding
+ *      argument then the rel_part must be either 'object' or 'subject' to
+ *      indicate which side of the relationship the matched features belong.
+ *
+ * @return
+ *   an array of matching sequence in the following keys for each sequence:
+ *    - types: an array of feature types that were used to derive
+ *      the sequence (e.g. from an aggregated sequence)
+ *    - upstream: the number of upstream bases included in the sequence
+ *    - downstream: the number of downstream bases included in the
+ *      sequence
+ *    - defline: the definintion line used to create a FASTA sequence
+ *    - residues: the residues
+ *    - featureloc_id: the featureloc_id if the sequences is from an
+ *        alignment
+ *
+ * @ingroup tripal_chado_module_DEPRECATED_api
+ */
+function tripal_get_feature_sequences($feature, $options) {
+  return chado_get_feature_sequences($feature, $options);
+}
+
+/**
+ * Retrieves the bulk sequences for a given feature.
+ *
+ * @param $options
+ *   An associative array of options for selecting a feature. Valid keys include:
+ *    - org_commonname: The common name of the organism for which sequences
+ *      should be retrieved
+ *    - genus: The genus of the organism for which sequences should be retrieved
+ *    - species: The species of the organism for which sequences should be
+ *      retrieved
+ *    - analysis_name: The name of an analysis to which sequences belong. Only
+ *      those that are associated with the analysis will be retrieved.
+ *    - type: The type of feature (a sequence ontology term).
+ *    - feature_name: the name of the feature. Can be an array of feature names.
+ *    - feature_uname: the uniquename of the feature.  Can be an array of
+ *      feature unique names.
+ *    - upstream: An integer specifing the number of upstream bases to include
+ *      in the output
+ *    - downstream: An integer specifying the number of downstream bases to
+ *      include in the output.
+ *    - derive_from_parent: Set to '1' if the sequence should be obtained from
+ *      the parent to which this feature is aligned.
+ *    - aggregate: Set to '1' if the sequence should only contain sub features,
+ *      excluding intro sub feature sequence.  For example, set this option to
+ *      obtain just the coding sequence of an mRNA.
+ *    - sub_feature_types: Only include sub features (or child features) of
+ *      the types provided in the array
+ *    - relationship_type: If a relationship name is provided (e.g. sequence_of)
+ *      then any sequences that are in relationships of this type with matched
+ *      sequences are also included
+ *    - relationship_part: If a relationship is provided in the preceeding
+ *      argument then the rel_part must be either 'object' or 'subject' to
+ *      indicate which side of the relationship the matched features belong
+ *    - width: Indicate the number of bases to use per line.  A new line will
+ *      be added after the specified number of bases on each line.
+ *    - is_html: Set to '1' if  the sequence is meant to be displayed on a
+ *      web page. This will cause a <br> tag to separate lines of the FASTA
+ *      sequence.
+ * @return
+ *   Returns an array of sequences. The sequences will be in an array with the
+ *   following keys for each sequence:
+ *      'types'         => an array of feature types that were used to derive
+ *         the sequence (e.g. from an aggregated sequence)
+ *      'upstream'      => the number of upstream bases in the sequence
+ *      'downstream'    => the number of downstream bases in the sequence
+ *      'defline'       => the definintion line used to create a FASTA sequence
+ *      'residues'      => the residues
+ *      'featureloc_id' => the featureloc_id if from an alignment
+ *
+ * @ingroup tripal_chado_module_DEPRECATED_api
+ */
+function tripal_get_bulk_feature_sequences($options) {
+  return chado_get_bulk_feature_sequences($options);
+}
+
+/**
+ * Returns a definition line that can be used in a FASTA file.
+ *
+ * @param $feature
+ *   A single feature object containing all the fields from the chado.feature 
+ *   table. Best case is to provide an object generated by the 
+ *   chado_generate_var() function.
+ * @param $notes
+ *   Optional: additional notes to be added to the definition line.
+ * @param $featureloc
+ *   Optional: a single featureloc object generated using chado_generate_var
+ *   that contains a record from the chado.featureloc table. Provide this if the
+ *   sequence was obtained by using the alignment rather than from the 
+ *   feature.residues column.
+ * @param $type
+ *   Optional: the type of sequence. By default the feature type is used.
+ * @param $length
+ *   Optional: the length of the sequence.
+ *
+ * @return
+ *   A string of the format: uniquename|name|type|feature_id
+ *   or if an alignment:  srcfeature_name:fmin..fmax[+-]; alignment of 
+ *   uniquename|name|type|feature_id.
+ * 
+ * @ingroup tripal_chado_module_DEPRECATED_api
+ */
+function tripal_get_fasta_defline($feature, $notes = '', $featureloc = null, $type = '', $length = 0) {
+  return chado_get_fasta_defline($feature, $notes, $featureloc, $type, $length);
+}
+
+/**
+ * Returns a string representing a feature location in an alignment.
+ *
+ * @param $featureloc
+ *   A single featureloc object generated using chado_generate_var that
+ *   contains a record from the chado.featureloc table.
+ *
+ *  @return
+ *   A string of the format: uniquename:featurelocmin..featurelocmax.strand
+ * 
+ * @ingroup tripal_chado_module_DEPRECATED_api
+ */
+function tripal_get_location_string($featureloc) {
+  return chado_get_location_string($featureloc);
+}
+
+/**
+ * Retrieves a chado organism variable.
+ *
+ * @param $identifier
+ *   An array with the key stating what the identifier is. Supported keys (only 
+ *   on of the following unique keys is required):
+ *    - organism_id: the chado organism.organism_id primary key.
+ *    - genus & species: the chado organism.genus field & organism.species field.
+ *   There are also some specially handled keys. They are:
+ *    - property: An array/object describing the property to select records for. 
+ *      It should at least have either a type_name (if unique across cvs) or 
+ *      type_id. Other supported keys include: cv_id/cv_name (of the type), 
+ *      value and rank.
+ * @param $options
+ *   An array of options. Supported keys include:
+ *     - Any keys supported by chado_generate_var(). See that function 
+ *      definition for additional details.
+ *
+ * NOTE: the $identifier parameter can really be any array similar to $values 
+ * passed into chado_select_record(). It should fully specify the organism 
+ * record to be returned.
+ *
+ * @return
+ *   If unique values were passed in as an identifier then an object describing 
+ *   the organism will be returned (will be a chado variable from 
+ *   chado_generate_var()). Otherwise, FALSE will be returned.
+ *
+ * @ingroup tripal_chado_module_DEPRECATED_api
+ */
+function tripal_get_organism($identifiers, $options = array()) {
+  return chado_get_organism($identifiers, $options);
+}
+
+/**
+ * Returns the full scientific name of an organism.
+ *
+ * @param $organism
+ *   An organism object.
+ * @return
+ *   The full scientific name of the organism.
+ *
+ * @ingroup tripal_chado_module_DEPRECATED_api
+ */
+function tripal_get_organism_scientific_name($organism) {
+  return chado_get_organism_scientific_name($organism);
+}
+
+/**
+ * Returns a list of organisms that are currently synced with Drupal to use in 
+ * select lists.
+ *
+ * @param $syncd_only
+ *   Whether or not to return all chado organisms or just those sync'd with 
+ *   drupal. Defaults to TRUE (only sync'd organisms).
+ * @return
+ *   An array of organisms sync'd with Drupal where each value is the organism 
+ *   scientific name and the keys are organism_id's.
+ *
+ * @ingroup tripal_chado_module_DEPRECATED_api
+ */
+function tripal_get_organism_select_options($syncd_only = true) {
+  return chado_get_organism_select_options($syncd_only);
+}
+
+/**
+ * Return the path for the organism image.
+ *
+ * @param $organism
+ *   An organism table record.
+ *
+ * @return
+ *   If the type parameter is 'url' (the default) then the fully qualified
+ *   url to the image is returend. If no image is present then NULL is returned.
+ *
+ * @ingroup tripal_chado_module_DEPRECATED_api
+ */
+function tripal_get_organism_image_url($organism) {
+  return chado_get_organism_image_url($organism);
+}
+
+/**
+ * This function is intended to be used in autocomplete forms
+ * for searching for organisms that begin with the provided string.
+ *
+ * @param $text
+ *   The string to search for.
+ *
+ * @return
+ *   A json array of terms that begin with the provided string.
+ *
+ * @ingroup tripal_chado_module_DEPRECATED_api
+ */
+function tripal_autocomplete_organism($text) {
+  return chado_autocomplete_organism($text);
+}
+
+/**
+ * A handy function to abbreviate the infraspecific rank.
+ *
+ * @param $rank
+ *   The rank below species.
+ * @return
+ *   The proper abbreviation for the rank.
+ *
+ * @ingroup tripal_chado_module_DEPRECATED_api
+ */
+function tripal_abbreviate_infraspecific_rank($rank) {
+  return chado_abbreviate_infraspecific_rank($rank);
+}
+
+/** tripal_phylotree_api */
+/**
+ * Validates an $options array for insert or update of a phylotree record.
+ *
+ * If validation passes then any values that needed validation lookups
+ * (such as the dbxref, analysis, leaf_type, etc) will have their approriate
+ * primary_keys added to the $options array, and missing default values
+ * will also be added.
+ *
+ * @param $val_type
+ *   The type of validation. Can be either 'insert' or 'update'.
+ * @param $options
+ *   An array of key/value pairs containing any of the valid keys for
+ *   either the tripal_insert_phylotree() or tripal_update_phylotree()
+ *   functions.
+ * @param $errors
+ *   An empty array where validation error messages will be set. The keys
+ *   of the array will be name of the field from the options array and the
+ *   value is the error message.
+ * @param $warnings
+ *   An empty array where validation warning messagges will be set. The
+ *   warnings should not stop an insert or an update but should be provided
+ *   to the user as information by a drupal_set_message() if appropriate. The
+ *   keys of the array will be name of the field from the options array and the
+ *   value is the error message.
+ * @return
+ *   If validation failes then FALSE is returned.  Any options that do not pass
+ *   validation checks will be added in the $errors array with the key being
+ *   the option and the value being the error message.  If validation
+ *   is successful then TRUE is returned.
+ *
+ * @ingroup tripal_chado_module_DEPRECATED_api
+ */
+function tripal_validate_phylotree($val_type, &$options, &$errors, &$warnings) {
+  return chado_validate_phylotree($val_type, $options, $errors, $warnings); 
+}
+
+/**
+ * Inserts a phylotree record into Chado.
+ *
+ * This function validates the options passed prior to insertion of the record,
+ * and if validation passes then any values in the options array that needed
+ * validation lookups (such as the dbxref, analysis, leaf_type, etc) will have
+ * their approriate primary key values added to the options array.
+ *
+ * @param $options
+ *  An array of key value pairs with the following keys required:
+ *     'name':       The name of the tree. This will be displayed to users.
+ *     'description: A description about the tree
+ *     'anlaysis_id: The ID of the analysis to which this phylotree should be
+ *                   associated.
+ *     'analysis':   If the analysis_id key is not used then the analysis name
+ *                   may be provided to identify the analysis to which the tree
+ *                   should be associated.
+ *     'leaf_type':  A sequence ontology term or the word 'organism'. If the
+ *                   type is 'organism' then this tree represents a
+ *                   taxonomic tree.  The default, if not specified, is the
+ *                   term 'polypeptide'.
+ *     'tree_file':  The path of the file containing the phylogenetic tree to
+ *                   import or a Drupal managed_file numeric ID.
+ *     'format':     The file format. Currently only 'newick is supported'.
+ * 
+ *  Optional keys:
+ *     'dbxref':     A database cross-reference of the form DB:ACCESSION.
+ *                   Where DB is the database name, which is already present
+ *                   in Chado, and ACCESSION is the unique identifier for
+ *                   this tree in the remote database.
+ *     'name_re':    If the leaf type is NOT 'taxonomy', then the value of
+ *                   this field can be a regular expression to pull out
+ *                   the name of the feature from the node label in the
+ *                   intput tree. If no value is provided the entire label is
+ *                   used.
+ *     'match':      Set to 'uniquename' if the leaf nodes should be matched
+ *                   with the feature uniquename.
+ *     'load_now':   If set, the tree will be loaded immediately if a tree_file
+ *                   is provided. Otherwise, the tree will be loaded via
+ *                   a Tripal jobs call.
+ *     'no_load':    If set the tree file will not be loaded.
+ * @param $errors
+ *   An empty array where validation error messages will be set. The keys
+ *   of the array will be name of the field from the options array and the
+ *   value is the error message.
+ * @param $warnings
+ *   An empty array where validation warning messagges will be set. The
+ *   warnings should not stop an insert or an update but should be provided
+ *   to the user as information by a drupal_set_message() if appropriate. The
+ *   keys of the array will be name of the field from the options array and the
+ *   value is the error message.
+ * @return
+ *   TRUE for success and FALSE for failure.
+ *
+ * @ingroup tripal_chado_module_DEPRECATED_api
+ */
+function tripal_insert_phylotree(&$options, &$errors, &$warnings) {
+  return chado_insert_phylotree($options, $errors, $warnings);
+}
+
+/**
+ * Updates a phylotree record into Chado.
+ *
+ * This function validates the options passed prior to update of the record
+ * and if validation passes then any values in the options array that needed
+ * validation lookups (such as the dbxref, analysis, leaf_type, etc) will have
+ * their approriate primary key values added to the options array. A Drupal
+ * File object will be added to the options array for the tree file if one
+ * is provided.
+ *
+ *
+ * @param $phylotree_id
+ *   The ID of the phylotree to update.
+ * @param $options
+ *  An array of key value pairs with the following optional keys:
+ *     'name':       The name of the tree. This will be displayed to users.
+ *     'description: A description about the tree
+ *     'anlaysis_id: The ID of the analysis to which this phylotree should be
+ *                   associated.
+ *     'analysis':   If the analysis_id key is not used then the analysis name
+ *                   may be provided to identify the analysis to which the tree
+ *                   should be associated.
+ *     'leaf_type':  A sequence ontology term or the word 'organism'. If the
+ *                   type is 'organism' then this tree represents a
+ *                   taxonomic tree.  The default, if not specified, is the
+ *                   term 'polypeptide'.
+ *     'tree_file':  The path of the file containing the phylogenetic tree to
+ *                   import or a Drupal managed_file numeric ID.
+ *     'format':     The file format. Currently only 'newick is supported'
+ *     'dbxref':     A database cross-reference of the form DB:ACCESSION.
+ *                   Where DB is the database name, which is already present
+ *                   in Chado, and ACCESSION is the unique identifier for
+ *                   this tree in the remote database.
+ *     'name_re':    If the leaf type is NOT 'taxonomy', then the value of
+ *                   this field can be a regular expression to pull out
+ *                   the name of the feature from the node label in the
+ *                   intput tree. If no value is provided the entire label is
+ *                   used.
+ *     'match':      Set to 'uniquename' if the leaf nodes should be matched
+ *                   with the feature uniquename.
+ *     'load_now':   If set, the tree will be loaded immediately if a tree_file
+ *                   is provided. Otherwise, the tree will be loaded via
+ *                   a Tripal jobs call.
+ *
+ * @ingroup tripal_chado_module_DEPRECATED_api
+ */
+function tripal_update_phylotree($phylotree_id, &$options) {
+  return chado_update_phylotree($phylotree_id, $options);
+}
+
+/**
+ * Deletes a phylotree record from Chado.
+ *
+ * @param $phylotree_id
+ *
+ * @return
+ *   TRUE on success, FALSE on failure.
+ *
+ * @ingroup tripal_chado_module_DEPRECATED_api
+ */
+function tripal_delete_phylotree($phylotree_id) {
+  return chado_delete_phylotree($phylotree_id);
+}
+
+/**
+ * Iterates through the tree and sets the left and right indicies.
+ *
+ * @param $tree
+ *   The tree array.
+ * @param $index
+ *   This parameters is not used when the function is first called. It
+ *   is used for recursive calls.
+ *
+ * @ingroup tripal_chado_module_DEPRECATED_api
+ */
+function tripal_assign_phylogeny_tree_indices(&$tree, &$index = 1) {
+  return chado_assign_phylogeny_tree_indices($tree, $index);
+}
+
+/**
+ * Iterates through the tree array and creates phylonodes in Chado.
+ *
+ * The function iterates through the tree in a top-down approach adding
+ * parent internal nodes prior to leaf nodes.  Each node of the tree should have
+ * the following fields:
+ *
+ *   -name:         The name (or label) for this node.
+ *   -depth:        The depth of the node in the tree.
+ *   -is_root:      Set to 1 if this node is a root node.
+ *   -is_leaf:      Set to 1 if this node is a leaf node.
+ *   -is_internal:  Set to 1 if this node is an internal node.
+ *   -left_index:   The index of the node to the left in the tree.
+ *   -right_index:  The index of the node to the right in the tree.
+ *   -branch_set:   An array containing a list of nodes of that are children
+ *                  of the node.
+ *   -parent:       The name of the parent node.
+ *   -organism_id:  The organism_id for associtating the node with an organism.
+ *   -properties:   An array of key/value pairs where the key is the cvterm_id
+ *                  and the value is the property value.  These properties
+ *                  will be assocaited with the phylonode.
+ *
+ * Prior to importing the tree the indicies can be set by using the
+ * chado_assign_phylogeny_tree_indices() function.
+ *
+ * @param $tree
+ *   The tree array.
+ * @param $phylotree.
+ *   The phylotree object (from Chado).
+ * @param $options
+ *   The options provide some direction for how the tree is imported.  The
+ *   following keys can be used:
+ *   -taxonomy:  Set to 1 if this tree is a taxonomic tree. Set to 0
+ *               otherwise.
+ *   -leaf_type: Set to the leaf type name. If this is a non-taxonomic tree
+ *               that is associated with features, then this should be the
+ *               Sequence Ontology term for the feature (e.g. polypeptide).
+ *               If this is a taxonomic tree then this option is not needed.
+ *   -match:     Set to either 'name' or 'uniquename'.  This is used for
+ *               matching the feature name or uniquename with the node name.
+ *               This is not needed for taxonomic trees.
+ *   -match_re:  Set to a regular that can be used for matching the node
+ *               name with the feature name if the node name is not
+ *               identical to the feature name.
+ * @param $vocab
+ *   Optional. An array containing a set of key/value pairs that maps node
+ *   types to CV terms.  The keys must be 'root', 'internal' or 'leaf'.  If
+ *   no vocab is provded then the terms provided by the tripal_phylogeny
+ *   CV will be used.
+ * @param $parent
+ *   This argument is not needed when the funtion is first called. This
+ *   function is recursive and this argument is used on recursive calls.
+ *
+ * @ingroup tripal_chado_module_DEPRECATED_api
+ */
+function tripal_phylogeny_import_tree(&$tree, $phylotree, $options, $vocab = array(), $parent = null) {
+  return chado_phylogeny_import_tree($tree, $phylotree, $options, $vocab, $parent);
+}
+
+/**
+ * Get the vocabulary terms used to describe nodes in the tree.
+ *
+ * @return 
+ *  Array of vocab info or FALSE on failure.
+ * 
+ * @ingroup tripal_chado_module_DEPRECATED_api
+ */
+function tripal_phylogeny_get_node_types_vocab() {
+  return chado_phylogeny_get_node_types_vocab();
+}
+
+/**
+ * Imports a tree file.
+ *
+ * This function is used as a wrapper for loading a phylogenetic tree using
+ * any number of file loaders.
+ *
+ * @param $file_name
+ *   The name of the file containing the phylogenetic tree to import.
+ * @param $format
+ *   The format of the file. Currently only the 'newick' file format is
+ *   supported.
+ * @param $options
+ *   Options if the phylotree record already exists:
+ *     'phylotree_id': The imported nodes will be associated with this tree.
+ *     'leaf_type':  A sequence ontology term or the word 'organism'. If the
+ *                   type is 'organism' then this tree represents a
+ *                   taxonomic tree.  The default, if not specified, is the
+ *                   term 'polypeptide'.
+ *     'name_re':    If the leaf type is NOT 'taxonomy', then the value of
+ *                   this field can be a regular expression to pull out
+ *                   the name of the feature from the node label in the
+ *                   intput tree. If no value is provided the entire label is
+ *                   used.
+ *     'match':      Set to 'uniquename' if the leaf nodes should be matched
+ *                   with the feature uniquename.
+ *
+ *  @ingroup tripal_chado_module_DEPRECATED_api
+ */
+function tripal_phylogeny_import_tree_file($file_name, $format, $options = array(), $job_id = null) {
+  return chado_phylogeny_import_tree_file($file_name, $format, $options, $job_id);
+}
+
+/** tripal_pub_api */
+/**
+ * Retrieves a chado publication array.
+ *
+ * @param $identifier
+ *   An array used to uniquely identify a publication. This array has the same
+ *   format as that used by the chado_generate_var(). The following keys can be
+ *   useful for uniquely identifying a publication as they should be unique:
+ *    - pub_id: the chado pub.pub_id primary key.
+ *    - nid: the drupal nid of the publication.
+ *    - uniquename: A value to matach with the pub.uniquename field.
+ *   There are also some specially handled keys. They are:
+ *    - property: An array describing the property to select records for. It
+ *      should at least have either a 'type_name' key (if unique across cvs) or
+ *      'type_id' key. Other supported keys include: 'cv_id', 'cv_name' 
+ *      (of the type), 'value' and 'rank'
+ *    - dbxref: The database cross reference accession.  It should be in the 
+ *      form DB:ACCESSION, where DB is the database name and ACCESSION is the
+ *      unique publication identifier (e.g. PMID:4382934)
+ *    - dbxref_id:  The dbxref.dbxref_id of the publication.
+ * @param $options
+ *   An array of options. Supported keys include:
+ *     - Any keys supported by chado_generate_var(). See that function 
+ *       definition for additional details.
+ *
+ * NOTE: the $identifier parameter can really be any array similar to $values 
+ * passed into chado_select_record(). It should fully specify the pub record to 
+ * be returned.
+ *
+ * @return
+ *   If a singe publication is retreived using the identifiers, then a 
+ *   publication array will be returned.  The array is of the same format 
+ *   returned by the chado_generate_var() function. Otherwise, FALSE will be 
+ *   returned.
+ *
+ * @ingroup tripal_chado_module_DEPRECATED_api
+ */
+function tripal_get_publication($identifiers, $options = array()) {
+  return chado_get_publication($identifiers, $options);
+}
+
+/**
+ * The publication table of Chado only has a unique constraint for the
+ * uniquename of the publiation, but in reality a publication can be considered
+ * unique by a combination of the title, publication type, published year and
+ * series name (e.g. journal name or conference name). The site administrator
+ * can configure how publications are determined to be unique.  This function
+ * uses the configuration specified by the administrator to look for publications
+ * that match the details specified by the $pub_details argument
+ * and indicates if one ore more publications match the criteria.
+ *
+ * @param $pub_details
+ *   An associative array with details about the publications. The expected keys
+ *   are:
+ *     'Title':              The title of the publication.
+ *     'Year':               The published year of the publication.
+ *     'Publication Type':   An array of publication types. A publication can 
+ *                           have more than one type.
+ *     'Series Name':        The series name of the publication.
+ *     'Journal Name':       An alternative to 'Series Name'.
+ *     'Conference Name':    An alternative to 'Series Name'.
+ *     'Citation':           The publication citation (this is the value saved 
+ *                           in the pub.uniquename field and must be unique).
+ *   
+ *     If this key is present it will also be checked
+ *     'Publication Dbxref': A database cross reference of the form DB:ACCESSION 
+ *                           where DB is the name of the database and ACCESSION 
+ *                           is the unique identifier (e.g PMID:3483139).
+ *
+ * @return
+ *   An array containing the pub_id's of matching publications. Returns an
+ *   empty array if no pubs match.
+ *
+ * @ingroup tripal_chado_module_DEPRECATED_api
+ */
+function tripal_publication_exists($pub_details) {
+  return chado_publication_exists($pub_details);
+}
+
+/**
+ * Used for autocomplete in forms for identifying for publications.
+ *
+ * @param $field
+ *   The field in the publication to search on.
+ * @param $string
+ *   The string to search for.
+ *
+ * @return
+ *   A json array of terms that begin with the provided string.
+ *
+ * @ingroup tripal_chado_module_DEPRECATED_api
+ */
+function tripal_autocomplete_pub($string = '') {
+  return chado_autocomplete_pub($string);
+}
+
+/**
+ * Imports a singe publication specified by a remote database cross reference.
+ *
+ * @param $pub_dbxref
+ *   The unique database ID for the record to update.  This value must
+ *   be of the format DB_NAME:ACCESSION where DB_NAME is the name of the
+ *   database (e.g. PMID or AGL) and the ACCESSION is the unique identifier
+ *   for the record in the database.
+ * @param $do_contact
+ *   Set to TRUE if authors should automatically have a contact record added
+ *   to Chado.
+ * @param $do_update
+ *   If set to TRUE then the publication will be updated if it already exists
+ *   in the database.
+ *
+ * @ingroup tripal_chado_module_DEPRECATED_api
+ */
+function tripal_import_pub_by_dbxref($pub_dbxref, $do_contact = false, $do_update = true) {
+  return chado_import_pub_by_dbxref($pub_dbxref, $do_contact, $do_update);
+}
+
+/**
+ * Imports all publications for all active import setups.
+ *
+ * @param $report_email
+ *   A list of email address, separated by commas, that should be notified
+ *   once importing has completed.
+ * @param $do_update
+ *   If set to TRUE then publications that already exist in the Chado database
+ *   will be updated, whereas if FALSE only new publications will be added.
+ *
+ * @ingroup tripal_chado_module_DEPRECATED_api
+ */
+function tripal_execute_active_pub_importers($report_email = false, $do_update = false) {
+  return chado_execute_active_pub_importers($report_email, $do_update);
+}
+
+/**
+ * Updates publication records.
+ *
+ * Updates publication records that currently exist in the Chado pub table
+ * with the most recent data in the remote database.
+ *
+ * @param $do_contact
+ *   Set to TRUE if authors should automatically have a contact record added
+ *   to Chado. Contacts are added using the name provided by the remote
+ *   database.
+ * @param $dbxref
+ *   The unique database ID for the record to update.  This value must
+ *   be of the format DB_NAME:ACCESSION where DB_NAME is the name of the
+ *   database (e.g. PMID or AGL) and the ACCESSION is the unique identifier
+ *   for the record in the database.
+ * @param $db
+ *   The name of the remote database to update.  If this value is provided and
+ *   no dbxref then all of the publications currently in the Chado database
+ *   for this remote database will be updated.
+ *
+ * @ingroup tripal_chado_module_DEPRECATED_api
+ */
+function tripal_reimport_publications($do_contact = false, $dbxref = null, $db = null) {
+  return chado_reimport_publications($do_contact, $dbxref, $db);
+}
+
+/**
+ * Launch the Tripal job to generate citations.
+ *
+ * This function will recreate citations for all publications currently
+ * loaded into Tripal.  This is useful to create a consistent format for
+ * all citations.
+ *
+ * @param $options
+ *  Options pertaining to what publications to generate citations for.
+ *  One of the following must be present:
+ *   - all: Create and replace citation for all pubs.
+ *   - new: Create citation for pubs that don't already have one.
+ *
+ * @ingroup tripal_chado_module_DEPRECATED_api
+ */
+function tripal_pub_create_citations($options) {
+  return chado_pub_create_citations($options);
+}
+
+/**
+ * This function generates citations for publications.  It requires
+ * an array structure with keys being the terms in the Tripal
+ * publication ontology.  This function is intended to be used
+ * for any function that needs to generate a citation.
+ *
+ * @param $pub
+ *   An array structure containing publication details where the keys
+ *   are the publication ontology term names and values are the
+ *   corresponding details.  The pub array can contain the following
+ *   keys with corresponding values:
+ *     - Publication Type:  an array of publication types. a publication can 
+ *       have more than one type.
+ *     - Authors: a  string containing all of the authors of a publication.
+ *     - Journal Name:  a string containing the journal name.
+ *     - Journal Abbreviation: a string containing the journal name abbreviation.
+ *     - Series Name: a string containing the series (e.g. conference 
+ *       proceedings) name.
+ *     - Series Abbreviation: a string containing the series name abbreviation
+ *     - Volume: the serives volume number.
+ *     - Issue: the series issue number.
+ *     - Pages: the page numbers for the publication.
+ *     - Publication Date:  A date in the format "Year Month Day".
+ *
+ * @return
+ *   A text string containing the citation.
+ *
+ * @ingroup tripal_chado_module_DEPRECATED_api
+ */
+function tripal_pub_create_citation($pub) {
+  return chado_pub_create_citation($pub);
+}
+
+/**
+ * Retrieves the minimal information to uniquely describe any publication.
+ *
+ * The returned array is an associative array where the keys are
+ * the controlled vocabulary terms in the form [vocab]:[accession].
+ *
+ * @param $pub
+ *   A publication object as created by chado_generate_var().
+ *
+ * @return
+ *   An array with the following keys:  'Citation', 'Abstract', 'Authors',
+ *   'URL'. All keys are term names in the Tripal Publication Ontology :TPUB.
+ * 
+ * @ingroup tripal_chado_module_DEPRECATED_api
+ */
+function tripal_get_minimal_pub_info($pub) {
+  return chado_get_minimal_pub_info($pub);
+}
+
+
+/** tripal_stock_api */
+/**
+ * Retrieves a chado stock variable
+ *
+ * @param $identifier
+ *   An array with the key stating what the identifier is. Supported keys (only 
+ *   one of the following unique keys is required):
+ *    - stock_id: the chado stock.stock_id primary key
+ *    - nid: the drupal nid of the stock
+ *   There are also some specially handled keys. They are:
+ *    - property: An array/object describing the property to select records for. 
+ *      It should at least have either a type_name (if unique across cvs) or 
+ *      type_id. Other supported keys include: cv_id/cv_name (of the type), 
+ *      value and rank
+ * @param $options
+ *   An array of options. Supported keys include:
+ *     - Any keys supported by chado_generate_var(). See that function 
+ *      definition for additional details.
+ *
+ * NOTE: the $identifier parameter can really be any array similar to $values
+ * passed into chado_select_record(). It should fully specify the stock record 
+ * to be returned.
+ *
+ * @return
+ *   If unique values were passed in as an identifier then an object describing 
+ *   the stock will be returned (will be a chado variable from 
+ *   chado_generate_var()). Otherwise, FALSE will be returned.
+ *
+ * @ingroup tripal_chado_module_DEPRECATED_api
+ */
+function tripal_get_stock($identifiers, $options = array()) {
+  return chado_get_stock($identifiers, $options);
+}
+
+/**
+ * Retrieves a chado stock variable.
+ *
+ * @param $identifier
+ *   An array with the key stating what the identifier is. Supported keys 
+ *   include any field in the stock table. See the chado_select_record() $values
+ *   parameter for additional details including an example.
+ * @param $options
+ *   An array of options. Supported keys include:
+ *     - Any keys supported by chado_generate_var(). See that function 
+ *       definition for additional details.
+ *
+ * @return
+ *   An array of stock objects matching the criteria.
+ *
+ * @ingroup tripal_chado_module_DEPRECATED_api
+ */
+function tripal_get_multiple_stocks($identifiers, $options = array()) {
+  return chado_get_multiple_stocks($identifiers, $options);
+}

+ 60 - 52
tripal_chado/api/modules/tripal_chado.organism.api.inc

@@ -1,57 +1,62 @@
 <?php
 /**
  * @file
- * Provides an application programming interface (API) to manage organisms
+ * Provides API functions specificially for managing feature
+ * records in Chado.  
  */
 
 /**
  * @defgroup tripal_organism_api Chado Organism
  * @ingroup tripal_chado_api
  * @{
+ * Provides API functions specificially for managing organism
+ * records in Chado.
  * @}
  */
 
 /**
- * Retrieves a chado organism variable
+ * Retrieves a chado organism variable.
  *
  * @param $identifier
- *   An array with the key stating what the identifier is. Supported keys (only on of the
- *   following unique keys is required):
- *    - organism_id: the chado organism.organism_id primary key
- *    - genus & species: the chado organism.genus field & organism.species field
+ *   An array with the key stating what the identifier is. Supported keys (only 
+ *   on of the following unique keys is required):
+ *    - organism_id: the chado organism.organism_id primary key.
+ *    - genus & species: the chado organism.genus field & organism.species field.
  *   There are also some specially handled keys. They are:
- *    - property: An array/object describing the property to select records for. It
- *      should at least have either a type_name (if unique across cvs) or type_id. Other
- *      supported keys include: cv_id/cv_name (of the type), value and rank
+ *    - property: An array/object describing the property to select records for. 
+ *      It should at least have either a type_name (if unique across cvs) or 
+ *      type_id. Other supported keys include: cv_id/cv_name (of the type), 
+ *      value and rank.
  * @param $options
  *   An array of options. Supported keys include:
- *     - Any keys supported by chado_generate_var(). See that function definition for
- *       additional details.
+ *     - Any keys supported by chado_generate_var(). See that function 
+ *      definition for additional details.
  *
- * NOTE: the $identifier parameter can really be any array similar to $values passed into
- *   chado_select_record(). It should fully specify the organism record to be returned.
+ * NOTE: the $identifier parameter can really be any array similar to $values 
+ * passed into chado_select_record(). It should fully specify the organism 
+ * record to be returned.
  *
  * @return
  *   If unique values were passed in as an identifier then an object describing the organism
  *   will be returned (will be a chado variable from chado_generate_var()). Otherwise,
- *   FALSE will be returned.
+ *   NULL will be returned.
  *
  * @ingroup tripal_organism_api
  */
-function tripal_get_organism($identifiers, $options = array()) {
+function chado_get_organism($identifiers, $options = array()) {
 
-  // Set Defaults
+  // Set Defaults.
   if (!isset($options['include_fk'])) {
-    // Tells chado_generate_var not to follow any foreign keys
+    // Tells chado_generate_var not to follow any foreign keys.
     $options['include_fk'] = array();
   }
 
-  // Error Checking of parameters
+  // Error Checking of parameters.
   if (!is_array($identifiers)) {
     tripal_report_error(
       'tripal_organism_api',
       TRIPAL_ERROR,
-      "tripal_get_organism: The identifier passed in is expected to be an array with the key
+      "chado_get_organism: The identifier passed in is expected to be an array with the key
         matching a column name in the organism table (ie: organism_id or name). You passed in %identifier.",
       array(
         '%identifier'=> print_r($identifiers, TRUE)
@@ -62,7 +67,7 @@ function tripal_get_organism($identifiers, $options = array()) {
     tripal_report_error(
       'tripal_organism_api',
       TRIPAL_ERROR,
-      "tripal_get_organism: You did not pass in anything to identify the organism you want. The identifier
+      "chado_get_organism: You did not pass in anything to identify the organism you want. The identifier
         is expected to be an array with the key matching a column name in the organism table
         (ie: organism_id or name). You passed in %identifier.",
       array(
@@ -71,7 +76,7 @@ function tripal_get_organism($identifiers, $options = array()) {
     );
   }
 
-  // If one of the identifiers is property then use chado_get_record_with_property()
+  // If one of the identifiers is property then use chado_get_record_with_property().
   if (isset($identifiers['property'])) {
     $property = $identifiers['property'];
     unset($identifiers['property']);
@@ -82,7 +87,8 @@ function tripal_get_organism($identifiers, $options = array()) {
     );
   }
 
-  // Else we have a simple case and we can just use chado_generate_var to get the analysis
+  // Else we have a simple case and we can just use chado_generate_var to get 
+  // the analysis.
   else {
 
     // Try to get the organism
@@ -93,24 +99,25 @@ function tripal_get_organism($identifiers, $options = array()) {
     );
   }
 
-  // Ensure the organism is singular. If it's an array then it is not singular
+  // Ensure the organism is singular. If it's an array then it is not singular.
   if (is_array($organism)) {
     tripal_report_error(
       'tripal_organism_api',
       TRIPAL_ERROR,
-      "tripal_get_organism: The identifiers you passed in were not unique. You passed in %identifier.",
+      "chado_get_organism: The identifiers you passed in were not unique. You passed in %identifier.",
       array(
         '%identifier'=> print_r($identifiers, TRUE)
       )
     );
   }
 
-  // Report an error if $organism is FALSE since then chado_generate_var has failed
+  // Report an error if $organism is FALSE since then chado_generate_var has 
+  // failed.
   elseif ($organism === FALSE) {
     tripal_report_error(
       'tripal_organism_api',
       TRIPAL_ERROR,
-      "tripal_get_organism: chado_generate_var() failed to return a organism based on the identifiers
+      "chado_get_organism: chado_generate_var() failed to return a organism based on the identifiers
         you passed in. You should check that your identifiers are correct, as well as, look
         for a chado_generate_var error for additional clues. You passed in %identifier.",
       array(
@@ -135,27 +142,27 @@ function tripal_get_organism($identifiers, $options = array()) {
  *
  * @ingroup tripal_organism_api
  */
-function tripal_get_organism_scientific_name($organism) {
+function chado_get_organism_scientific_name($organism) {
   $name = $organism->genus . ' ' . $organism->species;
 
   // For Chado v1.3 we have a type_id and infraspecific name.
   if (property_exists($organism, 'type_id')) {
     $rank = '';
-    // For organism objects crated using chado_generate_var
+    // For organism objects crated using chado_generate_var.
     if (is_object($organism->type_id)) {
       if ($organism->type_id) {
-        $rank = $orgasnism->type_id->name;
+        $rank = $organism->type_id->name;
       }
     }
     else {
-      $rank_term = tripal_get_cvterm(array('cvterm_id' => $organism->type_id));
+      $rank_term = chado_get_cvterm(array('cvterm_id' => $organism->type_id));
       if ($rank_term) {
         $rank = $rank_term->name;
       }
     }
 
     if ($rank) {
-      $rank = tripal_abbreviate_infraspecific_rank($rank);
+      $rank = chado_abbreviate_infraspecific_rank($rank);
       $name .= ' ' . $rank . ' ' . $organism->infraspecific_name;
     }
     else if ($organism->infraspecific_name) {
@@ -166,18 +173,19 @@ function tripal_get_organism_scientific_name($organism) {
 }
 
 /**
- * Returns a list of organisms that are currently synced with Drupal to use in select lists
+ * Returns a list of organisms that are currently synced with Drupal to use in 
+ * select lists.
  *
  * @param $syncd_only
- *   Whether or not to return all chado organisms or just those sync'd with drupal. Defaults
- *   to TRUE (only sync'd organisms)
+ *   Whether or not to return all chado organisms or just those sync'd with 
+ *   drupal. Defaults to TRUE (only sync'd organisms).
  * @return
- *   An array of organisms sync'd with Drupal where each value is the organism scientific
- *   name and the keys are organism_id's
+ *   An array of organisms sync'd with Drupal where each value is the organism 
+ *   scientific name and the keys are organism_id's.
  *
  * @ingroup tripal_organism_api
  */
-function tripal_get_organism_select_options($syncd_only = TRUE) {
+function chado_get_organism_select_options($syncd_only = TRUE) {
   $org_list = array();
   $org_list[] = 'Select an organism';
 
@@ -190,7 +198,7 @@ function tripal_get_organism_select_options($syncd_only = TRUE) {
     ";
     $orgs = chado_query($sql);
 
-    // iterate through the organisms and build an array of those that are synced
+    // Iterate through the organisms and build an array of those that are synced.
     foreach ($orgs as $org) {
       $org_list[$org->organism_id] = $org->genus . ' ' . $org->species;
     }
@@ -200,7 +208,7 @@ function tripal_get_organism_select_options($syncd_only = TRUE) {
     $csql =  "SELECT * FROM {organism} ORDER BY genus, species";
     $orgs = chado_query($csql);
 
-    // iterate through the organisms and build an array of those that are synced
+    // Iterate through the organisms and build an array of those that are synced.
     foreach ($orgs as $org) {
       $org_list[$org->organism_id] = $org->genus . ' ' . $org->species;
     }
@@ -212,22 +220,22 @@ function tripal_get_organism_select_options($syncd_only = TRUE) {
  * Return the path for the organism image.
  *
  * @param $organism
- *   An organism table record
+ *   An organism table record.
  *
  * @return
  *   If the type parameter is 'url' (the default) then the fully qualified
- *   url to the image is returend. If no image is present then NULL is returned
+ *   url to the image is returend. If no image is present then NULL is returned.
  *
  * @ingroup tripal_organism_api
  */
-function tripal_get_organism_image_url($organism) {
+function chado_get_organism_image_url($organism) {
   $url = '';
 
   if (!is_object($organism)) {
     return NULL;
   }
 
-  // Get the organism's node
+  // Get the organism's node.
   $nid = chado_get_nid_from_id('organism', $organism->organism_id);
 
   // Look in the file_usage table of Drupal for the image file. This
@@ -245,8 +253,8 @@ function tripal_get_organism_image_url($organism) {
     return file_create_url($file->uri);
   }
 
-  // First look for an image with the genus/species name.  This is old-style tripal
-  // and we keep it for backwards compatibility.
+  // First look for an image with the genus/species name.  This is old-style 
+  // tripal and we keep it for backwards compatibility.
   $base_path = realpath('.');
   $image_dir = tripal_get_files_dir('tripal_organism') . "/images";
   $image_name =  $organism->genus . "_" . $organism->species . ".jpg";
@@ -272,17 +280,17 @@ function tripal_get_organism_image_url($organism) {
 
 /**
  * This function is intended to be used in autocomplete forms
- * for searching for organisms that begin with the provided string
+ * for searching for organisms that begin with the provided string.
  *
  * @param $text
- *   The string to search for
+ *   The string to search for.
  *
  * @return
- *   A json array of terms that begin with the provided string
+ *   A json array of terms that begin with the provided string.
  *
  * @ingroup tripal_organism_api
  */
-function tripal_autocomplete_organism($text) {
+function chado_autocomplete_organism($text) {
   $matches = array();
   $genus = $text;
   $species = '';
@@ -300,9 +308,9 @@ function tripal_autocomplete_organism($text) {
   $sql .= "ORDER BY genus, species ";
   $sql .= "LIMIT 25 OFFSET 0 ";
   $results = chado_query($sql, $args);
-  $items = array();
+  $items = array(['args' => [$sql => $args]]);
   foreach ($results as $organism) {
-    $name = tripal_get_organism_scientific_name($organism);
+    $name = chado_get_organism_scientific_name($organism);
     $items["$name [id: $organism->organism_id]"] = $name;
   }
   drupal_json_output($items);
@@ -318,7 +326,7 @@ function tripal_autocomplete_organism($text) {
  *
  * @ingroup tripal_organism_api
  */
-function tripal_abbreviate_infraspecific_rank($rank) {
+function chado_abbreviate_infraspecific_rank($rank) {
   $abb = '';
   switch($rank) {
     case 'no_rank':

+ 50 - 41
tripal_chado/api/modules/tripal_chado.phylotree.api.inc

@@ -2,13 +2,18 @@
 
 /**
  * @file
- * Provides an application programming interface (API) to manage organisms
+ * Provides API functions specificially for managing phylogenetic and taxonomic
+ * tree records in Chado.  
  */
 
 /**
  * @defgroup tripal_phylotree_api Chado Phylotree
  * @ingroup tripal_chado_api
  * @{
+ * Provides API functions specificially for managing phylogenetic and taxonomic
+ * tree records in Chado.  The API consists of functions for creation, 
+ * retrieval, update and deltion (CRUD) for phylogenetic tree records as 
+ * well as importing of trees in the newick file format.
  * @}
  */
 
@@ -25,7 +30,7 @@
  *   The type of validation. Can be either 'insert' or 'update'.
  * @param $options
  *   An array of key/value pairs containing any of the valid keys for
- *   either the tripal_insert_phylotree() or tripal_update_phylotree()
+ *   either the chado_insert_phylotree() or chado_update_phylotree()
  *   functions.
  * @param $errors
  *   An empty array where validation error messages will be set. The keys
@@ -45,7 +50,7 @@
  *
  * @ingroup tripal_phylotree_api
  */
-function tripal_validate_phylotree($val_type, &$options, &$errors, &$warnings) {
+function chado_validate_phylotree($val_type, &$options, &$errors, &$warnings) {
 
   if ($val_type != 'insert' and $val_type != 'update') {
     tripal_report_error('tripal_phylogeny', TRIPAL_ERROR, "The $val_type argument must be either 'update or 'insert'.");
@@ -88,14 +93,14 @@ function tripal_validate_phylotree($val_type, &$options, &$errors, &$warnings) {
       $errors['format'] = t('Please provide a file format for the tree file.');
       return FALSE;
     }
-    // Make sure the file format is correct
+    // Make sure the file format is correct.
     if ($options['format'] != 'newick' and $options['format'] != 'taxonomy') {
       $errors['format'] = t('The file format is not supported. Currently only the "newick" file format is supported.');
       return FALSE;
     }
   }
   else {
-    // Does the phylotree ID exist and is it valid
+    // Does the phylotree ID exist and is it valid.
     if (!array_key_exists('phylotree_id', $options)) {
       $errors['phylotree_id'] = t('Please provide the ID for the tree.');
       return FALSE;
@@ -109,7 +114,7 @@ function tripal_validate_phylotree($val_type, &$options, &$errors, &$warnings) {
 
   }
 
-  // Make sure the file exists if one is specified
+  // Make sure the file exists if one is specified.
   if (array_key_exists('tree_file', $options) and $options['tree_file']) {
     // If this is a numeric Drupal file then all is good, no need to check.
     if (!is_numeric($options['tree_file'])) {
@@ -118,7 +123,7 @@ function tripal_validate_phylotree($val_type, &$options, &$errors, &$warnings) {
         return FALSE;
       }
     }
-    // Make sure the file format is correct
+    // Make sure the file format is correct.
     if (!array_key_exists('format', $options) or
         ($options['format'] != 'newick' and $options['format'] != 'taxonomy')) {
       $errors['format'] = t('Please provide a supported file format. Currently only the "newick" file format is supported.');
@@ -204,7 +209,7 @@ function tripal_validate_phylotree($val_type, &$options, &$errors, &$warnings) {
     $options['dbxref_id'] = $dbxref->dbxref_id;
   }
 
-  // Make sure the tree name is unique
+  // Make sure the tree name is unique.
   if (array_key_exists('name', $options) and $options['name']) {
     $sql = "
       SELECT *
@@ -249,6 +254,7 @@ function tripal_validate_phylotree($val_type, &$options, &$errors, &$warnings) {
  *     'tree_file':  The path of the file containing the phylogenetic tree to
  *                   import or a Drupal managed_file numeric ID.
  *     'format':     The file format. Currently only 'newick is supported'.
+ * 
  *  Optional keys:
  *     'dbxref':     A database cross-reference of the form DB:ACCESSION.
  *                   Where DB is the database name, which is already present
@@ -280,7 +286,7 @@ function tripal_validate_phylotree($val_type, &$options, &$errors, &$warnings) {
  *
  * @ingroup tripal_phylotree_api
  */
-function tripal_insert_phylotree(&$options, &$errors, &$warnings) {
+function chado_insert_phylotree(&$options, &$errors, &$warnings) {
   global $user;
 
   $options['name_re'] = trim($options['name_re']);
@@ -290,7 +296,7 @@ function tripal_insert_phylotree(&$options, &$errors, &$warnings) {
   $options['tree_file'] = trim($options['tree_file']);
 
   // Validate the incoming options.
-  $success = tripal_validate_phylotree('insert', $options, $errors, $warnings);
+  $success = chado_validate_phylotree('insert', $options, $errors, $warnings);
   if (!$success) {
     foreach ($errors as $field => $message) {
       tripal_report_error('tripal_phylogeny', TRIPAL_ERROR, $message);
@@ -340,7 +346,7 @@ function tripal_insert_phylotree(&$options, &$errors, &$warnings) {
         'match' => $options['match'] ? 'uniquename' : 'name',
         'name_re' => $options['name_re'],
       );
-      tripal_phylogeny_import_tree_file($real_file_path, $options['format'], $args);
+      chado_phylogeny_import_tree_file($real_file_path, $options['format'], $args);
     }
     else {
       $args = array(
@@ -354,7 +360,7 @@ function tripal_insert_phylotree(&$options, &$errors, &$warnings) {
           ),
       );
       if (tripal_add_job("Import Tree File: " . $file->filename, 'tripal_phylogeny',
-          'tripal_phylogeny_import_tree_file', $args, $user->uid)) {
+          'chado_phylogeny_import_tree_file', $args, $user->uid)) {
           drupal_set_message(t('The tree visualizations will appear once the tree is fully imported.'));
       }
     }
@@ -409,13 +415,13 @@ function tripal_insert_phylotree(&$options, &$errors, &$warnings) {
  *
  * @ingroup tripal_phylotree_api
  */
-function tripal_update_phylotree($phylotree_id, &$options) {
+function chado_update_phylotree($phylotree_id, &$options) {
   global $user;
 
   // Validate the incoming options.
   $errors = array();
   $warnings = array();
-  $success = tripal_validate_phylotree('update', $options, $errors, $warnings);
+  $success = chado_validate_phylotree('update', $options, $errors, $warnings);
   if (!$success) {
     foreach ($errors as $field => $message) {
       tripal_report_error('tripal_phylogeny', TRIPAL_ERROR, $message);
@@ -452,7 +458,7 @@ function tripal_update_phylotree($phylotree_id, &$options) {
     );
   }
 
-  // If we have a tree file, then import the tree
+  // If we have a tree file, then import the tree.
   if (array_key_exists('tree_file', $options) and $options['tree_file']) {
 
     // Remove any existing nodes
@@ -495,7 +501,7 @@ function tripal_update_phylotree($phylotree_id, &$options) {
         'match' => $options['match'] ? 'uniquename' : 'name',
         'name_re' => $options['name_re'],
       );
-      tripal_phylogeny_import_tree_file($real_file_path, $options['format'], $args);
+      chado_phylogeny_import_tree_file($real_file_path, $options['format'], $args);
     }
     else {
       $args = array(
@@ -509,7 +515,7 @@ function tripal_update_phylotree($phylotree_id, &$options) {
         ),
       );
       if (tripal_add_job("Import Tree File: " . $file->filename, 'tripal_phylogeny',
-          'tripal_phylogeny_import_tree_file', $args, $user->uid)) {
+          'chado_phylogeny_import_tree_file', $args, $user->uid)) {
         drupal_set_message(t('The tree visualizations will appear once the tree is fully imported.'));
       }
     }
@@ -528,9 +534,9 @@ function tripal_update_phylotree($phylotree_id, &$options) {
  *
  * @ingroup tripal_phylotree_api
  */
-function tripal_delete_phylotree($phylotree_id) {
+function chado_delete_phylotree($phylotree_id) {
 
-  // if we don't have a phylotree id for this node then this isn't a node of
+  // If we don't have a phylotree id for this node then this isn't a node of
   // type chado_phylotree or the entry in the chado_phylotree table was lost.
   if (!$phylotree_id) {
     tripal_report_error('tripal_phylogeny', TRIPAL_ERROR,
@@ -544,7 +550,7 @@ function tripal_delete_phylotree($phylotree_id) {
 }
 
 /**
- * Iterates through the tree and sets the left and right indicies .
+ * Iterates through the tree and sets the left and right indicies.
  *
  * @param $tree
  *   The tree array.
@@ -554,7 +560,7 @@ function tripal_delete_phylotree($phylotree_id) {
  *
  * @ingroup tripal_phylotree_api
  */
-function tripal_assign_phylogeny_tree_indices(&$tree, &$index = 1) {
+function chado_assign_phylogeny_tree_indices(&$tree, &$index = 1) {
   // Assign a left and right index to each node.  The child node must
   // have a right and left index less than that of it's parents.  We
   // increment the index by 100 to give space for new nodes that might
@@ -567,7 +573,7 @@ function tripal_assign_phylogeny_tree_indices(&$tree, &$index = 1) {
   }
   if (array_key_exists('branch_set', $tree)) {
     foreach ($tree['branch_set'] as $key => $node) {
-      tripal_assign_phylogeny_tree_indices($tree['branch_set'][$key], $index);
+      chado_assign_phylogeny_tree_indices($tree['branch_set'][$key], $index);
       $tree['right_index'] = $index += 100;
     }
   }
@@ -596,7 +602,7 @@ function tripal_assign_phylogeny_tree_indices(&$tree, &$index = 1) {
  *                  will be assocaited with the phylonode.
  *
  * Prior to importing the tree the indicies can be set by using the
- * tripal_assign_phylogeny_tree_indices() function.
+ * chado_assign_phylogeny_tree_indices() function.
  *
  * @param $tree
  *   The tree array.
@@ -628,12 +634,12 @@ function tripal_assign_phylogeny_tree_indices(&$tree, &$index = 1) {
  *
  * @ingroup tripal_phylotree_api
  */
-function tripal_phylogeny_import_tree(&$tree, $phylotree, $options, $vocab = array(), $parent = NULL) {
+function chado_phylogeny_import_tree(&$tree, $phylotree, $options, $vocab = array(), $parent = NULL) {
 
   // Get the vocabulary terms used to describe nodes in the tree if one
   // wasn't provided.
   if (count($vocab) == 0) {
-    $vocab = tripal_phylogeny_get_node_types_vocab();
+    $vocab = chado_phylogeny_get_node_types_vocab();
   }
 
   if (is_array($tree) and array_key_exists('name', $tree)) {
@@ -642,14 +648,14 @@ function tripal_phylogeny_import_tree(&$tree, $phylotree, $options, $vocab = arr
       'left_idx'  => $tree['left_index'],
       'right_idx' => $tree['right_index'],
     );
-    // Add in any optional values to the $values array if they are present
+    // Add in any optional values to the $values array if they are present.
     if (!empty($tree['name']) and $tree['name'] != '') {
       $values['label'] = $tree['name'];
     }
     if (!empty($tree['length']) and $tree['length'] != '') {
       $values['distance'] = $tree['length'];
     }
-    // Set the type of node
+    // Set the type of node.
     if ($tree['is_root']) {
       $values['type_id'] = $vocab['root']->cvterm_id;
     }
@@ -669,8 +675,9 @@ function tripal_phylogeny_import_tree(&$tree, $phylotree, $options, $vocab = arr
       if (!empty($tree['name']) and $tree['name'] != '') {
         if (!$options['taxonomy']) {
 
-          // This is a sequence-based tree. Try to match leaf nodes with features.
-          // First, Get the Name and uniquename for the feature
+          // This is a sequence-based tree. Try to match leaf nodes with 
+          // features.
+          // First, Get the Name and uniquename for the feature.
           $matches = array();
           $sel_values = array();
           if ($options['match'] == "name") {
@@ -708,7 +715,7 @@ function tripal_phylogeny_import_tree(&$tree, $phylotree, $options, $vocab = arr
       }
     }
 
-    // Insert the new node and then add it's assigned phylonode_id to the node
+    // Insert the new node and then add it's assigned phylonode_id to the node.
     $phylonode = chado_insert_record('phylonode', $values);
     $tree['phylonode_id'] = $phylonode['phylonode_id'];
 
@@ -722,7 +729,7 @@ function tripal_phylogeny_import_tree(&$tree, $phylotree, $options, $vocab = arr
       $pylonode_organism = chado_insert_record('phylonode_organism', $values);
     }
 
-    // Associate any properties
+    // Associate any properties.
     if (array_key_exists('properties', $tree)) {
       foreach ($tree['properties'] as $type_id => $value) {
         $values = array(
@@ -736,19 +743,21 @@ function tripal_phylogeny_import_tree(&$tree, $phylotree, $options, $vocab = arr
   }
   if (is_array($tree) and array_key_exists('branch_set', $tree)) {
     foreach ($tree['branch_set'] as $key => $node) {
-      tripal_phylogeny_import_tree($tree['branch_set'][$key], $phylotree, $options, $vocab, $tree);
+      chado_phylogeny_import_tree($tree['branch_set'][$key], $phylotree, $options, $vocab, $tree);
     }
   }
 }
 
 /**
+ * Get the vocabulary terms used to describe nodes in the tree.
  *
- * @return
- *
+ * @return 
+ *  Array of vocab info or FALSE on failure.
+ * 
  * @ingroup tripal_phylotree_api
  */
-function tripal_phylogeny_get_node_types_vocab() {
-  // Get the vocabulary terms used to describe nodes in the tree
+function chado_phylogeny_get_node_types_vocab() {
+  // Get the vocabulary terms used to describe nodes in the tree.
   $values = array(
     'name' => 'phylo_leaf',
     'cv_id' => array(
@@ -815,7 +824,7 @@ function tripal_phylogeny_get_node_types_vocab() {
  *
  *  @ingroup tripal_phylotree_api
  */
-function tripal_phylogeny_import_tree_file($file_name, $format, $options = array(), $job_id = NULL) {
+function chado_phylogeny_import_tree_file($file_name, $format, $options = array(), $job_id = NULL) {
 
   // Set some option details.
   if (!array_key_exists('leaf_type', $options)) {
@@ -839,7 +848,7 @@ function tripal_phylogeny_import_tree_file($file_name, $format, $options = array
     }
   }
 
-  // get the phylotree record.
+  // Get the phylotree record.
   $values = array('phylotree_id' => $options['phylotree_id']);
   $phylotree = chado_generate_var('phylotree', $values);
 
@@ -862,12 +871,12 @@ function tripal_phylogeny_import_tree_file($file_name, $format, $options = array
       module_load_include('inc', 'tripal_chado', 'includes/loaders/tripal_chado.phylotree_newick');
       $tree = tripal_phylogeny_parse_newick_file($file_name);
 
-      // Assign the right and left indecies to the tree ndoes
-      tripal_assign_phylogeny_tree_indices($tree);
+      // Assign the right and left indecies to the tree ndoes.
+      chado_assign_phylogeny_tree_indices($tree);
     }
     // Iterate through the tree nodes and add them to Chado in accordance
     // with the details in the $options array.
-    tripal_phylogeny_import_tree($tree, $phylotree, $options);
+    chado_phylogeny_import_tree($tree, $phylotree, $options);
   }
   catch (Exception $e) {
     $transaction->rollback();

+ 134 - 111
tripal_chado/api/modules/tripal_chado.pub.api.inc

@@ -1,52 +1,57 @@
 <?php
 /**
  * @file
- * Provides an application programming interface (API) to manage chado publications
+ * Provides API functions specificially for managing publication 
+ * records in Chado.  
  */
 
 /**
  * @defgroup tripal_pub_api Chado Publication
  * @ingroup tripal_chado_api
  * @{
+ * Provides API functions specificially for managing publication 
+ * records in Chado.
  * @}
  */
 
 
 /**
- * Retrieves a chado publication array
+ * Retrieves a chado publication array.
  *
  * @param $identifier
  *   An array used to uniquely identify a publication. This array has the same
  *   format as that used by the chado_generate_var(). The following keys can be
  *   useful for uniquely identifying a publication as they should be unique:
- *    - pub_id: the chado pub.pub_id primary key
- *    - nid: the drupal nid of the publication
- *    - uniquename: A value to matach with the pub.uniquename field
+ *    - pub_id: the chado pub.pub_id primary key.
+ *    - nid: the drupal nid of the publication.
+ *    - uniquename: A value to matach with the pub.uniquename field.
  *   There are also some specially handled keys. They are:
  *    - property: An array describing the property to select records for. It
  *      should at least have either a 'type_name' key (if unique across cvs) or
- *      'type_id' key. Other supported keys include: 'cv_id', 'cv_name' (of the type),
- *      'value' and 'rank'
- *    - dbxref: The database cross reference accession.  It should be in the form
- *        DB:ACCESSION, where DB is the database name and ACCESSION is the
- *        unique publication identifier (e.g. PMID:4382934)
+ *      'type_id' key. Other supported keys include: 'cv_id', 'cv_name' 
+ *      (of the type), 'value' and 'rank'
+ *    - dbxref: The database cross reference accession.  It should be in the 
+ *      form DB:ACCESSION, where DB is the database name and ACCESSION is the
+ *      unique publication identifier (e.g. PMID:4382934)
  *    - dbxref_id:  The dbxref.dbxref_id of the publication.
  * @param $options
  *   An array of options. Supported keys include:
- *     - Any keys supported by chado_generate_var(). See that function definition for
- *       additional details.
+ *     - Any keys supported by chado_generate_var(). See that function 
+ *       definition for additional details.
  *
- * NOTE: the $identifier parameter can really be any array similar to $values passed into
- *   chado_select_record(). It should fully specify the pub record to be returned.
+ * NOTE: the $identifier parameter can really be any array similar to $values 
+ * passed into chado_select_record(). It should fully specify the pub record to 
+ * be returned.
  *
  * @return
- *   If a singe publication is retreived using the identifiers, then a publication
- *   array will be returned.  The array is of the same format returned by the
- *   chado_generate_var() function. Otherwise, FALSE will be returned.
+ *   If a singe publication is retreived using the identifiers, then a 
+ *   publication array will be returned.  The array is of the same format 
+ *   returned by the chado_generate_var() function. Otherwise, FALSE will be 
+ *   returned.
  *
  * @ingroup tripal_pub_api
  */
-function tripal_get_publication($identifiers, $options = array()) {
+function chado_get_publication($identifiers, $options = array()) {
 
   // Error Checking of parameters
   if (!is_array($identifiers)) {
@@ -65,7 +70,8 @@ function tripal_get_publication($identifiers, $options = array()) {
     );
   }
 
-  // If one of the identifiers is property then use chado_get_record_with_property()
+  // If one of the identifiers is property then use 
+  // chado_get_record_with_property().
   if (array_key_exists('property', $identifiers)) {
     $property = $identifiers['property'];
     unset($identifiers['property']);
@@ -105,11 +111,11 @@ function tripal_get_publication($identifiers, $options = array()) {
     }
   }
   elseif (array_key_exists('dbxref_id', $identifiers)) {
-    // first get the pub_dbxref record
+    // First get the pub_dbxref record.
     $values = array('dbxref_id' => $identifiers['dbxref_id']);
     $pub_dbxref = chado_select_record('pub_dbxref', array('pub_id'), $values);
 
-    // now get the pub
+    // Now get the pub.
     if (count($pub_dbxref) > 0) {
       $pub = chado_generate_var('pub', array('pub_id' => $pub_dbxref[0]->pub_id), $options);
     }
@@ -118,13 +124,14 @@ function tripal_get_publication($identifiers, $options = array()) {
     }
 
   }
-  // Else we have a simple case and we can just use chado_generate_var to get the pub
+  // Else we have a simple case and we can just use chado_generate_var to get 
+  // the pub.
   else {
-    // Try to get the pub
+    // Try to get the pub.
     $pub = chado_generate_var('pub', $identifiers, $options);
   }
 
-  // Ensure the pub is singular. If it's an array then it is not singular
+  // Ensure the pub is singular. If it's an array then it is not singular.
   if (is_array($pub)) {
     tripal_report_error('tripal_pub_api', TRIPAL_ERROR,
       "chado_get_publication: The identifiers did not find a single unique record. Identifiers passed: %identifier.",
@@ -132,7 +139,7 @@ function tripal_get_publication($identifiers, $options = array()) {
     );
   }
 
-  // Report an error if $pub is FALSE since then chado_generate_var has failed
+  // Report an error if $pub is FALSE since then chado_generate_var has failed.
   elseif ($pub === FALSE) {
     tripal_report_error('tripal_pub_api', TRIPAL_ERROR,
       "chado_get_publication: Could not find a publication using the identifiers
@@ -159,42 +166,47 @@ function tripal_get_publication($identifiers, $options = array()) {
  * @param $pub_details
  *   An associative array with details about the publications. The expected keys
  *   are:
- *     'Title':              The title of the publication
- *     'Year':               The published year of the publication
- *     'Publication Type':   An array of publication types. A publication can have more than one type.
- *     'Series Name':        The series name of the publication
- *     'Journal Name':       An alternative to 'Series Name'
- *     'Conference Name':    An alternative to 'Series Name'
- *     'Citation':           The publication citation (this is the value saved in the pub.uniquename field and must be unique)
- *   If this key is present it will also be checked
- *     'Publication Dbxref': A database cross reference of the form DB:ACCESSION where DB is the name
- *                           of the database and ACCESSION is the unique identifier (e.g PMID:3483139)
+ *     'Title':              The title of the publication.
+ *     'Year':               The published year of the publication.
+ *     'Publication Type':   An array of publication types. A publication can 
+ *                           have more than one type.
+ *     'Series Name':        The series name of the publication.
+ *     'Journal Name':       An alternative to 'Series Name'.
+ *     'Conference Name':    An alternative to 'Series Name'.
+ *     'Citation':           The publication citation (this is the value saved 
+ *                           in the pub.uniquename field and must be unique).
+ *   
+ *     If this key is present it will also be checked
+ *     'Publication Dbxref': A database cross reference of the form DB:ACCESSION 
+ *                           where DB is the name of the database and ACCESSION 
+ *                           is the unique identifier (e.g PMID:3483139).
  *
  * @return
  *   An array containing the pub_id's of matching publications. Returns an
- *   empty array if no pubs match
+ *   empty array if no pubs match.
  *
  * @ingroup tripal_pub_api
  */
-function tripal_publication_exists($pub_details) {
+function chado_publication_exists($pub_details) {
 
-  // first try to find the publication using the accession number if that key exists in the details array
+  // First try to find the publication using the accession number if that key 
+  // exists in the details array.
   if (array_key_exists('Publication Dbxref', $pub_details)) {
-    $pub = tripal_get_publication(array('dbxref' => $pub_details['Publication Dbxref']));
+    $pub = chado_get_publication(array('dbxref' => $pub_details['Publication Dbxref']));
     if($pub) {
       return array($pub->pub_id);
     }
   }
 
-  // make sure the citation is unique
+  // Make sure the citation is unique.
   if (array_key_exists('Citation', $pub_details)) {
-    $pub = tripal_get_publication(array('uniquename' => $pub_details['Citation']));
+    $pub = chado_get_publication(array('uniquename' => $pub_details['Citation']));
     if($pub) {
       return array($pub->pub_id);
     }
   }
 
-  // get the publication type (use the first publication type)
+  // Get the publication type (use the first publication type).
   if (array_key_exists('Publication Type', $pub_details)) {
     $type_name = '';
     if(is_array($pub_details['Publication Type'])) {
@@ -209,22 +221,23 @@ function tripal_publication_exists($pub_details) {
         'name' => 'tripal_pub',
       ),
     );
-    $pub_type = tripal_get_cvterm($identifiers);
+    $pub_type = chado_get_cvterm($identifiers);
   }
   else {
     tripal_report_error('tripal_pub', TRIPAL_ERROR,
-      "tripal_publication_exists(): The Publication Type is a " .
+      "chado_publication_exists(): The Publication Type is a " .
       "required property but is missing", array());
     return array();
   }
   if (!$pub_type) {
     tripal_report_error('tripal_pub', TRIPAL_ERROR,
-     "tripal_publication_exists(): Cannot find publication type: '%type'",
+      "chado_publication_exists(): Cannot find publication type: '%type'",
       array('%type' => $pub_details['Publication Type'][0]));
     return array();
   }
 
-  // get the series name.  The pub.series_name field is only 255 chars so we must truncate to be safe
+  // Get the series name.  The pub.series_name field is only 255 chars so we 
+  // must truncate to be safe.
   $series_name = '';
   if (array_key_exists('Series Name', $pub_details)) {
     $series_name = substr($pub_details['Series Name'], 0, 255);
@@ -236,7 +249,8 @@ function tripal_publication_exists($pub_details) {
     $series_name = substr($pub_details['Conference Name'], 0, 255);
   }
 
-  // make sure the publication is unique using the prefereed import duplication check
+  // Make sure the publication is unique using the prefereed import 
+  // duplication check.
   $import_dups_check = variable_get('tripal_pub_import_duplicate_check', 'title_year_media');
   $pubs = array();
   switch ($import_dups_check) {
@@ -280,14 +294,14 @@ function tripal_publication_exists($pub_details) {
  * @param $field
  *   The field in the publication to search on.
  * @param $string
- *   The string to search for
+ *   The string to search for.
  *
  * @return
- *   A json array of terms that begin with the provided string
+ *   A json array of terms that begin with the provided string.
  *
- * @ingroup tripal_chado_api
+ * @ingroup tripal_pub_api
  */
-function tripal_autocomplete_pub($string = '') {
+function chado_autocomplete_pub($string = '') {
   $items = array();
   $sql = "
     SELECT pub_id, title, uniquename
@@ -321,9 +335,9 @@ function tripal_autocomplete_pub($string = '') {
  *   If set to TRUE then the publication will be updated if it already exists
  *   in the database.
  *
- * @ingroup tripal_pub
+ * @ingroup tripal_pub_api
  */
-function tripal_import_pub_by_dbxref($pub_dbxref, $do_contact = FALSE, $do_update = TRUE) {
+function chado_import_pub_by_dbxref($pub_dbxref, $do_contact = FALSE, $do_update = TRUE) {
   $num_to_retrieve = 1;
   $pager_id = 0;
   $page = 0;
@@ -366,11 +380,12 @@ function tripal_import_pub_by_dbxref($pub_dbxref, $do_contact = FALSE, $do_updat
     // is enabled. If so, then sync the nodes.
     if (module_exists('tripal_pub')) {
 
-      // sync the newly added publications with Drupal
+      // Sync the newly added publications with Drupal.
       print "Syncing publications with Drupal...\n";
       chado_node_sync_records('pub');
 
-      // if any of the importers wanted to create contacts from the authors then sync them
+      // If any of the importers wanted to create contacts from the authors 
+      // then sync them.
       if($do_contact) {
         print "Syncing contacts with Drupal...\n";
         chado_node_sync_records('contact');
@@ -391,14 +406,14 @@ function tripal_import_pub_by_dbxref($pub_dbxref, $do_contact = FALSE, $do_updat
  *
  * @param $report_email
  *   A list of email address, separated by commas, that should be notified
- *   once importing has completed
+ *   once importing has completed.
  * @param $do_update
  *   If set to TRUE then publications that already exist in the Chado database
- *   will be updated, whereas if FALSE only new publications will be added
+ *   will be updated, whereas if FALSE only new publications will be added.
  *
- * @ingroup tripal_pub
+ * @ingroup tripal_pub_api
  */
-function tripal_execute_active_pub_importers($report_email = FALSE, $do_update = FALSE) {
+function chado_execute_active_pub_importers($report_email = FALSE, $do_update = FALSE) {
   $num_to_retrieve = 100;
   $page = 0;
 
@@ -410,7 +425,7 @@ function tripal_execute_active_pub_importers($report_email = FALSE, $do_update =
   $transaction = db_transaction();
 
   try {
-    // get all of the loaders
+    // Get all of the loaders.
     $args = array();
     $sql = "SELECT * FROM {tripal_pub_import} WHERE disabled = 0 ";
     $results = db_query($sql, $args);
@@ -419,27 +434,27 @@ function tripal_execute_active_pub_importers($report_email = FALSE, $do_update =
     foreach ($results as $import) {
       $page = 0;
       print "Executing importer: '" . $import->name . "'\n";
-      // keep track if any of the importers want to create contacts from authors
+      // Keep track if any of the importers want to create contacts from authors.
       if ($import->do_contact == 1) {
         $do_contact = TRUE;
       }
       $criteria = unserialize($import->criteria);
       $remote_db = $criteria['remote_db'];
       do {
-        // retrieve the pubs for this page. We'll retreive 100 at a time
+        // Retrieve the pubs for this page. We'll retreive 100 at a time.
         $results = tripal_get_remote_pubs($remote_db, $criteria, $num_to_retrieve, $page);
         $pubs = $results['pubs'];
         $reports[$import->name] = tripal_pub_add_publications($pubs, $import->do_contact, $do_update);
         $page++;
       }
-      // continue looping until we have a $pubs array that does not have
-      // our requested numer of records.  This means we've hit the end
+      // Continue looping until we have a $pubs array that does not have
+      // our requested numer of records.  This means we've hit the end.
       while (count($pubs) == $num_to_retrieve);
     }
 
-    // sync the newly added publications with Drupal. If the user
+    // Sync the newly added publications with Drupal. If the user
     // requested a report then we don't want to print any syncing information
-    // so pass 'FALSE' to the sync call
+    // so pass 'FALSE' to the sync call.
     // For backwards compatibility check to see if the legacy pub module
     // is enabled. If so, then sync the nodes.
     if (module_exists('tripal_pub')) {
@@ -447,7 +462,8 @@ function tripal_execute_active_pub_importers($report_email = FALSE, $do_update =
       chado_node_sync_records('pub');
     }
 
-    // iterate through each of the reports and generate a final report with HTML links
+    // Iterate through each of the reports and generate a final report with HTML
+    // links.
     $HTML_report = '';
     if ($report_email) {
       $HTML_report .= "<html>";
@@ -475,7 +491,8 @@ function tripal_execute_active_pub_importers($report_email = FALSE, $do_update =
     // For backwards compatibility check to see if the legacy pub module
     // is enabled. If so, then sync the nodes.
     if (module_exists('tripal_pub')) {
-      // if any of the importers wanted to create contacts from the authors then sync them
+      // If any of the importers wanted to create contacts from the authors then 
+      // sync them.
       if($do_contact) {
         print "Syncing contacts with Drupal...\n";
         chado_node_sync_records('contact');
@@ -512,9 +529,9 @@ function tripal_execute_active_pub_importers($report_email = FALSE, $do_update =
  *   no dbxref then all of the publications currently in the Chado database
  *   for this remote database will be updated.
  *
- * @ingroup tripal_pub
+ * @ingroup tripal_pub_api
  */
-function tripal_reimport_publications($do_contact = FALSE, $dbxref = NULL, $db = NULL) {
+function chado_reimport_publications($do_contact = FALSE, $dbxref = NULL, $db = NULL) {
 
   print "\nNOTE: Loading of publications is performed using a database transaction. \n" .
       "If the load fails or is terminated prematurely then the entire set of \n" .
@@ -522,7 +539,8 @@ function tripal_reimport_publications($do_contact = FALSE, $dbxref = NULL, $db =
   $transaction = db_transaction();
   try {
 
-    // get a list of all publications by their Dbxrefs that have supported databases
+    // Get a list of all publications by their Dbxrefs that have supported 
+    // databases.
     $sql = "
       SELECT DB.name as db_name, DBX.accession
       FROM pub P
@@ -546,17 +564,17 @@ function tripal_reimport_publications($do_contact = FALSE, $dbxref = NULL, $db =
     $results = chado_query($sql, $args);
 
     $num_to_retrieve = 100;
-    $i = 0;                 // count the number of IDs. When we hit $num_to_retrieve we'll do the query
-    $curr_db = '';          // keeps track of the current current database
-    $ids = array();         // the list of IDs for the database
-    $search = array();      // the search array passed to the search function
+    $i = 0;                 // count the number of IDs. When we hit $num_to_retrieve we'll do the query.
+    $curr_db = '';          // keeps track of the current current database.
+    $ids = array();         // the list of IDs for the database.
+    $search = array();      // the search array passed to the search function.
 
-    // iterate through the pub IDs
+    // Iterate through the pub IDs.
     while ($pub = $results->fetchObject()) {
       $accession = $pub->accession;
       $remote_db = $pub->db_name;
 
-      // here we need to only update publications for databases we support
+      // Here we need to only update publications for databases we support.
       $supported_dbs = variable_get('tripal_pub_supported_dbs', array());
       if(!in_array($remote_db, $supported_dbs)) {
         continue;
@@ -582,11 +600,11 @@ function tripal_reimport_publications($do_contact = FALSE, $dbxref = NULL, $db =
     // For backwards compatibility check to see if the legacy pub module
     // is enabled. If so, then sync the nodes.
     if (module_exists('tripal_pub')) {
-      // sync the newly added publications with Drupal
+      // Sync the newly added publications with Drupal.
       print "Syncing publications with Drupal...\n";
       chado_node_sync_records('pub');
 
-      // if the caller wants to create contacts then we should sync them
+      // If the caller wants to create contacts then we should sync them.
       if ($do_contact) {
         print "Syncing contacts with Drupal...\n";
         chado_node_sync_records('contact');
@@ -613,12 +631,12 @@ function tripal_reimport_publications($do_contact = FALSE, $dbxref = NULL, $db =
  * @param $options
  *  Options pertaining to what publications to generate citations for.
  *  One of the following must be present:
- *   - all: Create and replace citation for all pubs
- *   - new: Create citation for pubs that don't already have one
+ *   - all: Create and replace citation for all pubs.
+ *   - new: Create citation for pubs that don't already have one.
  *
- * @ingroup tripal_pub
+ * @ingroup tripal_pub_api
  */
-function tripal_pub_create_citations($options) {
+function chado_pub_create_citations($options) {
   $skip_existing = TRUE;
   $sql = "
     SELECT cvterm_id
@@ -629,12 +647,12 @@ function tripal_pub_create_citations($options) {
   ";
   $citation_type_id = chado_query($sql)->fetchField();
 
-  // Create and replace citation for all pubs
+  // Create and replace citation for all pubs.
   if ($options == 'all') {
     $sql = "SELECT pub_id FROM {pub} P WHERE pub_id <> 1";
     $skip_existing = FALSE;
   }
-  // Create citation for pubs that don't already have one
+  // Create citation for pubs that don't already have one.
   else if ($options == 'new') {
     $sql = "
       SELECT pub_id
@@ -654,9 +672,10 @@ function tripal_pub_create_citations($options) {
   while ($pub = $result->fetchObject()) {
     $pub_arr = tripal_pub_get_publication_array($pub->pub_id, $skip_existing);
     if ($pub_arr) {
-      $citation = tripal_pub_create_citation($pub_arr);
+      $citation = chado_pub_create_citation($pub_arr);
       print $citation . "\n\n";
-      // Replace if citation exists. This condition is never TRUE if $skip_existing is TRUE
+      // Replace if citation exists. This condition is never TRUE if 
+      // $skip_existing is TRUE.
       if ($pub_arr['Citation']) {
         $sql = "
           UPDATE {pubprop} SET value = :value
@@ -665,7 +684,7 @@ function tripal_pub_create_citations($options) {
         chado_query($sql, array(':value' => $citation, ':pub_id' => $pub->pub_id,
           ':type_id' => $citation_type_id, ':rank' => 0));
         $counter_updated ++;
-        // Generate a new citation
+        // Generate a new citation.
       } else {
         $sql = "
           INSERT INTO {pubprop} (pub_id, type_id, value, rank)
@@ -692,23 +711,25 @@ function tripal_pub_create_citations($options) {
  *   are the publication ontology term names and values are the
  *   corresponding details.  The pub array can contain the following
  *   keys with corresponding values:
- *     - Publication Type:  an array of publication types. a publication can have more than one type
- *     - Authors: a  string containing all of the authors of a publication
- *     - Journal Name:  a string containing the journal name
- *     - Journal Abbreviation: a string containing the journal name abbreviation
- *     - Series Name: a string containing the series (e.g. conference proceedings) name
+ *     - Publication Type:  an array of publication types. a publication can 
+ *       have more than one type.
+ *     - Authors: a  string containing all of the authors of a publication.
+ *     - Journal Name:  a string containing the journal name.
+ *     - Journal Abbreviation: a string containing the journal name abbreviation.
+ *     - Series Name: a string containing the series (e.g. conference 
+ *       proceedings) name.
  *     - Series Abbreviation: a string containing the series name abbreviation
- *     - Volume: the serives volume number
- *     - Issue: the series issue number
- *     - Pages: the page numbers for the publication
- *     - Publication Date:  A date in the format "Year Month Day"
+ *     - Volume: the serives volume number.
+ *     - Issue: the series issue number.
+ *     - Pages: the page numbers for the publication.
+ *     - Publication Date:  A date in the format "Year Month Day".
  *
  * @return
- *   A text string containing the citation
+ *   A text string containing the citation.
  *
- * @ingroup tripal_pub
+ * @ingroup tripal_pub_api
  */
-function tripal_pub_create_citation($pub) {
+function chado_pub_create_citation($pub) {
   $citation = '';
   $pub_type = '';
 
@@ -745,8 +766,8 @@ function tripal_pub_create_citation($pub) {
       }
       else if ($ptype == "Research Support, Non-U.S. Gov't") {
         $pub_type = $ptype;
-        // we don't break because if the article is also a Journal Article
-        // we prefer that type
+        // We don't break because if the article is also a Journal Article
+        // we prefer that type.
       }
     }
     // If we don't have a recognized publication type, then just use the
@@ -999,16 +1020,18 @@ function tripal_pub_create_citation($pub) {
  * Retrieves the minimal information to uniquely describe any publication.
  *
  * The returned array is an associative array where the keys are
- * the controlled vocabulary terms in the form [vocab]:[accession]
+ * the controlled vocabulary terms in the form [vocab]:[accession].
  *
  * @param $pub
- *   A publication object as created by chado_generate_var()
+ *   A publication object as created by chado_generate_var().
  *
  * @return
  *   An array with the following keys:  'Citation', 'Abstract', 'Authors',
  *   'URL'. All keys are term names in the Tripal Publication Ontology :TPUB.
+ * 
+ * @ingroup tripal_pub_api
  */
-function tripal_get_minimal_pub_info($pub) {
+function chado_get_minimal_pub_info($pub) {
   if (!$pub) {
     return array();
   }
@@ -1018,11 +1041,11 @@ function tripal_get_minimal_pub_info($pub) {
     return array();
   }
 
-  // expand the title
+  // Expand the title.
   $pub = chado_expand_var($pub, 'field', 'pub.title');
   $pub = chado_expand_var($pub, 'field', 'pub.volumetitle');
 
-  // get the abstract
+  // Get the abstract.
   $values = array(
     'pub_id' => $pub->pub_id,
     'type_id' => array(
@@ -1058,7 +1081,7 @@ function tripal_get_minimal_pub_info($pub) {
     $authors_list = $authors->value;
   }
 
-  // get the first database cross-reference with a url.
+  // Get the first database cross-reference with a url.
   $options = array('return_array' => 1);
   $pub = chado_expand_var($pub, 'table', 'pub_dbxref', $options);
   $dbxref = NULL;
@@ -1070,7 +1093,7 @@ function tripal_get_minimal_pub_info($pub) {
     }
   }
 
-  // get the URL.
+  // Get the URL.
   $values = array(
     'pub_id' => $pub->pub_id,
     'type_id' => array(
@@ -1103,7 +1126,7 @@ function tripal_get_minimal_pub_info($pub) {
     $dbxrefs[] = $pub_dbxref->dbxref_id->db_id->name . ':' . $pub_dbxref->dbxref_id->accession;
   }
 
-  // get the citation
+  // Get the citation.
   $values = array(
     'pub_id' => $pub->pub_id,
     'type_id' => array(
@@ -1130,7 +1153,7 @@ function tripal_get_minimal_pub_info($pub) {
       'Pages' => $pub->pages,
       'Publication Date' => $pub->pyear,
     );
-    $citation = tripal_pub_create_citation($pub_info);
+    $citation = chado_pub_create_citation($pub_info);
   }
 
   return array(

+ 55 - 43
tripal_chado/api/modules/tripal_chado.stock.api.inc

@@ -1,13 +1,19 @@
 <?php
 /**
  * @file
- * Provides an application programming interface (API) to manage stocks
+ * Provides API functions specificially for managing stock 
+ * records in Chado. 
  */
 
 /**
  * @defgroup tripal_stock_api Chado Stock
  * @ingroup tripal_chado_api
  * @{
+ * Provides API functions specificially for managing stock 
+ * records in Chado.  The stock table of Chado is used for storing a variety
+ * of data types besides just stocks from a stock collection.  Examples of 
+ * other records commonly stored in the stock table are germplasm and
+ * individuals from a breeding population.
  * @}
  */
 
@@ -15,43 +21,45 @@
  * Retrieves a chado stock variable
  *
  * @param $identifier
- *   An array with the key stating what the identifier is. Supported keys (only one of the
- *   following unique keys is required):
+ *   An array with the key stating what the identifier is. Supported keys (only 
+ *   one of the following unique keys is required):
  *    - stock_id: the chado stock.stock_id primary key
  *    - nid: the drupal nid of the stock
  *   There are also some specially handled keys. They are:
- *    - property: An array/object describing the property to select records for. It
- *      should at least have either a type_name (if unique across cvs) or type_id. Other
- *      supported keys include: cv_id/cv_name (of the type), value and rank
+ *    - property: An array/object describing the property to select records for. 
+ *      It should at least have either a type_name (if unique across cvs) or 
+ *      type_id. Other supported keys include: cv_id/cv_name (of the type), 
+ *      value and rank
  * @param $options
  *   An array of options. Supported keys include:
- *     - Any keys supported by chado_generate_var(). See that function definition for
- *       additional details.
+ *     - Any keys supported by chado_generate_var(). See that function 
+ *      definition for additional details.
  *
- * NOTE: the $identifier parameter can really be any array similar to $values passed into
- *   chado_select_record(). It should fully specify the stock record to be returned.
+ * NOTE: the $identifier parameter can really be any array similar to $values
+ * passed into chado_select_record(). It should fully specify the stock record 
+ * to be returned.
  *
  * @return
- *   If unique values were passed in as an identifier then an object describing the stock
- *   will be returned (will be a chado variable from chado_generate_var()). Otherwise,
- *   FALSE will be returned.
+ *   If unique values were passed in as an identifier then an object describing 
+ *   the stock will be returned (will be a chado variable from 
+ *   chado_generate_var()). Otherwise, FALSE will be returned.
  *
  * @ingroup tripal_stock_api
  */
-function tripal_get_stock($identifiers, $options = array()) {
+function chado_get_stock($identifiers, $options = array()) {
 
-  // Set Defaults
+  // Set Defaults.
   if (!isset($options['include_fk'])) {
-    // Tells chado_generate_var to only expand 1 level
+    // Tells chado_generate_var to only expand 1 level.
     $options['include_fk'] = array('type_id' => TRUE, 'dbxref_id' => TRUE);
   }
 
-  // Error Checking of parameters
+  // Error Checking of parameters.
   if (!is_array($identifiers)) {
     tripal_report_error(
       'tripal_stock_api',
       TRIPAL_ERROR,
-      "tripal_get_stock: The identifier passed in is expected to be an array with the key
+      "chado_get_stock: The identifier passed in is expected to be an array with the key
         matching a column name in the stock table (ie: stock_id or name). You passed in %identifier.",
       array(
         '%identifier'=> print_r($identifiers, TRUE)
@@ -62,7 +70,7 @@ function tripal_get_stock($identifiers, $options = array()) {
     tripal_report_error(
       'tripal_stock_api',
       TRIPAL_ERROR,
-      "tripal_get_stock: You did not pass in anything to identify the stock you want. The identifier
+      "chado_get_stock: You did not pass in anything to identify the stock you want. The identifier
         is expected to be an array with the key matching a column name in the stock table
         (ie: stock_id or name). You passed in %identifier.",
       array(
@@ -71,7 +79,8 @@ function tripal_get_stock($identifiers, $options = array()) {
     );
   }
 
-  // If one of the identifiers is property then use chado_get_record_with_property()
+  // If one of the identifiers is property then use 
+  // chado_get_record_with_property().
   if (isset($identifiers['property'])) {
     $property = $identifiers['property'];
     unset($identifiers['property']);
@@ -82,10 +91,11 @@ function tripal_get_stock($identifiers, $options = array()) {
     );
   }
 
-  // Else we have a simple case and we can just use chado_generate_var to get the stock
+  // Else we have a simple case and we can just use chado_generate_var to get 
+  // the stock.
   else {
 
-    // Try to get the stock
+    // Try to get the stock.
     $stock = chado_generate_var(
       'stock',
       $identifiers,
@@ -93,24 +103,24 @@ function tripal_get_stock($identifiers, $options = array()) {
     );
   }
 
-  // Ensure the stock is singular. If it's an array then it is not singular
+  // Ensure the stock is singular. If it's an array then it is not singular.
   if (is_array($stock)) {
     tripal_report_error(
       'tripal_stock_api',
       TRIPAL_ERROR,
-      "tripal_get_stock: The identifiers you passed in were not unique. You passed in %identifier.",
+      "chado_get_stock: The identifiers you passed in were not unique. You passed in %identifier.",
       array(
         '%identifier'=> print_r($identifiers, TRUE)
       )
     );
   }
 
-  // Report an error if $stock is FALSE since then chado_generate_var has failed
+  // Report an error if $stock is FALSE since then chado_generate_var has failed.
   elseif ($stock === FALSE) {
     tripal_report_error(
       'tripal_stock_api',
       TRIPAL_ERROR,
-      "tripal_get_stock: chado_generate_var() failed to return a stock based on the identifiers
+      "chado_get_stock: chado_generate_var() failed to return a stock based on the identifiers
         you passed in. You should check that your identifiers are correct, as well as, look
         for a chado_generate_var error for additional clues. You passed in %identifier.",
       array(
@@ -126,36 +136,36 @@ function tripal_get_stock($identifiers, $options = array()) {
 }
 
 /**
- * Retrieves a chado stock variable
+ * Retrieves a chado stock variable.
  *
  * @param $identifier
- *   An array with the key stating what the identifier is. Supported keys include any
- *   field in the stock table. See the chado_select_record() $values parameter for
- *   additional details including an example.
+ *   An array with the key stating what the identifier is. Supported keys 
+ *   include any field in the stock table. See the chado_select_record() $values
+ *   parameter for additional details including an example.
  * @param $options
  *   An array of options. Supported keys include:
- *     - Any keys supported by chado_generate_var(). See that function definition for
- *       additional details.
+ *     - Any keys supported by chado_generate_var(). See that function 
+ *       definition for additional details.
  *
  * @return
  *   An array of stock objects matching the criteria.
  *
  * @ingroup tripal_stock_api
  */
-function tripal_get_multiple_stocks($identifiers, $options = array()) {
+function chado_get_multiple_stocks($identifiers, $options = array()) {
 
-  // Set Defaults
+  // Set Defaults.
   if (!isset($options['include_fk'])) {
-    // Tells chado_generate_var to only expand 1 level
+    // Tells chado_generate_var to only expand 1 level.
     $options['include_fk'] = array('type_id' => TRUE, 'dbxref_id' => TRUE);
   }
 
-  // Error Checking of parameters
+  // Error Checking of parameters.
   if (!is_array($identifiers)) {
     tripal_report_error(
       'tripal_stock_api',
       TRIPAL_ERROR,
-      "tripal_get_stock: The identifier passed in is expected to be an array with the key
+      "chado_get_stock: The identifier passed in is expected to be an array with the key
         matching a column name in the stock table (ie: stock_id or name). You passed in %identifier.",
       array(
         '%identifier'=> print_r($identifiers, TRUE)
@@ -166,7 +176,7 @@ function tripal_get_multiple_stocks($identifiers, $options = array()) {
     tripal_report_error(
       'tripal_stock_api',
       TRIPAL_ERROR,
-      "tripal_get_stock: You did not pass in anything to identify the stock you want. The identifier
+      "chado_get_stock: You did not pass in anything to identify the stock you want. The identifier
         is expected to be an array with the key matching a column name in the stock table
         (ie: stock_id or name). You passed in %identifier.",
       array(
@@ -175,7 +185,8 @@ function tripal_get_multiple_stocks($identifiers, $options = array()) {
     );
   }
 
-  // If one of the identifiers is property then use chado_get_record_with_property()
+  // If one of the identifiers is property then use 
+  // chado_get_record_with_property().
   if (isset($identifiers['property'])) {
     $property = $identifiers['property'];
     unset($identifiers['property']);
@@ -186,10 +197,11 @@ function tripal_get_multiple_stocks($identifiers, $options = array()) {
     );
   }
 
-  // Else we have a simple case and we can just use chado_generate_var to get the stock
+  // Else we have a simple case and we can just use chado_generate_var to get 
+  //the stock.
   else {
 
-    // Try to get the stock
+    // Try to get the stock.
     $stock = chado_generate_var(
       'stock',
       $identifiers,
@@ -197,12 +209,12 @@ function tripal_get_multiple_stocks($identifiers, $options = array()) {
     );
   }
 
-  // Report an error if $stock is FALSE since then chado_generate_var has failed
+  // Report an error if $stock is FALSE since then chado_generate_var has failed.
   if ($stock === FALSE) {
     tripal_report_error(
       'tripal_stock_api',
       TRIPAL_ERROR,
-      "tripal_get_stock: chado_generate_var() failed to return a stock based on the identifiers
+      "chado_get_stock: chado_generate_var() failed to return a stock based on the identifiers
         you passed in. You should check that your identifiers are correct, as well as, look
         for a chado_generate_var error for additional clues. You passed in %identifier.",
       array(

+ 390 - 0
tripal_chado/api/tripal_chado.DEPRECATED.api.inc

@@ -0,0 +1,390 @@
+<?php
+
+/**
+ * @file
+ *
+ * These api functions are deprecated, if your site is currently using them
+ * please update your code with the newer tripal_chado functions.
+ */
+
+/**
+ * @defgroup tripal_chado_DEPRECATED_api
+ * @ingroup tripal_chado_api
+ * @{
+ * Deprecated legacy api code.
+ * @}
+ */
+
+/**
+ * Publishes content in Chado as a new TripalEntity entity.
+ *
+ * @param $values
+ *   A key/value associative array that supports the following keys:
+ *   - bundle_name:  The name of the the TripalBundle (e.g. bio_data-12345).
+ * @param $job_id
+ *   (Optional) The numeric job ID as provided by the Tripal jobs system. There
+ *   is no need to specify this argument if this function is being called
+ *   outside of the jobs systems.
+ *
+ * @return boolean
+ *   TRUE if all of the records of the given bundle type were published, and
+ *   FALSE if a failure occured.
+ *
+ * @ingroup tripal_chado_DEPRECATED_api
+ */
+function tripal_chado_publish_records($values, $job_id = null) {
+  return chado_publish_records($values, $job_id = null);
+}
+
+/**
+ * Returns an array of tokens based on Tripal Entity Fields.
+ *
+ * @param $base_table
+ *    The name of a base table in Chado.
+ * @return
+ *    An array of tokens where the key is the machine_name of the token.
+ *
+ * @ingroup tripal_chado_DEPRECATED_api
+ */
+function tripal_get_chado_tokens($base_table) {
+  return chado_get_tokens($base_table);
+}
+
+/**
+ * Replace all Chado Tokens in a given string.
+ *
+ * NOTE: If there is no value for a token then the token is removed.
+ *
+ * @param string $string
+ *   The string containing tokens.
+ * @param $record
+ *   A Chado record as generated by chado_generate_var()
+ *
+ * @return
+ *   The string will all tokens replaced with values.
+ *
+ *  @ingroup tripal_chado_DEPRECATED_api
+ */
+function tripal_replace_chado_tokens($string, $record) {
+  return chado_replace_tokens($string, $record);
+}
+
+/**
+ * Migrate Tripal content types
+ *
+ * Migrate specified Tripal content type and publish all its content. The content type
+ * will be created if it does not already exist.
+ *
+ * @param $type
+ *   A type array specifying the vocabular, accession, term_name, and chado data_table
+ *   e.g.
+ *     $type = array(
+ *       'vocabulary' => 'OBI',
+ *       'accession' => '0100026',
+ *       'term_name' => 'organism',
+ *       'storage_args' => array (
+ *         'data_table' => $table
+ *       )
+ *     )
+ * @ingroup tripal_chado_DEPRECATED_api
+ */
+function tripal_chado_migrate_tripal_content_type($type = array()) {
+  return chado_migrate_tripal_content_type($type = array());
+}
+
+
+/**
+ * Add a materialized view to the chado database to help speed data access. This
+ * function supports the older style where postgres column specifications
+ * are provided using the $mv_table, $mv_specs and $indexed variables. It also
+ * supports the newer preferred method where the materialized view is described
+ * using the Drupal Schema API array.
+ *
+ * @param $name
+ *   The name of the materialized view.
+ * @param $modulename
+ *   The name of the module submitting the materialized view
+ *   (e.g. 'tripal_library').
+ * @param $mv_schema
+ *   If using the newer Schema API array to define the materialized view then
+ *   this variable should contain the array or a string representation of the
+ *   array.
+ * @param $query
+ *   The SQL query that loads the materialized view with data.
+ * @param $comment
+ *   A string containing a description of the materialized view.
+ * @param $redirect
+ *   Optional (default: TRUE). By default this function redirects back to
+ *   admin pages. However, when called by Drush we don't want to redirect. This
+ *   parameter allows this to be used as a true API function.
+ *
+ * @ingroup tripal_chado_DEPRECATED_api
+ */
+function tripal_add_mview($name, $modulename, $mv_schema, $query, $comment = null, $redirect = true) {
+  return chado_add_mview($name, $modulename, $mv_schema, $query, $comment, $redirect);
+}
+
+/**
+ * Edits a materialized view to the chado database to help speed data access.
+ * This function supports the older style where postgres column specifications
+ * are provided using the $mv_table, $mv_specs and $indexed variables. It also
+ * supports the newer preferred method where the materialized view is described
+ * using the Drupal Schema API array.
+ *
+ * @param $mview_id
+ *   The mview_id of the materialized view to edit.
+ * @param $name
+ *   The name of the materialized view.
+ * @param $modulename
+ *   The name of the module submitting the materialized view
+ *   (e.g. 'tripal_library').
+ * @param $mv_table
+ *   The name of the table to add to chado. This is the table that can be
+ *   queried.
+ * @param $mv_specs
+ *   The table definition.
+ * @param $indexed
+ *   The columns that are to be indexed.
+ * @param $query
+ *   The SQL query that loads the materialized view with data.
+ * @param $special_index
+ *   currently not used.
+ * @param $comment
+ *   A string containing a description of the materialized view.
+ * @param $mv_schema
+ *   If using the newer Schema API array to define the materialized view then
+ *   this variable should contain the array.
+ *
+ * @ingroup tripal_chado_DEPRECATED_api
+ */
+function tripal_edit_mview($mview_id, $name, $modulename, $mv_table, $mv_specs,
+  $indexed, $query, $special_index, $comment = null, $mv_schema = null) {
+  return chado_edit_mview($mview_id, $name, $modulename, $mv_table, $mv_specs,
+    $indexed, $query, $special_index, $comment = null,$mv_schema = null);
+}
+
+/**
+ * Retrieve the materialized view_id given the name.
+ *
+ * @param $view_name
+ *   The name of the materialized view.
+ *
+ * @return
+ *   The unique identifier for the given view.
+ *
+ * @ingroup tripal_chado_DEPRECATED_api
+ */
+function tripal_get_mview_id($view_name) {
+  return chado_get_mview_id($view_name);
+}
+
+/**
+ * Populates the specified Materialized View.
+ *
+ * @param $mview_id
+ *   The unique ID of the materialized view for the action to be performed on.
+ *
+ * @ingroup tripal_chado_DEPRECATED_api
+ */
+function tripal_refresh_mview($mview_id) {
+  return chado_refresh_mview($mview_id);
+}
+
+/**
+ * Retrieves the list of materialized view IDs and their names.
+ *
+ * @return
+ *   An array of objects with the following properties:  mview_id, name.
+ *
+ * @ingroup tripal_chado_DEPRECATED_api
+ *
+ */
+function tripal_get_mviews() {
+  return chado_get_mviews();
+}
+
+/**
+ * Does the specified action for the specified Materialized View.
+ *
+ * @param $op
+ *   The action to be taken. One of update or delete.
+ * @param $mview_id
+ *   The unique ID of the materialized view for the action to be performed on.
+ *
+ * @ingroup tripal_chado_DEPRECATED_api
+ */
+function tripal_delete_mview($mview_id) {
+  return chado_delete_mview($mview_id);
+}
+
+/**
+ * Update a Materialized View.
+ *
+ * @param $mview_id
+ *   The unique identifier for the materialized view to be updated.
+ *
+ * @return
+ *   True if successful, FALSE otherwise.
+ *
+ * @ingroup tripal_chado_DEPRECATED_api
+ */
+function tripal_populate_mview($mview_id) {
+  return chado_populate_mview($mview_id);
+}
+
+/**
+ * Alter the name of the schema housing Chado and/or Drupal.
+ *
+ * This example implementation shows a solution for the case where your chado
+ * database was well established in the "public" schema and you added Drupal
+ * later in a "drupal" schema. Please note that this has not been tested and
+ * while we can ensure that Tripal will work as expected, we have no control
+ * over whether Drupal is compatible with not being in the public schema. That's
+ * why we recommened the organization we have (ie: Chado in a "chado" schema and
+ * Drupal in the "public schema).
+ *
+ * @param $schema_name
+ *   The current name of the schema as known by Tripal. This is likely the
+ *   default set in tripal_get_schema_name() but in the case of multiple alter
+ *   hooks, it might be different.
+ * @param $context
+ *   This is an array of items to provide context.
+ *     - schema: this is the schema that was passed to tripal_get_schema_name()
+ *       and will be either "chado" or "drupal". This should be used to
+ *       determine you are changing the name of the correct schema.
+ *
+ * @ingroup tripal_chado_DEPRECATED_api
+ */
+function hook_tripal_get_schema_name_alter($schema_name, $context) {
+  return hook_chado_get_schema_name_alter($schema_name, $context);
+}
+
+/**
+ * Retrieve the name of the PostgreSQL schema housing Chado or Drupal.
+ *
+ * @param $schema
+ *   Wehter you want the schema name for 'chado' or 'drupal'. Chado is the
+ *   default.
+ * @return
+ *   The name of the PostgreSQL schema housing the $schema specified.
+ *
+ * @ingroup tripal_chado_DEPRECATED_api
+ */
+function tripal_get_schema_name($schema = 'chado') {
+  return chado_get_schema_name($schema);
+}
+
+
+/**
+ * Adds a new Chado table to the semantic web support for Chado.
+ *
+ * Newly added tables (i.e. custom tables) need to be integrated into the
+ * semantic web infrastructure.  After a new table is created and added to
+ * the Chado schema, this function should be called to indicate that the
+ * table should be included in the semantic web. No associations are made for
+ * the columns. The associations should be added using the
+ * tripal_associate_chado_semweb_term() function.
+ *
+ * If the table has already been added previously then this function does
+ * nothing. It will not overwrite existing assocations.
+ *
+ * Temporary tables (e.g. Tripal tables that begin with 'tripal_' and end with
+ * '_temp', are not supported.
+ *
+ * @param $chado_table
+ *   The name of the Chado table.
+ *
+ * @ingroup tripal_chado_DEPRECATED_api
+ */
+function tripal_add_chado_semweb_table($chado_table) {
+  return chado_add_semweb_table($chado_table);
+}
+
+/**
+ * Associates a controlled vocabulary term with a field in a Chado table.
+ *
+ * For sharing of data via the semantic web we need to associate a
+ * term from a controlled vocabulary with every column of every table in Chado.
+ *
+ * Temporary tables (e.g. Tripal tables that begin with 'tripal_' and end with
+ * '_temp', are not supported.
+ *
+ * @param $chado_table
+ *   The name of the table in Chado. This argument is optional. If left empty
+ *   or set to NULL then all fields in all Chado tables with that have the
+ *   $column_name will be associated with the provided $term.
+ * @param $chado_column
+ *   The column name in the Chado table to which the term should be associated.
+ * @param $term
+ *   A cvterm object as returned by chado_generate_var().
+ * @param $update
+ *   Set to TRUE if the association should be updated to use the new term
+ *   if a term is already associated with the table and column.  Default is
+ *   FALSE.  If not TRUE and a term is already associated, then no change
+ *   occurs.
+ *
+ * @return boolean
+ *   Returns TRUE if the association was made successfully and FALSE otherwise.
+ *
+ *  @ingroup tripal_chado_DEPRECATED_api
+ */
+function tripal_associate_chado_semweb_term($chado_table, $chado_column, $term,
+    $update = false) {
+  return chado_associate_semweb_term($chado_table, $chado_column, $term, $update);
+}
+
+
+/**
+ * Retrieves the term that maps to the given Chado table and field.
+ *
+ * @param $chado_table
+ *   The name of the Chado table.
+ * @param $chado_column
+ *   The name of the Chado field.
+ * @param $options
+ *   An associative array of one or more of the following keys:
+ *     -return_object:  Set to TRUE to return the cvterm object rather than
+ *      the string version of the term.
+ *
+ * @return
+ *   Returns a string-based representation of the term (e.g. SO:0000704). If
+ *   the 'return_object' options is provided then a cvterm object is returned.
+ *   returns NULL if no term is mapped to the table and column.
+ *
+ *  @ingroup tripal_chado_DEPRECATED_api
+ */
+function tripal_get_chado_semweb_term($chado_table, $chado_column, $options = array()) {
+  return chado_get_semweb_term($chado_table, $chado_column, $options);
+}
+
+/**
+ * Formats a controlled vocabulary term from Chado for use with Tripal.
+ *
+ * @param $cvterm
+ *   A cvterm object.
+ * @return
+ *   The semantic web name for the term.
+ *
+ *  @ingroup tripal_chado_DEPRECATED_api
+ */
+function tripal_format_chado_semweb_term($cvterm) {
+  return chado_format_semweb_term($cvterm);
+}
+/**
+ * Retreive the column name in a Chado table that matches a given term.
+ *
+ * @param $chado_table
+ *   The name of the Chado table.
+ * @param $term
+ *   The term. This can be a term name or a unique identifer of the form
+ *   {db}:{accession} or of the form {db}__{term_name}.
+ *
+ * @return
+ *   The name of the Chado column that matches the given term or FALSE if the
+ *   term is not mapped to the Chado table.
+ *
+ *  @ingroup tripal_chado_DEPRECATED_api
+ */
+function tripal_get_chado_semweb_column($chado_table, $term) {
+  return chado_get_semweb_column($chado_table, $term);
+}

+ 28 - 5
tripal_chado/api/tripal_chado.api.inc

@@ -1,5 +1,24 @@
 <?php
 
+/**
+ * @file
+ *
+ * This file contains miscellaneous API functions specific to working with
+ * records in Chado that do not have a home in any other sub category of 
+ * API functions.
+ */
+
+/**
+ * @defgroup tripal_chado_api Chado
+ *
+ * @ingroup tripal_api
+ * The Tripal Chado API is a set of functions for interacting with data 
+ * inside of a Chado relational database. Entities (or pages) in Drupal
+ * that are provided by Tripal can supply data from any supported database 
+ * back-end, and Chado is the default. This API contains a variety of sub
+ * categories (or groups) where functions are organized.  Any extension module
+ * that desires to work with data in Chado will find these functions useful.
+ */
 
 /**
  * Publishes content in Chado as a new TripalEntity entity.
@@ -18,7 +37,7 @@
  *
  * @ingroup tripal_chado_api
  */
-function tripal_chado_publish_records($values, $job_id = NULL) {
+function chado_publish_records($values, $job_id = NULL) {
 
   // We want the job object in order to report progress.
   if (is_object($job_id)) {
@@ -251,8 +270,10 @@ function tripal_chado_publish_records($values, $job_id = NULL) {
  *    The name of a base table in Chado.
  * @return
  *    An array of tokens where the key is the machine_name of the token.
+ * 
+ * @ingroup tripal_chado_api
  */
-function tripal_get_chado_tokens($base_table) {
+function chado_get_tokens($base_table) {
 
   $tokens = array();
   $table_descrip = chado_get_schema($base_table);
@@ -284,7 +305,7 @@ function tripal_get_chado_tokens($base_table) {
         $sub_token_prefix = $base_table . '.' . $left_field;
         $sub_location_prefix = implode(' > ',array($base_table, $left_field));
 
-        $sub_tokens = tripal_get_chado_tokens($table);
+        $sub_tokens = chado_get_tokens($table);
         if (is_array($sub_tokens)) {
           $tokens = array_merge($tokens, $sub_tokens);
         }
@@ -307,10 +328,12 @@ function tripal_get_chado_tokens($base_table) {
  *
  * @return
  *   The string will all tokens replaced with values.
+ * 
+ *  @ingroup tripal_chado_api
  */
-function tripal_replace_chado_tokens($string, $record) {
+function chado_replace_tokens($string, $record) {
   // Get the list of tokens
-  $tokens = tripal_get_chado_tokens($record->tablename);
+  $tokens = chado_get_tokens($record->tablename);
 
   // Determine which tokens were used in the format string
   if (preg_match_all('/\[[^]]+\]/', $string, $used_tokens)) {

+ 47 - 46
tripal_chado/api/tripal_chado.custom_tables.api.inc

@@ -17,9 +17,9 @@
  * using the Drupal Schema API array.
  *
  * @param $table_id
- *   The table_id of the table to edit
+ *   The table_id of the table to edit.
  * @param $table_name
- *   The name of the custom table
+ *   The name of the custom table.
  * @param $schema
  *   Use the Schema API array to define the custom table.
  * @param $skip_if_exists
@@ -33,32 +33,32 @@ function chado_edit_custom_table($table_id, $table_name, $schema, $skip_if_exist
 
   $transaction = db_transaction();
   try {
-    // Create a new record
+    // Create a new record.
     $record = new stdClass();
     $record->table_id = $table_id;
     $record->table_name = $table_name;
     $record->schema = serialize($schema);
 
-    // get the current custom table record
+    // Get the current custom table record.
     $sql = "SELECT * FROM {tripal_custom_tables} WHERE table_id = :table_id";
     $results = db_query($sql, array(':table_id' => $table_id));
     $custom_table = $results->fetchObject();
 
-    // if this is a materialized view then don't allow editing with this function
+    // If this is a materialized view then don't allow editing with this function.
     if ($custom_table->mview_id) {
-      tripal_report_error('tripal_chado', TRIPAL_ERROR, "Please use the tripal_edit_mview() function to edit this custom table as it is a materialized view.", array());
+      tripal_report_error('tripal_chado', TRIPAL_ERROR, "Please use the chado_edit_mview() function to edit this custom table as it is a materialized view.", array());
       drupal_set_message("This custom table is a materialized view. Please use the "  . l('Materialized View', 'admin/tripal/storage/chado/mviews') . " interface to edit it.", 'error');
       return FALSE;
     }
 
-    // if the user changed the table name, we want to drop the old one and force
+    // If the user changed the table name, we want to drop the old one and force
     // creation of the new one.
     if ($custom_table->table_name != $table_name) {
       chado_query("DROP TABLE %s", $custom_table->table_name);
       $skip_if_exists = 0; // we want to create the table
     }
 
-    // if skip creation is not set, then drop the table from chado if it exists
+    // If skip creation is not set, then drop the table from chado if it exists.
     if (!$skip_if_exists) {
       if (db_table_exists($custom_table->table_name)) {
         chado_query("DROP TABLE %s", $custom_table->table_name);
@@ -66,13 +66,13 @@ function chado_edit_custom_table($table_id, $table_name, $schema, $skip_if_exist
       }
     }
 
-    // update the custom table record and run the create custom table function
+    // Update the custom table record and run the create custom table function.
     drupal_write_record('tripal_custom_tables', $record, 'table_id');
     $success = chado_create_custom_table ($table_name, $schema, $skip_if_exists);
 
     // Re-add the custom table to the semantic web interface to pick up any
     // changes in fields.
-    tripal_add_chado_semweb_table($table_name);
+    chado_add_semweb_table($table_name);
   }
   catch (Exception $e) {
     $transaction->rollback();
@@ -98,17 +98,17 @@ function chado_edit_custom_table($table_id, $table_name, $schema, $skip_if_exist
  * added to the tripal_custom_tables and no table is created in Chado.
  *
  * If you are creating a materialized view do not use this function, but rather
- * use the tripal_add_mview(). A materialized view is also considered a custom table
- * and an entry for it will be added to both the tripal_mviews and
- * tripal_custom_tables tables, but only if the tripal_add_mview() function is
+ * use the chado_add_mview(). A materialized view is also considered a custom 
+ * table and an entry for it will be added to both the tripal_mviews and
+ * tripal_custom_tables tables, but only if the chado_add_mview() function is
  * used. The optional $mview_id parameters in this function is intended
- * for use by the tripal_add_mview() function when it calls this function
+ * for use by the chado_add_mview() function when it calls this function
  * to create the table.
  *
  * @param $table
  *   The name of the table to create.
  * @param $schema
- *   A Drupal-style Schema API definition of the table
+ *   A Drupal-style Schema API definition of the table.
  * @param $skip_if_exists
  *   Set as TRUE to skip dropping and re-creation of the table if it already
  *   exists.  This is useful if the table was already created through another
@@ -117,14 +117,14 @@ function chado_edit_custom_table($table_id, $table_name, $schema, $skip_if_exist
  * @param $mview_id
  *   Optional. If this custom table is also a materialized view then provide
  *   it's mview_id. This paramter is intended only when this function
- *   is called by the tripal_add_mview() function. When creating a custom
+ *   is called by the chado_add_mview() function. When creating a custom
  *   table you shouldn't need to use this parameter.
  * @param $redirect
  *   Optional (default: TRUE). By default this function redirects back to
  *   admin pages. However, when called by Drush we don't want to redirect. This
  *   parameter allows this to be used as a true API function.
  * @return
- *   TRUE on success, FALSE on failure
+ *   TRUE on success, FALSE on failure.
  *
  * @ingroup tripal_custom_tables_api
  */
@@ -153,32 +153,33 @@ function chado_create_custom_table($table, $schema, $skip_if_exists = TRUE,
   $created = 0;
   $recreated = 0;
 
-  $chado_schema = tripal_get_schema_name('chado');
+  $chado_schema = chado_get_schema_name('chado');
   $chado_dot = $chado_schema . '.';
 
   $transaction = db_transaction();
   try {
-    // see if the table entry already exists in the tripal_custom_tables table.
+    // See if the table entry already exists in the tripal_custom_tables table.
     $sql = "SELECT * FROM {tripal_custom_tables} WHERE table_name = :table_name";
     $results = db_query($sql, array(':table_name' => $table));
     $centry = $results->fetchObject();
 
-    // check to see if the table already exists in the chado schema
+    // Check to see if the table already exists in the chado schema.
     $exists = chado_table_exists($table);
 
-    // if the table does not exist then create it
+    // If the table does not exist then create it.
     if (!$exists) {
       $ret = db_create_table($chado_dot . $table, $schema);
       $created = 1;
     }
 
-    // if the table exists in Chado and in our custom table and
-    // skip creation is turned off then drop and re-create the table
+    // If the table exists in Chado and in our custom table and
+    // skip creation is turned off then drop and re-create the table.
     if ($exists and is_object($centry) and !$skip_if_exists) {
 
-      // drop the table we'll recreate it with the new schema
+      // Drop the table we'll recreate it with the new schema.
       chado_query('DROP TABLE {' . $table . '}');
-      // remove any 'referring_tables' from the array as the db_create_table doesn't use that
+      // Remove any 'referring_tables' from the array as the 
+      // db_create_table doesn't use that.
       $new_schema = $schema;
       if (array_key_exists('referring_tables', $new_schema)) {
         unset($new_schema['referring_tables']);
@@ -187,7 +188,7 @@ function chado_create_custom_table($table, $schema, $skip_if_exists = TRUE,
       $recreated = 1;
     }
 
-    // add an entry in the tripal_custom_table
+    // Add an entry in the tripal_custom_table.
     $record = new stdClass();
     $record->table_name = $table;
     $record->schema = serialize($schema);
@@ -195,17 +196,17 @@ function chado_create_custom_table($table, $schema, $skip_if_exists = TRUE,
       $record->mview_id = $mview_id;
     }
 
-    // if an entry already exists then remove it
+    // If an entry already exists then remove it.
     if ($centry) {
       $sql = "DELETE FROM {tripal_custom_tables} WHERE table_name = :table_name";
       db_query($sql, array(':table_name' => $table));
     }
     $success = drupal_write_record('tripal_custom_tables', $record);
 
-    // now add any foreign key constraints
+    // Now add any foreign key constraints.
     if (($created or !$skip_if_exists) and array_key_exists('foreign keys', $schema)) {
 
-      // iterate through the foreign keys and add each one
+      // Iterate through the foreign keys and add each one.
       $fkeys = $schema['foreign keys'];
       foreach ($fkeys as $fktable => $fkdetails) {
         $relations = $fkdetails['columns'];
@@ -221,8 +222,8 @@ function chado_create_custom_table($table, $schema, $skip_if_exists = TRUE,
       }
     }
 
-    // Add the custom table to the semantic web interface
-    tripal_add_chado_semweb_table($table);
+    // Add the custom table to the semantic web interface.
+    chado_add_semweb_table($table);
   }
   catch (Exception $e) {
     $transaction->rollback();
@@ -264,10 +265,10 @@ function chado_create_custom_table($table, $schema, $skip_if_exists = TRUE,
  * a user and needs validation.
  *
  * @param $schema_array
- *   the Drupal Schema API compatible array
+ *   the Drupal Schema API compatible array.
  *
  * @return
- *   An empty string for success or a message string for failure
+ *   An empty string for success or a message string for failure.
  *
  * @ingroup tripal_custom_tables_api
  */
@@ -283,7 +284,7 @@ function chado_validate_custom_table_schema($schema_array) {
   }
 
 
-  // check index length
+  // Check index length.
   if (array_key_exists('indexes', $schema_array)) {
     foreach ($schema_array['indexes'] as $index_name => $details) {
       if (strlen($schema_array['table'] . '_' . $index_name) > 60) {
@@ -295,7 +296,7 @@ function chado_validate_custom_table_schema($schema_array) {
     }
   }
 
-  // check unique key length
+  // Check unique key length.
   if (array_key_exists('unique keys', $schema_array)) {
     foreach ($schema_array['unique keys'] as $index_name => $details) {
       if (strlen($schema_array['table'] . '_' . $index_name) > 60) {
@@ -309,13 +310,13 @@ function chado_validate_custom_table_schema($schema_array) {
 
 }
 /**
- * Retrieve the custom table id given the name
+ * Retrieve the custom table id given the name.
  *
  * @param $table_name
- *   The name of the custom table
+ *   The name of the custom table.
  *
  * @return
- *   The unique identifier for the given table
+ *   The unique identifier for the given table.
  *
  * @ingroup tripal_custom_tables_api
  */
@@ -335,7 +336,7 @@ function chado_get_custom_table_id($table_name) {
 /**
  * Retrieves the list of custom tables in this site.
  *
- * @returns
+ * @return
  *   An associative array where the key and value pairs are the table names.
  *
  * @ingroup tripal_custom_tables_api
@@ -356,10 +357,10 @@ function chado_get_custom_table_names($include_mview = TRUE) {
   return $tables;
 }
 /**
- * Deletes the specified custom table
+ * Deletes the specified custom table.
  *
  * @param $table_id
- *   The unique ID of the custom table for the action to be performed on
+ *   The unique ID of the custom table for the action to be performed on.
  *
  * @ingroup tripal_custom_tables_api
  */
@@ -371,26 +372,26 @@ function chado_delete_custom_table($table_id) {
     return '';
   }
 
-  // get this table details
+  // Get this table details.
   $sql = "SELECT * FROM {tripal_custom_tables} WHERE table_id = :table_id";
   $results = db_query($sql, array(':table_id' => $table_id));
   $custom_table = $results->fetchObject();
 
-  // if this is a materialized view then don't allow deletion with this function
+  // If this is a materialized view then don't allow deletion with this function.
   if ($custom_table->mview_id) {
-    tripal_report_error('tripal_chado', TRIPAL_ERROR, "Please use the tripal_delete_mview() function to delete this custom table as it is a materialized view. Table not deleted.", array());
+    tripal_report_error('tripal_chado', TRIPAL_ERROR, "Please use the chado_delete_mview() function to delete this custom table as it is a materialized view. Table not deleted.", array());
     drupal_set_message("This custom table is a materialized view. Please use the "  . l('Materialized View', 'admin/tripal/storage/chado/mviews') . " interface to delete it.", 'error');
     return FALSE;
   }
 
-  // remove the entry from the tripal_custom tables table
+  // Remove the entry from the tripal_custom tables table.
   $sql = "DELETE FROM {tripal_custom_tables} WHERE table_id = $table_id";
   $success = db_query($sql);
   if ($success) {
     drupal_set_message(t("Custom Table '%name' removed", array('%name' => $custom_table->table_name)));
   }
 
-  // drop the table from chado if it exists
+  // Drop the table from chado if it exists.
   if (chado_table_exists($custom_table->table_name)) {
     $success = chado_query("DROP TABLE {" .  $custom_table->table_name . "}");
     if ($success) {

+ 20 - 8
tripal_chado/api/tripal_chado.migrate.api.inc

@@ -1,4 +1,16 @@
 <?php 
+/**
+ * @file
+ * Provides an application programming interface (API) to migrate content.
+ */
+
+/**
+ * @defgroup tripal_chado_migrate_api Chado Entity
+ * @ingroup tripal_chado_api
+ * @{
+ * Provides an application programming interface (API) to migrate content.
+ * @}
+ */
 
 /**
  * Migrate Tripal content types
@@ -17,25 +29,25 @@
  *         'data_table' => $table
  *       )
  *     )
- * 
+ * @ingroup tripal_chado_migrate_api
  */
-function tripal_chado_migrate_tripal_content_type($type = array()) {
+function chado_migrate_tripal_content_type($type = array()) {
     
-  // Check if the term already exists
+  // Check if the term already exists.
   $term = tripal_load_term_entity($type);
-  // If term doesn't exist, create a new bundle for this term
+  // If term doesn't exist, create a new bundle for this term.
   if (!$term) {
     print("Creating bundle for term '" . $type['term_name'] . "'...\n");
     $success = tripal_create_bundle($type);
     $term = tripal_load_term_entity($type);
   }
-  // Create bundle name
+  // Create bundle name.
   $bundle_name = 'bio_data_' . $term->id;
     
-  // Publish records for the bundle
+  // Publish records for the bundle.
   $value = array(
     'sync_node' => 1,
     'bundle_name' => $bundle_name
   );
-  tripal_chado_publish_records($value);
-}
+  chado_publish_records($value);
+}

+ 62 - 58
tripal_chado/api/tripal_chado.mviews.api.inc

@@ -1,16 +1,17 @@
 <?php
 /**
  * @file
- * Provides an application programming interface (API) to manage materialized views in Chado.
+ * Provides an application programming interface (API) to manage materialized 
+ * views in Chado.
  */
 
 /**
  * @defgroup tripal_mviews_api Chado Materalized Views
  * @ingroup tripal_chado_api
  * @{
- * Provides an application programming interface (API) to manage materialized views in Chado.
- * The Perl-based chado comes with an interface for managing materialzed views.  This
- * API provides an alternative Drupal-based method.
+ * Provides an application programming interface (API) to manage materialized 
+ * views in Chado The Perl-based chado comes with an interface for managing 
+ * materialzed views.  This API provides an alternative Drupal-based method.
  * @}
  */
 
@@ -24,15 +25,16 @@
  * @param $name
  *   The name of the materialized view.
  * @param $modulename
- *   The name of the module submitting the materialized view (e.g. 'tripal_library')
+ *   The name of the module submitting the materialized view 
+ *   (e.g. 'tripal_library').
  * @param $mv_schema
  *   If using the newer Schema API array to define the materialized view then
  *   this variable should contain the array or a string representation of the
  *   array.
  * @param $query
- *   The SQL query that loads the materialized view with data
+ *   The SQL query that loads the materialized view with data.
  * @param $comment
- *   A string containing a description of the materialized view
+ *   A string containing a description of the materialized view.
  * @param $redirect
  *   Optional (default: TRUE). By default this function redirects back to
  *   admin pages. However, when called by Drush we don't want to redirect. This
@@ -40,7 +42,7 @@
  *
  * @ingroup tripal_mviews_api
  */
-function tripal_add_mview($name, $modulename, $mv_schema, $query, $comment = NULL, $redirect = TRUE) {
+function chado_add_mview($name, $modulename, $mv_schema, $query, $comment = NULL, $redirect = TRUE) {
 
   if (!array_key_exists('table', $mv_schema)) {
      tripal_report_error('tripal_chado', TRIPAL_ERROR,
@@ -50,7 +52,7 @@ function tripal_add_mview($name, $modulename, $mv_schema, $query, $comment = NUL
 
   $mv_table = $mv_schema['table'];
 
-  // see if the mv_table name already exsists
+  // See if the mv_table name already exsists.
   $mview_id = db_query(
     'SELECT mview_id FROM {tripal_mviews} WHERE name = :name',
     array(':name' => $name))->fetchField();
@@ -58,7 +60,7 @@ function tripal_add_mview($name, $modulename, $mv_schema, $query, $comment = NUL
   if(!$mview_id) {
     $transaction = db_transaction();
     try {
-      // Create a new record
+      // Create a new record.
       $record = new stdClass();
       $record->name = $name;
       $record->modulename = $modulename;
@@ -66,21 +68,21 @@ function tripal_add_mview($name, $modulename, $mv_schema, $query, $comment = NUL
       $record->query = $query;
       $record->comment = $comment;
 
-      // convert the schema into a string format
+      // Convert the schema into a string format.
       $str_schema = var_export($mv_schema, TRUE);
       $str_schema = preg_replace('/=>\s+\n\s+array/', '=> array', $str_schema);
       $record->mv_schema = $str_schema;
 
-      // add the record to the tripal_mviews table and if successful
-      // create the new materialized view in the chado schema
+      // Add the record to the tripal_mviews table and if successful
+      // create the new materialized view in the chado schema.
       if (drupal_write_record('tripal_mviews', $record)) {
 
-        // drop the table from chado if it exists
+        // Drop the table from chado if it exists.
         if (chado_table_exists($mv_table)) {
           $sql = 'DROP TABLE {' . $mv_table . '}';
           chado_query($sql);
         }
-        // create the table
+        // Create the table.
         chado_create_custom_table($mv_table, $mv_schema, 0, $record->mview_id, $redirect);
       }
     }
@@ -102,37 +104,39 @@ function tripal_add_mview($name, $modulename, $mv_schema, $query, $comment = NUL
 }
 
 /**
- * Edits a materialized view to the chado database to help speed data access. This
- * function supports the older style where postgres column specifications
+ * Edits a materialized view to the chado database to help speed data access. 
+ * This function supports the older style where postgres column specifications
  * are provided using the $mv_table, $mv_specs and $indexed variables. It also
  * supports the newer preferred method where the materialized view is described
  * using the Drupal Schema API array.
  *
  * @param $mview_id
- *   The mview_id of the materialized view to edit
+ *   The mview_id of the materialized view to edit.
  * @param $name
  *   The name of the materialized view.
  * @param $modulename
- *   The name of the module submitting the materialized view (e.g. 'tripal_library')
+ *   The name of the module submitting the materialized view 
+ *   (e.g. 'tripal_library').
  * @param $mv_table
- *   The name of the table to add to chado. This is the table that can be queried.
+ *   The name of the table to add to chado. This is the table that can be 
+ *   queried.
  * @param $mv_specs
- *   The table definition
+ *   The table definition.
  * @param $indexed
- *   The columns that are to be indexed
+ *   The columns that are to be indexed.
  * @param $query
- *   The SQL query that loads the materialized view with data
+ *   The SQL query that loads the materialized view with data.
  * @param $special_index
- *   currently not used
+ *   currently not used.
  * @param $comment
- *   A string containing a description of the materialized view
+ *   A string containing a description of the materialized view.
  * @param $mv_schema
  *   If using the newer Schema API array to define the materialized view then
  *   this variable should contain the array.
  *
  * @ingroup tripal_mviews_api
  */
-function tripal_edit_mview($mview_id, $name, $modulename, $mv_table, $mv_specs,
+function chado_edit_mview($mview_id, $name, $modulename, $mv_table, $mv_specs,
   $indexed, $query, $special_index, $comment = NULL, $mv_schema = NULL) {
 
   $transaction = db_transaction();
@@ -202,17 +206,17 @@ function tripal_edit_mview($mview_id, $name, $modulename, $mv_table, $mv_specs,
 }
 
 /**
- * Retrieve the materialized view_id given the name
+ * Retrieve the materialized view_id given the name.
  *
  * @param $view_name
- *   The name of the materialized view
+ *   The name of the materialized view.
  *
  * @return
- *   The unique identifier for the given view
+ *   The unique identifier for the given view.
  *
  * @ingroup tripal_mviews_api
  */
-function tripal_get_mview_id($view_name) {
+function chado_get_mview_id($view_name) {
   if (db_table_exists('tripal_mviews')) {
     $sql = "SELECT * FROM {tripal_mviews} WHERE name = :name";
     $results = db_query($sql, array(':name' => $view_name));
@@ -231,7 +235,7 @@ function tripal_get_mview_id($view_name) {
  * @returns
  *   An associative array where the key and value pairs are the table names.
  *
- * @ingroup tripal_custom_tables_api
+ * @ingroup tripal_mviews_api
  */
 function chado_get_mview_table_names() {
 
@@ -248,42 +252,42 @@ function chado_get_mview_table_names() {
 }
 
 /**
- * Populates the specified Materialized View
+ * Populates the specified Materialized View.
  *
  * @param $mview_id
- *   The unique ID of the materialized view for the action to be performed on
+ *   The unique ID of the materialized view for the action to be performed on.
  *
  * @ingroup tripal_mviews_api
  */
-function tripal_refresh_mview($mview_id) {
+function chado_refresh_mview($mview_id) {
   global $user;
 
   if (!$mview_id) {
     return '';
   }
 
-  // get this mview details
+  // Get this mview details.
   $sql = "SELECT * FROM {tripal_mviews} WHERE mview_id = :mview_id";
   $results = db_query($sql, array(':mview_id' => $mview_id));
   $mview = $results->fetchObject();
 
-  // add a job to populate the mview
+  // Add a job to populate the mview.
   $args = array("$mview_id");
   tripal_add_job("Populate materialized view '$mview->name'", 'tripal_chado',
-     'tripal_populate_mview', $args, $user->uid);
+    'chado_populate_mview', $args, $user->uid);
 
 }
 
 /**
- * Retrieves the list of materialized view IDs and their names
+ * Retrieves the list of materialized view IDs and their names.
  *
  * @return
- *   An array of objects with the following properties:  mview_id, name
+ *   An array of objects with the following properties:  mview_id, name.
  *
  * @ingroup tripal_mviews_api
  *
  */
-function tripal_get_mviews() {
+function chado_get_mviews() {
 
   $results = db_select('tripal_mviews', 'tm')
     ->fields('tm', array('mview_id', 'name'))
@@ -297,36 +301,36 @@ function tripal_get_mviews() {
 }
 
 /**
- * Does the specified action for the specified Materialized View
+ * Does the specified action for the specified Materialized View.
  *
  * @param $op
- *   The action to be taken. One of update or delete
+ *   The action to be taken. One of update or delete.
  * @param $mview_id
- *   The unique ID of the materialized view for the action to be performed on
+ *   The unique ID of the materialized view for the action to be performed on.
  *
  * @ingroup tripal_mviews_api
  */
-function tripal_delete_mview($mview_id) {
+function chado_delete_mview($mview_id) {
   global $user;
 
   if (!$mview_id) {
     return '';
   }
 
-  // get this mview details
+  // Get this mview details.
   $sql = "SELECT * FROM {tripal_mviews} WHERE mview_id = :mview_id";
   $results = db_query($sql, array(':mview_id' => $mview_id));
   $mview = $results->fetchObject();
 
-  // if op is to delete then do so
-  // remove the mview from the tripal_mviews table
+  // If op is to delete then do so.
+  // Remove the mview from the tripal_mviews table.
   $sql = "DELETE FROM {tripal_mviews} WHERE mview_id = $mview_id";
   db_query($sql);
 
-  // does the table already exist?
+  // Does the table already exist?
   $mview_exists = chado_table_exists($mview->mv_table);
 
-  // drop the table from chado if it exists
+  // Drop the table from chado if it exists.
   if ($mview_exists) {
     $sql = "DROP TABLE {" . $mview->mv_table . "}";
     $success = chado_query($sql);
@@ -340,29 +344,29 @@ function tripal_delete_mview($mview_id) {
 }
 
 /**
- * Update a Materialized View
+ * Update a Materialized View.
  *
  * @param $mview_id
- *   The unique identifier for the materialized view to be updated
+ *   The unique identifier for the materialized view to be updated.
  *
  * @return
- *   True if successful, FALSE otherwise
+ *   True if successful, FALSE otherwise.
  *
  * @ingroup tripal_mviews_api
  */
-function tripal_populate_mview($mview_id) {
+function chado_populate_mview($mview_id) {
   $sql = "SELECT * FROM {tripal_mviews} WHERE mview_id = :mview_id ";
   $results = db_query($sql, array(':mview_id' => $mview_id));
   $mview = $results->fetchObject();
   if ($mview) {
-    // execute the query inside a transaction so that it doesn't destroy existing data
-    // that may leave parts of the site unfunctional
+    // Execute the query inside a transaction so that it doesn't destroy 
+    // existing data that may leave parts of the site unfunctional.
     $transaction = db_transaction();
     $previous_db = chado_set_active('chado');  // use chado database
     try {
       $success = chado_query("DELETE FROM {" . $mview->mv_table . "}");
       $success = chado_query("INSERT INTO {" . $mview->mv_table . "} ($mview->query)");
-      // if success get the number of results and update the table record
+      // If success get the number of results and update the table record.
       if ($success) {
         $sql = "SELECT count(*) as cnt FROM {" . $mview->mv_table . "}";
         $results = chado_query($sql);
@@ -373,7 +377,7 @@ function tripal_populate_mview($mview_id) {
         $record->status = "Populated with " . number_format($count->cnt) . " rows";
         drupal_write_record('tripal_mviews', $record, 'mview_id');
       }
-      // if not success then throw an error
+      // If not success then throw an error.
       else {
         throw new Exception("ERROR populating the materialized view ". $mview->mv_table . ". See Drupal's recent log entries for details.");
       }
@@ -382,7 +386,7 @@ function tripal_populate_mview($mview_id) {
     catch (Exception $e) {
       $transaction->rollback();
       chado_set_active($previous_db);
-      // print and save the error message
+      // Print and save the error message.
       $record = new stdClass();
       $record->mview_id = $mview_id;
       $record->status = "ERROR populating $mview->mv_table. See Drupal's recent log entries for details.\n";

+ 43 - 37
tripal_chado/api/tripal_chado.property.api.inc

@@ -6,11 +6,11 @@
 
 /**
  * @defgroup tripal_chado_prop_api Chado Properties
- *
  * @ingroup tripal_api
+ * @{
  * The Chado Properties API provides a set of functions for interacting
  * with the any chado prop table.
- *
+ * @}
  */
 
 /**
@@ -39,8 +39,8 @@
  * @return
  *   An array in the same format as that generated by the function
  *   chado_generate_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
+ *   is a single object.  If more than one record is returned then it is an 
+ *   array of objects
  *
  * @ingroup tripal_chado_prop_api
  */
@@ -76,7 +76,7 @@ function chado_get_property($record, $property) {
     $type['cvterm_id'] = $type_id;
   }
 
-  // Make sure the CV term exists;
+  // Make sure the CV term exists.
   $options = array();
   $term = chado_select_record('cvterm', array('cvterm_id'), $type, $options);
   if (!$term or count($term) == 0) {
@@ -92,17 +92,17 @@ function chado_get_property($record, $property) {
         array('%property' => print_r($property, TRUE)));    return FALSE;
   }
 
-  // get the foreign key for this property table
+  // Get the foreign key for this property table.
   $table_desc = chado_get_schema($base_table . 'prop');
   $fkcol = key($table_desc['foreign keys'][$base_table]['columns']);
 
-  // construct the array of values to be selected
+  // Construct the array of values to be selected.
   $values = array(
     $fkcol => $base_id,
     'type_id' => $type,
   );
 
-  // if we have the unique property_id make sure to add that to the values
+  // If we have the unique property_id make sure to add that to the values.
   if ($prop_id) {
     $property_pkey = $table_desc['primary key'][0];
     $values[$property_pkey] = $prop_id;
@@ -127,7 +127,7 @@ function chado_get_property($record, $property) {
  *   should be assigned.  The following keys must be used:
  *     -table: The base table for which the property should be inserted.
  *         Thus to insert a property for a feature the base_table=feature and
- *         property is inserted into featureprop
+ *         property is inserted into featureprop.
  *     -id: The primary key value of the base table. The property will be
  *         associated with the record that matches this id.
  * @param $property
@@ -154,7 +154,7 @@ function chado_get_property($record, $property) {
  *        'force_rank' is set then an error will occur.
  *
  * @return
- *   Return TRUE if successful and FALSE otherwise
+ *   Return TRUE if successful and FALSE otherwise.
  *
  * @ingroup tripal_chado_prop_api
  */
@@ -191,9 +191,9 @@ function chado_insert_property($record, $property, $options = array()) {
     }
     else {
       if (!$force_rank) {
-        // iterate through the properties returned and check to see if the
+        // 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
+        // and insert the same property but with this new value.
         foreach ($props as $prop) {
           if ($prop->rank > $rank) {
             $rank = $prop->rank;
@@ -202,7 +202,7 @@ function chado_insert_property($record, $property, $options = array()) {
             return TRUE;
           }
         }
-        // now add 1 to the rank
+        // Now add 1 to the rank.
         $rank++;
       }
       else {
@@ -234,7 +234,7 @@ function chado_insert_property($record, $property, $options = array()) {
     $values['cvterm_id'] = $type_id;
   }
 
-  // Make sure the CV term exists;
+  // Make sure the CV term exists.
   $options = array();
   $term = chado_select_record('cvterm', array('cvterm_id'), $values, $options);
   if (!$term or count($term) == 0) {
@@ -251,7 +251,7 @@ function chado_insert_property($record, $property, $options = array()) {
   }
 
 
-    //Check that the cvalue property exists
+    // Check that the cvalue property exists.
     if ($cvalue_id){
         $term = chado_select_record('cvterm', array('cvterm_id'), array('cvterm_id' => $cvalue_id), $options);
        if (!$term or count($term) == 0) {
@@ -264,7 +264,7 @@ function chado_insert_property($record, $property, $options = array()) {
   }
 
 
-  // Get the foreign key for this property table
+  // Get the foreign key for this property table.
   $table_desc = chado_get_schema($base_table . 'prop');
   $fkcol = key($table_desc['foreign keys'][$base_table]['columns']);
 
@@ -303,7 +303,8 @@ function chado_insert_property($record, $property, $options = array()) {
  *     -value: The specific value for the property.
  *     -rank: The specific rank for the property.
  *     -cvalue_id: The cvterm_id of the value for the property.
- *      **note** cvalue_id is an anticipated column in the the next Chado release (1.4).  It is included here for early adopters.
+ *      **note** cvalue_id is an anticipated column in the the next Chado 
+ *      release (1.4).  It is included here for early adopters.
  *
  * @param $options
  *   An associative array containing the following keys:
@@ -312,7 +313,7 @@ function chado_insert_property($record, $property, $options = array()) {
  *
  *
  * @return
- *   Return TRUE on Update/Insert and FALSE otherwise
+ *   Return TRUE on Update/Insert and FALSE otherwise.
  *
  * @ingroup tripal_chado_prop_api
  */
@@ -332,7 +333,7 @@ function chado_update_property($record, $property, $options = array()) {
 
   $insert_if_missing = array_key_exists('insert_if_missing', $options) ? $options['insert_if_missing'] : FALSE;
 
-  // first see if the property is missing (we can't update a missing property
+  // First see if the property is missing (we can't update a missing property.
   $prop = chado_get_property($record, $property);
   if (count($prop) == 0) {
     if ($insert_if_missing) {
@@ -360,7 +361,7 @@ function chado_update_property($record, $property, $options = array()) {
     $type['cvterm_id'] = $type_id;
   }
 
-  // Make sure the CV term exists;
+  // Make sure the CV term exists.
   $options = array();
   $term = chado_select_record('cvterm', array('cvterm_id'), $type, $options);
   if (!$term or count($term) == 0) {
@@ -378,11 +379,11 @@ function chado_update_property($record, $property, $options = array()) {
   }
 
 
-  // Get the foreign key for this property table
+  // Get the foreign key for this property table.
   $table_desc = chado_get_schema($base_table . 'prop');
   $fkcol = key($table_desc['foreign keys'][$base_table]['columns']);
 
-  // construct the array that will match the exact record to update
+  // Construct the array that will match the exact record to update.
   $match = array(
     $fkcol => $base_id,
     'type_id' => $type,
@@ -404,7 +405,7 @@ function chado_update_property($record, $property, $options = array()) {
     $values['rank'] = $rank;
   }
 
-  // If a cvalue_id is supplied, check that it is a valid cvterm
+  // If a cvalue_id is supplied, check that it is a valid cvterm.
     if ($cvalue_id) {
         $term = chado_select_record('cvterm', array('cvterm_id'), array('cvterm_id' => $cvalue_id), $options);
         if (!$term or count($term) == 0) {
@@ -417,7 +418,7 @@ function chado_update_property($record, $property, $options = array()) {
   }
 
   // If we have the unique property_id then we can also update the type
-  // thus add it to the values to be updated
+  // thus add it to the values to be updated.
   if ($prop_id) {
     $values['type_id'] = $type;
   }
@@ -426,7 +427,7 @@ function chado_update_property($record, $property, $options = array()) {
 }
 
 /**
- * Deletes a property for a given base table record using the property name
+ * Deletes a property for a given base table record using the property name.
  *
  * @param $record
  *   An associative array used to identify the record to which the property
@@ -450,7 +451,7 @@ function chado_update_property($record, $property, $options = array()) {
  *     -rank: The specific rank for the property.
  *
  * @return
- *   Return TRUE on successful deletion and FALSE otherwise
+ *   Return TRUE on successful deletion and FALSE otherwise.
  *
  * @ingroup tripal_chado_prop_api
  */
@@ -468,7 +469,7 @@ function chado_delete_property($record, $property) {
   $rank        = array_key_exists('rank', $property) ? $property['rank'] : 0;
 
 
-  // Build the values array for checking if the CVterm exists
+  // Build the values array for checking if the CVterm exists.
   $type = array();
   if ($cv_id) {
     $type['cv_id'] = $cv_id;
@@ -485,7 +486,7 @@ function chado_delete_property($record, $property) {
     $type['cvterm_id'] = $type_id;
   }
 
-  // Make sure the CV term exists;
+  // Make sure the CV term exists.
   $options = array();
   $term = chado_select_record('cvterm', array('cvterm_id'), $type, $options);
   if (!$term or count($term) == 0) {
@@ -501,19 +502,20 @@ function chado_delete_property($record, $property) {
         array('%property' => print_r($property, TRUE)));    return FALSE;
   }
 
-  // get the foreign key for this property table
+  // Get the foreign key for this property table.
   $table_desc = chado_get_schema($base_table . 'prop');
   $fkcol = key($table_desc['foreign keys'][$base_table]['columns']);
 
-  // If we have the unique property_id, make sure to use it in the match to ensure
-  // we get the exact record. Doesn't rely on there only being one property of that type
+  // If we have the unique property_id, make sure to use it in the match to 
+  // ensure we get the exact record. Doesn't rely on there only being one 
+  // property of that type.
   if ($prop_id) {
     $property_pkey = $table_desc['primary key'][0];
     $match = array(
       $property_pkey => $prop_id
     );
   }
-  // construct the array that will match the exact record to update
+  // Construct the array that will match the exact record to update.
   else {
     $match = array(
       $fkcol => $record_id,
@@ -548,14 +550,15 @@ function chado_delete_property($record, $property) {
  *     -value: The specific value for the property.
  *     -rank: The specific rank for the property.
  *     -cvalue_id: The cvterm_id of the value for the property.
- *      **note** cvalue_id is an anticipated column in the the next Chado release (1.4).  It is included here for early adopters.
+ *      **note** cvalue_id is an anticipated column in the the next Chado 
+ *      release (1.4).  It is included here for early adopters.
  * 
  * @param $options
  *   An array of options supported by chado_generate_var(). These keys
  *   are used for generating the cvterm objects returned by this function.
  *
  * @return
- *   An array of chado variables with the given property
+ *   An array of chado variables with the given property.
  *
  * @ingroup tripal_chado_prop_api
  */
@@ -622,10 +625,11 @@ function chado_get_record_with_property($record, $property, $options = array())
     $values[$foreignkey_name] = $base_records;
   }
 
-  // Now select the ids of the base table that have the properties we want that match.
+  // Now select the ids of the base table that have the properties we want that 
+  // match.
   $select = chado_select_record($property_table, array($foreignkey_name), $values);
 
-  // For each of these ids, pull out the full base records
+  // For each of these ids, pull out the full base records.
   $records = array();
   foreach ($select as $s) {
     $id = $s->{$foreignkey_name};
@@ -643,8 +647,10 @@ function chado_get_record_with_property($record, $property, $options = array())
  * @param $prop_table
  *   The name of the property table.
  * @throws Exception
+ * 
  * @return
  *   An array of cvterm objects as created by chado_generate_var().
+ * 
  * @ingroup tripal_chado_prop_api
  */
 function chado_get_table_property_types($prop_table) {
@@ -660,4 +666,4 @@ function chado_get_table_property_types($prop_table) {
     $types[] = chado_generate_var('cvterm', array('cvterm_id' => $result->type_id));
   }
   return $types;
-}
+}

File diff suppressed because it is too large
+ 278 - 250
tripal_chado/api/tripal_chado.query.api.inc


+ 14 - 7
tripal_chado/api/tripal_chado.schema.api.inc

@@ -1,5 +1,12 @@
 <?php
 
+/**
+ * @file
+ * Provides an application programming interface (API) for describing Chado tables.
+ *
+ * @ingroup tripal_chado
+ */
+
 /**
  * @defgroup tripal_chado_schema_api Chado Schema
  * @ingroup tripal_chado_api
@@ -44,7 +51,7 @@ function chado_table_exists($table) {
   // Get the default database and chado schema.
   global $databases;
   $default_db = $databases['default']['default']['database'];
-  $chado_schema = tripal_get_schema_name('chado');
+  $chado_schema = chado_get_schema_name('chado');
 
   // If we've already lookup up this table then don't do it again, as
   // we don't need to keep querying the database for the same tables.
@@ -121,7 +128,7 @@ function chado_column_exists($table, $column) {
   $args = array(
     ':table_name' => $table,
     ':column_name' => $column,
-    ':chado' => tripal_get_schema_name('chado'),
+    ':chado' => chado_get_schema_name('chado'),
     ':default_db' => $default_db
   );
   $results = db_query($sql, $args);
@@ -168,7 +175,7 @@ function chado_sequence_exists($sequence) {
   ";
   $args = array(
     ':sequence_name' => $sequence,
-    ':sequence_schema' => tripal_get_schema_name('chado'),
+    ':sequence_schema' => chado_get_schema_name('chado'),
     ':sequence_catalog' => $default_db
   );
   $results = db_query($sql, $args);
@@ -291,7 +298,7 @@ function chado_is_local() {
       has_schema_privilege(nspname, 'USAGE') AND
       nspname = :chado
   ";
-  $results = db_query($sql, array(':chado' => tripal_get_schema_name('chado')));
+  $results = db_query($sql, array(':chado' => chado_get_schema_name('chado')));
   $name = $results->fetchObject();
   if ($name) {
     variable_set('chado_schema_exists', FALSE);
@@ -315,7 +322,7 @@ function chado_is_installed() {
   global $databases;
 
   // first check if chado is in the $databases variable of the settings.php file
-  if (array_key_exists(tripal_get_schema_name('chado'), $databases)) {
+  if (array_key_exists(chado_get_schema_name('chado'), $databases)) {
     return TRUE;
   }
 
@@ -358,7 +365,7 @@ function chado_get_version($exact = FALSE, $warn_if_unsupported = FALSE) {
   if (!$is_local) {
     // If it's not in the drupal database check to see if it's specified in
     // the $db_url in the settings.php
-    if (!array_key_exists(tripal_get_schema_name('chado'), $databases)) {
+    if (!array_key_exists(chado_get_schema_name('chado'), $databases)) {
       // if it's not in the drupal database or specified in the $db_url then
       // return uninstalled as the version
       return 'not installed';
@@ -371,7 +378,7 @@ function chado_get_version($exact = FALSE, $warn_if_unsupported = FALSE) {
   else {
     $chado_exists = TRUE;
     // @todo we need a chado aware db_table_exists.
-    $prop_exists = db_table_exists(tripal_get_schema_name('chado') . '.chadoprop');
+    $prop_exists = db_table_exists(chado_get_schema_name('chado') . '.chadoprop');
   }
 
   // if the table doesn't exist then we don't know what version but we know

+ 35 - 9
tripal_chado/api/tripal_chado.semweb.api.inc

@@ -1,4 +1,19 @@
 <?php
+
+/**
+ * @file
+ * Provides an application programming interface (API) for semantic web support.
+ *
+ * @ingroup tripal_chado
+ */
+/**
+ * @defgroup tripal_chado_semweb_api Semantic Web
+ * @ingroup tripal_chado_api
+ * @{
+ * Provides an application programming interface (API) for semantic web support.
+ * @}
+ */
+
 /**
  * Adds a new Chado table to the semantic web support for Chado.
  *
@@ -7,7 +22,7 @@
  * the Chado schema, this function should be called to indicate that the
  * table should be included in the semantic web. No associations are made for
  * the columns. The associations should be added using the
- * tripal_associate_chado_semweb_term() function.
+ * chado_associate_semweb_term() function.
  *
  * If the table has already been added previously then this function does
  * nothing. It will not overwrite existing assocations.
@@ -17,10 +32,12 @@
  *
  * @param $chado_table
  *   The name of the Chado table.
+ * 
+ * @ingroup tripal_chado_semweb_api
  */
-function tripal_add_chado_semweb_table($chado_table) {
+function chado_add_semweb_table($chado_table) {
 
-  // Don't include the tripal temp tables
+  // Don't include the tripal temp tables.
   if (preg_match('/tripal_.+_temp/', $chado_table)) {
     return;
   }
@@ -30,7 +47,7 @@ function tripal_add_chado_semweb_table($chado_table) {
   $schema = chado_get_schema($chado_table);
   foreach ($schema['fields'] as $chado_column => $details) {
 
-    // If the record already exists don't overwrite it
+    // If the record already exists don't overwrite it.
     $record = db_select('chado_semweb', 'CS')
       ->fields('CS', array('chado_semweb_id'))
       ->condition('CS.chado_table', $chado_table)
@@ -46,6 +63,7 @@ function tripal_add_chado_semweb_table($chado_table) {
     }
   }
 }
+
 /**
  * Associates a controlled vocabulary term with a field in a Chado table.
  *
@@ -71,8 +89,10 @@ function tripal_add_chado_semweb_table($chado_table) {
  *
  * @return boolean
  *   Returns TRUE if the association was made successfully and FALSE otherwise.
+ * 
+ *  @ingroup tripal_chado_semweb_api
  */
-function tripal_associate_chado_semweb_term($chado_table, $chado_column, $term,
+function chado_associate_semweb_term($chado_table, $chado_column, $term,
     $update = FALSE) {
 
   // Check for required arguments.
@@ -174,8 +194,10 @@ function tripal_associate_chado_semweb_term($chado_table, $chado_column, $term,
  *   Returns a string-based representation of the term (e.g. SO:0000704). If
  *   the 'return_object' options is provided then a cvterm object is returned.
  *   returns NULL if no term is mapped to the table and column.
+ * 
+ *  @ingroup tripal_chado_semweb_api
  */
-function tripal_get_chado_semweb_term($chado_table, $chado_column, $options = array()) {
+function chado_get_semweb_term($chado_table, $chado_column, $options = array()) {
   $cvterm_id = db_select('chado_semweb', 'CS')
     ->fields('CS', array('cvterm_id'))
     ->condition('chado_column', $chado_column)
@@ -189,7 +211,7 @@ function tripal_get_chado_semweb_term($chado_table, $chado_column, $options = ar
       return $cvterm;
     }
 
-    return tripal_format_chado_semweb_term($cvterm);
+    return chado_format_semweb_term($cvterm);
   }
 }
 
@@ -200,8 +222,10 @@ function tripal_get_chado_semweb_term($chado_table, $chado_column, $options = ar
  *   A cvterm object.
  * @return
  *   The semantic web name for the term.
+ * 
+ *  @ingroup tripal_chado_semweb_api
  */
-function tripal_format_chado_semweb_term($cvterm) {
+function chado_format_semweb_term($cvterm) {
   if ($cvterm) {
     return $cvterm->dbxref_id->db_id->name . ':' . $cvterm->dbxref_id->accession;
   }
@@ -219,8 +243,10 @@ function tripal_format_chado_semweb_term($cvterm) {
  * @return
  *   The name of the Chado column that matches the given term or FALSE if the
  *   term is not mapped to the Chado table.
+ * 
+ *  @ingroup tripal_chado_semweb_api
  */
-function tripal_get_chado_semweb_column($chado_table, $term) {
+function chado_get_semweb_column($chado_table, $term) {
   $columns = db_select('chado_semweb', 'CS')
     ->fields('CS')
     ->condition('chado_table', $chado_table)

+ 210 - 175
tripal_chado/api/tripal_chado.variables.api.inc

@@ -1,7 +1,18 @@
 <?php
+
 /**
  * @file
  * This API generates objects containing the full details of a record(s) in chado.
+ *
+ * @ingroup tripal_chado
+ */
+/**
+ * @defgroup tripal_chado_variables_api Semantic Web
+ * @ingroup tripal_chado_api
+ * 
+ * @{
+ * This API generates objects containing the full details of a record(s) in chado.
+ * @}
  */
 
 /**
@@ -130,7 +141,7 @@
  *   base table). If the option 'return_array' is provided the function
  *   always returns an array.
  *
- * @ingroup tripal_chado_query_api
+ * @ingroup tripal_chado_variables_api
  */
 function chado_generate_var($table, $values, $base_options = array()) {
   $all = new stdClass();
@@ -147,7 +158,7 @@ function chado_generate_var($table, $values, $base_options = array()) {
   if (array_key_exists('pager', $base_options)) {
     $pager = $base_options['pager'];
   }
-  // get description for the current table----------------------------------------------------------
+  // get description for the current table-------------------------------------
   $table_desc = chado_get_schema($table);
   if (!$table_desc or count($table_desc) == 0) {
     tripal_report_error('tripal_chado', TRIPAL_ERROR,
@@ -163,7 +174,7 @@ function chado_generate_var($table, $values, $base_options = array()) {
   $table_primary_key = $table_desc['primary key'][0];
   $table_columns = array_keys($table_desc['fields']);
 
-  // Expandable fields without value needed for criteria--------------------------------------------
+  // Expandable fields without value needed for criteria-----------------------
   // Add in the default expandable arrays
   // These are used for later expanding fields, tables, foreign keys and nodes
   $all->expandable_fields = array();
@@ -183,34 +194,36 @@ function chado_generate_var($table, $values, $base_options = array()) {
 
   // This allows modules to specify that some fields should be excluded by default
   // For example, tripal core provides a tripal_chado_exclude_field_from_feature_by_default()
-  // which says that we usually don't want to include the residues field by default since
-  // it can be very large and cause performance issues.
+  // which says that we usually don't want to include the residues field by 
+  // default since it can be very large and cause performance issues.
 
-  // If a field is excluded by default it can always be expanded at a later point by calling
-  // chado_expand_var($chado_var, 'field', <field name as shown in expandable_fields array>);
+  // If a field is excluded by default it can always be expanded at a later 
+  // point by calling chado_expand_var($chado_var, 'field', 
+  // <field name as shown in expandable_fields array>);
 
   // First get an array of all the fields to be removed for the current table
-  // module_invoke_all() is drupal's way of invoking all implementations of the specified
-  // hook and merging all of the results.
+  // module_invoke_all() is drupal's way of invoking all implementations of the 
+  // specified hook and merging all of the results.
 
   // $fields_to_remove should be an array with the keys matching field names
-  // and the values being strings to be executed using php_eval() to determine whether
-  // to exclude the field (evaluates to TRUE) or not (evaluates to FALSE)
+  // and the values being strings to be executed using php_eval() to determine 
+  // whether to exclude the field (evaluates to TRUE) or not (evaluates to FALSE)
   $fields_to_remove = module_invoke_all('exclude_field_from_' . $table . '_by_default');
 
   // Now, for each field to be removed
   foreach ($fields_to_remove as $field_name => $criteria) {
 
-    //replace <field_name> with the current field name
+    //Replace <field_name> with the current field name
     $field_name_safe = preg_replace("/\'\"\\\/", '\\1', $field_name);
     $criteria = preg_replace('/<field_name> /', $field_name_safe, $criteria);
-    // if field_value needed we can't deal with this field yet
+    // If field_value needed we can't deal with this field yet.
     if (preg_match('/<field_value> /', $criteria)) {
       break;
     }
 
-    //if criteria then remove from query
-    // @coder-ignore: only module designers can populate $criteria -not a security risk
+    // If criteria then remove from query
+    // @coder-ignore: only module designers can populate $criteria -not a 
+    // security risk.
     $success = php_eval('<?php return ' . $criteria . '; ?>');
     if ($success) {
       unset($table_columns[array_search($field_name, $table_columns)]);
@@ -222,40 +235,43 @@ function chado_generate_var($table, $values, $base_options = array()) {
   // Get fields to be removed by type................................
   // This gets all implementations of hook_exclude_type_by_default().
 
-  // This allows modules to specify that some types of fields should be excluded by default
-  // For example, tripal core provides a tripal_chado_exclude_type_by_default() which says
-  // that text fields are often very large and if they are longer than 250 characters then
+  // This allows modules to specify that some types of fields should be excluded 
+  // by default For example, tripal core provides a 
+  // tripal_chado_exclude_type_by_default() which says that text fields are 
+  // often very large and if they are longer than 250 characters then
   // we want to exclude them by default
 
-  // If a field is excluded by default it can always be expanded at a later point by calling
-  // chado_expand_var($chado_var, 'field', <field name as shown in expandable_fields array>);
+  // If a field is excluded by default it can always be expanded at a later 
+  // point by calling chado_expand_var($chado_var, 'field', 
+  //<field name as shown in expandable_fields array>);
 
-  // First get an array of all the types of fields to be removed for the current table
-  // module_invoke_all() is drupal's way of invoking all implementations of the specified
-  // hook and merging all of the results.
+  // First get an array of all the types of fields to be removed for the current
+  // table module_invoke_all() is drupal's way of invoking all implementations 
+  // of the specified hook and merging all of the results.
 
   // $types_to_remove should be an array with the keys matching field names
-  // and the values being strings to be executed using php_eval() to determine whether
-  // to exclude the field (evaluates to TRUE) or not (evaluates to FALSE)
+  // and the values being strings to be executed using php_eval() to determine 
+  // whether to exclude the field (evaluates to TRUE) or not (evaluates to FALSE)
   // (ie: array('text' => 'strlen("<field_value> ") > 100');
   $types_to_remove = module_invoke_all('exclude_type_by_default');
 
   // Get a list of all the types of fields
-  // the key is the type of field and the value is an array of fields of this type
+  // the key is the type of field and the value is an array of fields of this 
+  // type.
   $field_types = array();
   foreach ($table_desc['fields'] as $field_name => $field_array) {
     $field_types[$field_array['type']][] = $field_name;
   }
 
-  // We want to use the types to remove in conjunction with our table field descriptions
-  // to determine which fields might need to be removed
+  // We want to use the types to remove in conjunction with our table field 
+  // descriptions to determine which fields might need to be removed.
   foreach ($types_to_remove as $field_type => $criteria) {
 
-    // if there are fields of that type to remove
+    // If there are fields of that type to remove.
     if (isset($field_types[$field_type])) {
 
       // Do any processing needed on the php criteria
-      //replace <field_name>  with the current field name
+      //replace <field_name>  with the current field name.
       $field_name_safe = preg_replace('/\'|"|\\\/', '\\1', $field_name);
       $criteria = preg_replace('/<field_name> /', $field_name_safe, $criteria);
       foreach ($field_types[$field_type] as $field_name) {
@@ -265,19 +281,20 @@ function chado_generate_var($table, $values, $base_options = array()) {
           continue;
         }
 
-        // if criteria then remove from query
-        // (as long as <field_value> is not needed for the criteria to be evaluated)
-        // @coder-ignore: only module designers can populate $criteria -not a security risk
+        // If criteria then remove from query
+        // (as long as <field_value> is not needed for the criteria to be 
+        // evaluated) @coder-ignore: only module designers can populate 
+        //$criteria -not a security risk.
         $success = php_eval('<?php return ' . $criteria . '; ?>');
         if ($success) {
           unset($table_columns[array_search($field_name, $table_columns)]);
           $all->expandable_fields[] = $table . '.' . $field_name;
         }
-      } //end of foreach field of that type
+      } // End of foreach field of that type.
     }
-  } //end of foreach type to be removed
+  } // End of foreach type to be removed.
 
-  // get the values for the record in the current table---------------------------------------------
+  // Get the values for the record in the current table-------------------------
   $results = chado_select_record($table, $table_columns, $values, $base_options);
 
   if ($results) {
@@ -285,7 +302,7 @@ function chado_generate_var($table, $values, $base_options = array()) {
     // Iterate through each result.
     foreach ($results as $key => $object) {
 
-      // Add empty expandable_x arrays
+      // Add empty expandable_x arrays.
       $object->expandable_fields = $all->expandable_fields;
       $object->expandable_foreign_keys = $all->expandable_foreign_keys;
       $object->expandable_tables = $all->expandable_tables;
@@ -294,11 +311,12 @@ function chado_generate_var($table, $values, $base_options = array()) {
       $object->tablename = $table;
 
       // For Tripal v2 compatibility
-      // check if the current table maps to a node type-----------------------------------------------
-      // if this table is connected to a node there will be a chado_tablename table in drupal
+      // check if the current table maps to a node type-------------------------
+      // If this table is connected to a node there will be a chado_tablename 
+      // table in drupal.
       if (module_exists('tripal_core') and db_table_exists('chado_' . $table)) {
-        // that has a foreign key to this one ($table_desc['primary key'][0]
-        // and to the node table (nid)
+        // That has a foreign key to this one ($table_desc['primary key'][0]
+        // and to the node table (nid).
         $sql = "
           SELECT $table_primary_key, nid
           FROM {chado_$table}
@@ -319,13 +337,14 @@ function chado_generate_var($table, $values, $base_options = array()) {
         $object->entity_id = $entity_id;
       }
 
-      // remove any fields where criteria needs to be evalulated---------------------------------------
+      // Remove any fields where criteria needs to be evalulated----------------
       // The fields to be removed can be populated by implementing either
-      // hook_exclude_field_from_<table>_by_default() where <table> is the current table
-      // OR hook_exclude_type_by_default() where there are fields of the specified type in the current table
-      // It only reaches this point if the criteria specified for whether or not to
-      // exclude the field includes <field_value> which means it has to be evaluated after
-      // the query has been executed
+      // hook_exclude_field_from_<table>_by_default() where <table> is the 
+      // current table OR hook_exclude_type_by_default() where there are fields 
+      // of the specified type in the current table It only reaches this point 
+      // if the criteria specified for whether or not to exclude the field 
+      // includes <field_value> which means it has to be evaluated after
+      // the query has been executed.
       foreach ($fields_to_remove as $field_name => $criteria) {
 
         // If the field is an object then we don't support exclusion of it
@@ -334,7 +353,8 @@ function chado_generate_var($table, $values, $base_options = array()) {
           break;
         }
 
-        // replace <field_value> with the actual value of the field from the query
+        // Replace <field_value> with the actual value of the field from the 
+        // query.
         $field_name_safe = preg_replace('/\'|"|\\\/', '\\1', $object->{$field_name});
         $criteria = preg_replace('/<field_value>/', $field_name_safe, $criteria);
 
@@ -348,34 +368,35 @@ function chado_generate_var($table, $values, $base_options = array()) {
         }
       }
 
-      // recursively follow foreign key relationships nesting objects as we go------------------------
+      // Recursively follow foreign key relationships nesting objects as we go------------------------
       if (array_key_exists('foreign keys', $table_desc) and $table_desc['foreign keys']) {
         foreach ($table_desc['foreign keys'] as $foreign_key_array) {
           $foreign_table = $foreign_key_array['table'];
           foreach ($foreign_key_array['columns'] as $foreign_key => $primary_key) {
 
-            // Note: Foreign key is the field in the current table whereas primary_key is the field in
-            // the table referenced by the foreign key
-            //Dont do anything if the foreign key is empty
+            // Note: Foreign key is the field in the current table whereas 
+            // primary_key is the field in the table referenced by the foreign 
+            // key, don't do anything if the foreign key is empty
             if (empty($object->{$foreign_key})) {
               continue;
             }
 
             if (is_array($include_fk)) {
-              // don't recurse if the callee has supplied an $fk_include list and this
-              // FK table is not in the list.
+              // Don't recurse if the callee has supplied an $fk_include list 
+              // and this FK table is not in the list.
               if (is_array($include_fk) and !array_key_exists($foreign_key, $include_fk)) {
                 $object->expandable_foreign_keys[] = $table . '.' . $foreign_key . ' => ' . $foreign_table;
                 continue;
               }
             }
-            // if we have the option but it is not an array then we don't recurse any furutehr
+            // If we have the option but it is not an array then we don't 
+            // recurse any further.
             if ($include_fk === TRUE) {
               $object->expandable_foreign_keys[] = $table . '.' . $foreign_key . ' => ' . $foreign_table;
               continue;
             }
 
-            // get the record from the foreign table
+            // Get the record from the foreign table.
             $foreign_values = array($primary_key => $object->{$foreign_key});
             $options = array();
             if (is_array($include_fk)) {
@@ -384,9 +405,9 @@ function chado_generate_var($table, $values, $base_options = array()) {
 
             $foreign_object = chado_generate_var($foreign_table, $foreign_values, $options);
 
-            // add the foreign record to the current object in a nested manner
+            // Add the foreign record to the current object in a nested manner.
             $object->{$foreign_key} = $foreign_object;
-            // Flatten expandable_x arrays so only in the bottom object
+            // Flatten expandable_x arrays so only in the bottom object.
             if (property_exists($object->{$foreign_key}, 'expandable_fields') and
                 is_array($object->{$foreign_key}->expandable_fields)) {
               $object->expandable_fields = array_merge(
@@ -426,26 +447,26 @@ function chado_generate_var($table, $values, $base_options = array()) {
     }
   }
 
-  // convert the results into an array
+  // Convert the results into an array.
   $results_arr = array();
   foreach ($results as $record) {
     $results_arr[] = $record;
   }
-  // check only one result returned
+  // Check only one result returned.
   if (!$return_array) {
     if (sizeof($results_arr) == 1) {
-      // add results to object
+      // Add results to object.
       return $results_arr[0];
     }
     elseif (!empty($results_arr)) {
       return $results_arr;
     }
     else {
-      // no results returned
+      // No results returned.
     }
   }
-  // the caller has requested results are always returned as
-  // an array
+  // The caller has requested results are always returned as
+  // an array.
   else {
     if (!$results_arr) {
       return array();
@@ -550,16 +571,16 @@ function chado_generate_var($table, $values, $base_options = array()) {
  *   - return_array:
  *     Additionally,  The option 'return_array' can be provided to force
  *     the function to expand tables as an array. Default behavior is to expand
- *     a table as single record if only one record exists or to expand as an array if
- *     multiple records exist.
+ *     a table as single record if only one record exists or to expand as an 
+ *     array if multiple records exist.
  *   - include_fk:
  *     an array of FK relationships to follow. By default, the
  *     chado_expand_var function will follow all FK relationships but this
- *     may generate more queries then is desired slowing down this function call when
- *     there are lots of FK relationships to follow.  Provide an array specifying the
- *     fields to include.  For example, if expanding a property table (e.g. featureprop)
- *     and you want the CV and accession but do not want the DB the following
- *     array would work:
+ *     may generate more queries then is desired slowing down this function call
+ *     when there are lots of FK relationships to follow.  Provide an array 
+ *     specifying the fields to include.  For example, if expanding a property 
+ *     table (e.g. featureprop) and you want the CV and accession but do not 
+ *     want the DB the following array would work:
  *        $table_options =  array(
  *          'include_fk' => array(
  *            'type_id' => array(
@@ -583,21 +604,22 @@ function chado_generate_var($table, $values, $base_options = array()) {
  *     This options is only used where type=table and allows you to
  *     expand only a subset of results based on the given criteria. Criteria
  *     should provided as an array of [field name] => [value] similar to the
- *     values array provided to chado_generate_var(). For example, when expanding
- *     the featureprop table for a feature, you will already get only properties
- *     for that feature, this option allows you to further get only properties
- *     of a given type by passing in array('type_id' => array('name' => [name of type]))
+ *     values array provided to chado_generate_var(). For example, when 
+ *     expanding the featureprop table for a feature, you will already get only 
+ *     properties for that feature, this option allows you to further get only 
+ *     properties of a given type by passing in 
+ *     array('type_id' => array('name' => [name of type]))
  * @return
- *   A chado object supplemented with the field/table/node requested to be expanded.
- *   If the type is a table and it has already been expanded no changes is made to the
- *   returned object
+ *   A chado object supplemented with the field/table/node requested to be 
+ *   expanded. If the type is a table and it has already been expanded no 
+ *   changes is made to the returned object
  *
  *
- * @ingroup tripal_chado_query_api
+ * @ingroup tripal_chado_variables_api
  */
 function chado_expand_var($object, $type, $to_expand, $table_options = array()) {
 
-  // make sure we have a value
+  // Make sure we have a value.
   if (!$object) {
     tripal_report_error('tripal_chado',
       TRIPAL_ERROR,
@@ -606,7 +628,7 @@ function chado_expand_var($object, $type, $to_expand, $table_options = array())
     return $object;
   }
 
-  // check to see if we are expanding an array of objects
+  // Check to see if we are expanding an array of objects.
   if (is_array($object)) {
     foreach ($object as $index => $o) {
       $object[$index] = chado_expand_var($o, $type, $to_expand);
@@ -614,20 +636,20 @@ function chado_expand_var($object, $type, $to_expand, $table_options = array())
     return $object;
   }
 
-  // get the base table name
+  // Get the base table name.
   $base_table = $object->tablename;
 
   switch ($type) {
-    case "field": //--------------------------------------------------------------------------------
+    case "field": //------------------------------------------------------------
       if (preg_match('/(\w+)\.(\w+)/', $to_expand, $matches)) {
         $tablename = $matches[1];
         $fieldname = $matches[2];
         $table_desc = chado_get_schema($tablename);
 
-        // BASE CASE: the field is from the current table
+        // BASE CASE: the field is from the current table.
         if ($base_table == $tablename) {
           // Use the table description to fully describe the current object
-          // in a $values array to be used to select the field from chado
+          // in a $values array to be used to select the field from chado.
           $values = array();
           foreach ($table_desc['primary key'] as $key) {
             if(property_exists($object, $key)) {
@@ -635,21 +657,21 @@ function chado_expand_var($object, $type, $to_expand, $table_options = array())
             }
           }
 
-          // Retrieve the field from Chado
+          // Retrieve the field from Chado.
           $results = chado_select_record($tablename, array($fieldname), $values);
 
-          // Check that the field was retrieved correctly
+          // Check that the field was retrieved correctly.
           if (isset($results[0])) {
             $object->{$fieldname} = $results[0]->{$fieldname};
             $object->expanded = $to_expand;
           }
-          // If it wasn't retrieved correctly, we need to warn the administrator
+          // If it wasn't retrieved correctly, we need to warn the administrator.
 
         }
-        // RECURSIVE CASE: the field is in a nested object
+        // RECURSIVE CASE: the field is in a nested object.
         else {
           // We want to look at each field and if it's an object then we want to
-          // attempt to expand the field in it via recursion
+          // attempt to expand the field in it via recursion.
           foreach ((array) $object as $field_name => $field_value) {
             if (is_object($field_value)) {
               $object->{$field_name} = chado_expand_var(
@@ -658,11 +680,11 @@ function chado_expand_var($object, $type, $to_expand, $table_options = array())
               $to_expand
               );
             }
-          } //end of for each field in the current object
+          } // End of for each field in the current object.
         }
       }
       // Otherwise we weren't able to extract the parts of the field to expand
-      // Thus we will warn the administrator
+      // Thus we will warn the administrator.
       else {
         tripal_report_error('tripal_chado', TRIPAL_ERROR,
           'chado_expand_var: Field (%field) not in the right format. " .
@@ -670,21 +692,22 @@ function chado_expand_var($object, $type, $to_expand, $table_options = array())
       }
       break;
 
-    case "foreign_key": //--------------------------------------------------------------------------
+    case "foreign_key": //-----------------------------------------------------
       if (preg_match('/(\w+)\.(\w+) => (\w+)/', $to_expand, $matches)) {
         $table_name = $matches[1];
         $field_name = $matches[2];
         $foreign_table = $matches[3];
         $table_desc = chado_get_schema($table_name);
 
-        // BASE CASE: The foreign key is from the current table
+        // BASE CASE: The foreign key is from the current table.
         if ($base_table == $table_name) {
 
           // Get the value of the foreign key from the object
           $field_value = $object->{$field_name};
 
-          // Get the name of the field in the foreign table using the table description
-          // For example, with the feature.type_id => cvterm.cvterm_id we need cvterm_id
+          // Get the name of the field in the foreign table using the table 
+          // description For example, with the 
+          // feature.type_id => cvterm.cvterm_id we need cvterm_id
           $foreign_field_name = FALSE;
           foreach ($table_desc['foreign keys'][$foreign_table]['columns'] as $left => $right) {
             if ($right == $field_name) {
@@ -692,23 +715,25 @@ function chado_expand_var($object, $type, $to_expand, $table_options = array())
             }
           }
 
-          // Check that we were able to determine the field name in the foreign table
+          // Check that we were able to determine the field name in the foreign
+          // table.
           if ($foreign_field_name) {
 
             // Generate a chado variable of the foreign key
             // For example, if the foreign key to expand is feature.type_id
-            // then we want to generate a chado cvterm variable that matches the feature.type_id
+            // then we want to generate a chado cvterm variable that matches the 
+            // feature.type_id.
             $foreign_var = chado_generate_var(
               $foreign_table, // thus in the example above, generate a cvterm var
               array($foreign_field_name => $field_value), // where the cvterm.cvterm_id = feature.type_id value
               $table_options //pass in the same options given to this function
             );
 
-            // Check that the foreign object was returned
+            // Check that the foreign object was returned.
             if ($foreign_var) {
 
-              // It was so now we can add this chado variable to our current object
-              // in place of the key value
+              // It was so now we can add this chado variable to our current 
+              // object in place of the key value.
               $object->{$field_name} = $foreign_var;
               $object->expanded = $to_expand;
 
@@ -721,7 +746,7 @@ function chado_expand_var($object, $type, $to_expand, $table_options = array())
                 array('%fk' => $to_expand));
             }
           }
-          // Else we were unable to determine the field name in the foreign table
+          // Else we were unable to determine the field name in the foreign table.
           else {
             tripal_report_error('tripal_chado', TRIPAL_ERROR,
               'chado_expand_var: unable to determine the field name in the table the foreign
@@ -730,7 +755,7 @@ function chado_expand_var($object, $type, $to_expand, $table_options = array())
           }
 
         }
-        // RECURSIVE CASE: Check any nested objects
+        // RECURSIVE CASE: Check any nested objects.
         else {
 
           foreach ((array) $object as $field_name => $field_value) {
@@ -741,12 +766,12 @@ function chado_expand_var($object, $type, $to_expand, $table_options = array())
               $to_expand
               );
             }
-          } //end of for each field in the current object
+          } //End of for each field in the current object.
 
         }
       }
-      // Otherwise we weren't able to extract the parts of the foreign key to expand
-      // Thus we will warn the administrator
+      // Otherwise we weren't able to extract the parts of the foreign key to 
+      // expand thus we will warn the administrator.
       else {
         tripal_report_error('tripal_chado', TRIPAL_ERROR,
           'chado_expand_var: foreign_key (%fk) not in the right format. " .
@@ -754,7 +779,7 @@ function chado_expand_var($object, $type, $to_expand, $table_options = array())
       }
       break;
 
-    case "table": //--------------------------------------------------------------------------------
+    case "table": //------------------------------------------------------------
       $foreign_table = $to_expand;
 
       // BASE CASE: don't expand the table it already is expanded
@@ -763,15 +788,16 @@ function chado_expand_var($object, $type, $to_expand, $table_options = array())
       }
       $foreign_table_desc = chado_get_schema($foreign_table);
 
-      // TODO: if we don't get a foreign_table (which could happen of a custom table
-      // is not correctly defined or the table name is mispelled then we should return
-      // gracefully.
+      // TODO: if we don't get a foreign_table (which could happen of a custom 
+      // table is not correctly defined or the table name is mispelled then we 
+      // should return gracefully.
 
       // BASE CASE: If it's connected to the base table via a FK constraint
-      // then we have all the information needed to expand it now
+      // then we have all the information needed to expand it now.
       if (array_key_exists($base_table, $foreign_table_desc['foreign keys'])) {
         foreach ($foreign_table_desc['foreign keys'][$base_table]['columns'] as $left => $right) {
-          // if the FK value in the base table is not there then we can't expand it, so just skip it.
+          // if the FK value in the base table is not there then we can't expand
+          // it, so just skip it.
           if (!$object->{$right}) {
             continue;
           }
@@ -800,15 +826,17 @@ function chado_expand_var($object, $type, $to_expand, $table_options = array())
             $filter_criteria = array($left => $object->{$right});
           }
 
-          // generate a new object for this table using the FK values in the base table.
+          // Generate a new object for this table using the FK values in the 
+          // base table.
           $new_options = $table_options;
           $foreign_object = chado_generate_var($foreign_table, $filter_criteria, $new_options);
 
-          // if the generation of the object was successful, update the base object to include it.
+          // If the generation of the object was successful, update the base 
+          // object to include it.
           if ($foreign_object) {
-            // in the case where the foreign key relationship exists more
-            // than once with the same table we want to alter the array structure to
-            // include the field name.
+            // In the case where the foreign key relationship exists more
+            // than once with the same table we want to alter the array 
+            // structure to include the field name.
             if (count($foreign_table_desc['foreign keys'][$base_table]['columns']) > 1) {
               if (!property_exists($object, $foreign_table)) {
                 $object->{$foreign_table} = new stdClass();
@@ -825,11 +853,11 @@ function chado_expand_var($object, $type, $to_expand, $table_options = array())
               $object->expanded = $to_expand;
             }
           }
-          // if the object returned is NULL then handle that
+          // If the object returned is NULL then handle that.
           else {
-            // in the case where the foreign key relationship exists more
-            // than once with the same table we want to alter the array structure to
-            // include the field name.
+            // In the case where the foreign key relationship exists more
+            // than once with the same table we want to alter the array 
+            // structure to include the field name.
             if (count($foreign_table_desc['foreign keys'][$base_table]['columns']) > 1) {
               if (!property_exists($object, $foreign_table)) {
                 $object->{$foreign_table} = new stdClass();
@@ -842,30 +870,32 @@ function chado_expand_var($object, $type, $to_expand, $table_options = array())
           }
         }
       }
-      // RECURSIVE CASE: if the table is not connected directly to the current base table
-      // through a foreign key relationship, then maybe it has a relationship to
-      // one of the nested objects.
+      // RECURSIVE CASE: if the table is not connected directly to the current 
+      // base table through a foreign key relationship, then maybe it has a 
+      // relationship to one of the nested objects.
       else {
 
-        // We need to recurse -the table has a relationship to one of the nested objects
-        // We assume it's a nested object if the value of the field is an object
+        // We need to recurse -the table has a relationship to one of the nested
+        // objects. We assume it's a nested object if the value of the field is 
+        // an object.
         $did_expansion = 0;
         foreach ((array) $object as $field_name => $field_value) {
 
-          // CASE #1: This field is an already expanded foreign key and the table to be
-          // expanded is in the table referenced by the foreign key
+          // CASE #1: This field is an already expanded foreign key and the 
+          // table to be expanded is in the table referenced by the foreign key.
 
           // First of all it can only be expanded if it's an object
-          // And if it's a foreign key it should have a tablename property
+          // And if it's a foreign key it should have a tablename property.
           if (is_object($field_value) AND property_exists($field_value, 'tablename')) {
             $object->{$field_name} = chado_expand_var($field_value, 'table', $foreign_table);
           }
 
-          // CASE #2: This field is an already expanded object (ie: the field is actually
-          // the expanded table name) and the table to be expanded si related to it
+          // CASE #2: This field is an already expanded object (ie: the field is
+          // actually the expanded table name) and the table to be expanded is 
+          // related to it.
 
-          // check to see if the $field_name is a valid chado table, we don't need
-          // to call chado_expand_var on fields that aren't tables
+          // Check to see if the $field_name is a valid chado table, we don't 
+          // need to call chado_expand_var on fields that aren't tables.
           $check = chado_get_schema($field_name);
           if ($check) {
             $did_expansion = 1;
@@ -873,8 +903,8 @@ function chado_expand_var($object, $type, $to_expand, $table_options = array())
           }
         }
 
-        // if we did not expand this table we should return a message that the foreign table
-        // could not be expanded
+        // If we did not expand this table we should return a message that the 
+        // foreign tabl could not be expanded.
         if (!$did_expansion) {
           tripal_report_error('tripal_chado', TRIPAL_ERROR, 'chado_expand_var: Could not expand %table. ' .
             'The table is either not related to the base object through a foreign key relationships or ' .
@@ -886,19 +916,21 @@ function chado_expand_var($object, $type, $to_expand, $table_options = array())
       }
       break;
 
-    case "node": //---------------------------------------------------------------------------------
+    case "node": //-------------------------------------------------------------
 
-      // BASE CASE: if the node to be expanded is for our base table, then just expand it
+      // BASE CASE: if the node to be expanded is for our base table, then just 
+      // expand it.
       if ($object->tablename == $to_expand) {
 
-        // Load the node based on the current objects nid (node primary key)
+        // Load the node based on the current objects nid (node primary key).
         $node = NULL;
         if (property_exists($object, 'nid')) {
           $node = node_load($object->nid);
         }
-        // Try to get the nid based on the tablename
+        // Try to get the nid based on the tablename.
         else {
-          // Invoke all hook_node_info to avoid hard-coding the chado_$table assumption
+          // Invoke all hook_node_info to avoid hard-coding the chado_$table 
+          // assumption..
           foreach (module_invoke_all('node_info') as $node_info) {
             if (array_key_exists('chado_node_api', $node_info)) {
               if ($node_info['chado_node_api']['base_table'] == $object->tablename) {
@@ -920,7 +952,7 @@ function chado_expand_var($object, $type, $to_expand, $table_options = array())
         // If we have successfully loaded the node...
         if ($node) {
 
-          // Move expandable arrays from the object into the node
+          // Move expandable arrays from the object into the node.
           $object->expanded = $to_expand;
           $node->expandable_fields = $object->expandable_fields;
           unset($object->expandable_fields);
@@ -930,13 +962,14 @@ function chado_expand_var($object, $type, $to_expand, $table_options = array())
           unset($object->expandable_nodes);
 
           // The node becomes the base object with the obejct added to it.
-          // For example, we may start with a feature object with a name, uniquename , type, etc.
-          // After expanding we will return the node and at $node->feature you will find the original object
+          // For example, we may start with a feature object with a name, 
+          // uniquename , type, etc. After expanding we will return the node and
+          // at $node->feature you will find the original object.
           $node->{$base_table} = $object;
           $object = $node;
 
         }
-        // Else we were unable to load the node
+        // Else we were unable to load the node.
         else {
 
           // Warn the administrator
@@ -947,14 +980,14 @@ function chado_expand_var($object, $type, $to_expand, $table_options = array())
           else {
             tripal_report_error('tripal_chado', TRIPAL_NOTICE, 'chado_expand_var: There is no node for the current object: <pre>%object</pre>', array('%object' => print_r($object,TRUE)));
           }
-        } //end of if node
+        } //End of if node.
       }
-      // RECURSIVE CASE: check to see if the node to be expanded associates with a
-      // chado table within one of the nested objects.
+      // RECURSIVE CASE: check to see if the node to be expanded associates with 
+      // a chado table within one of the nested objects.
       else {
 
         // We need to recurse -the node to expand is one of the nested objects
-        // We assume it's a nested object if the field value is an object
+        // We assume it's a nested object if the field value is an object.
         foreach ((array) $object as $field_name => $field_value) {
           if (is_object($field_value)) {
             $object->{$field_name} = chado_expand_var(
@@ -963,11 +996,11 @@ function chado_expand_var($object, $type, $to_expand, $table_options = array())
             $to_expand
             );
           }
-        } //end of for each field in the current object
+        } // End of for each field in the current object.
       }
       break;
 
-    // The $type to be expanded is not yet supported
+    // The $type to be expanded is not yet supported.
     default:
       tripal_report_error('tripal_chado', TRIPAL_ERROR, 'chado_expand_var: Unrecognized type (%type). Should be one of "field", "table", "node".',
         array('%type' => $type));
@@ -975,22 +1008,22 @@ function chado_expand_var($object, $type, $to_expand, $table_options = array())
   }
 
   // Move expandable arrays downwards -------------------------------
-  // If the type was either table or foreign key then a new chado variable was generated
-  // this variable will have it's own expandable array's which need to be moved down
-  // and merged with the base objects expandable arrays
+  // If the type was either table or foreign key then a new chado variable was 
+  // generated this variable will have it's own expandable array's which need to
+  // be moved down and merged with the base objects expandable arrays.
 
   // Thus, check all nested objects for expandable arrays
-  // and if they have them, move them downwards
+  // and if they have them, move them downwards.
   foreach ( (array)$object as $field_name => $field_value) {
     if (is_object($field_value)) {
 
-      // The current nested object has expandable arrays
+      // The current nested object has expandable arrays.
       if (isset($field_value->expandable_fields)) {
 
-        // Move expandable fields downwards
+        // Move expandable fields downwards.
         if (isset($field_value->expandable_fields) and is_array($field_value->expandable_fields)) {
 
-          // If the current object has it's own expandable fields then merge them
+          // If the current object has it's own expandable fields then merge them.
           if (isset($object->expandable_fields)) {
             $object->expandable_fields = array_merge(
               $object->expandable_fields,
@@ -999,7 +1032,7 @@ function chado_expand_var($object, $type, $to_expand, $table_options = array())
             unset($object->{$field_name}->expandable_fields);
 
           }
-          // Otherwise, just move the expandable fields downwards
+          // Otherwise, just move the expandable fields downwards.
           else {
             $object->expandable_fields = $object->{$field_name}->expandable_fields;
             unset($object->{$field_name}->expandable_fields);
@@ -1007,10 +1040,11 @@ function chado_expand_var($object, $type, $to_expand, $table_options = array())
 
         }
 
-        // Move expandable foreign keys downwards
+        // Move expandable foreign keys downwards.
         if (isset($field_value->expandable_foreign_keys) and is_array($field_value->expandable_foreign_keys)) {
 
-          // If the current object has it's own expandable foreign keys then merge them
+          // If the current object has it's own expandable foreign keys then 
+          // merge them.
           if (isset($object->expandable_foreign_keys)) {
             $object->expandable_foreign_keys = array_merge(
               $object->expandable_foreign_keys,
@@ -1019,17 +1053,17 @@ function chado_expand_var($object, $type, $to_expand, $table_options = array())
             unset($object->{$field_name}->expandable_foreign_keys);
 
           }
-          // Otherwise, just move the expandable foreign keys downwards
+          // Otherwise, just move the expandable foreign keys downwards.
           else {
             $object->expandable_foreign_keys = $object->{$field_name}->expandable_foreign_keys;
             unset($object->{$field_name}->expandable_foreign_keys);
           }
         }
 
-        // Move expandable tables downwards
+        // Move expandable tables downwards.
         if (isset($field_value->expandable_tables) and is_array($field_value->expandable_tables)) {
 
-          // If the current object has it's own expandable tables then merge them
+          // If the current object has it's own expandable tables then merge them.
           if (isset($object->expandable_tables)) {
             $object->expandable_tables = array_merge(
               $object->expandable_tables,
@@ -1038,17 +1072,17 @@ function chado_expand_var($object, $type, $to_expand, $table_options = array())
             unset($object->{$field_name}->expandable_tables);
 
           }
-          // Otherwise, just move the expandable tables downwards
+          // Otherwise, just move the expandable tables downwards.
           else {
             $object->expandable_tables = $object->{$field_name}->expandable_tables;
             unset($object->{$field_name}->expandable_tables);
           }
         }
 
-        // Move expandable nodes downwards
+        // Move expandable nodes downwards.
         if (isset($field_value->expandable_nodes) and is_array($field_value->expandable_nodes)) {
 
-          // If the current object has it's own expandable tables then merge them
+          // If the current object has it's own expandable tables then merge them.
           if (isset($object->expandable_nodes)) {
             $object->expandable_nodes = array_merge(
               $object->expandable_nodes,
@@ -1057,7 +1091,7 @@ function chado_expand_var($object, $type, $to_expand, $table_options = array())
             unset($object->{$field_name}->expandable_nodes);
 
           }
-          // Otherwise, just move the expandable tables downwards
+          // Otherwise, just move the expandable tables downwards.
           else {
             $object->expandable_nodes = $object->{$field_name}->expandable_nodes;
             unset($object->{$field_name}->expandable_nodes);
@@ -1069,20 +1103,20 @@ function chado_expand_var($object, $type, $to_expand, $table_options = array())
 
   // Move extended array downwards ----------------------------------
   // This tells us what we have expanded (ie: that we succeeded)
-  // and is needed to remove the entry from the expandable array
+  // and is needed to remove the entry from the expandable array.
 
-  // If there is no expanded field in the current object then check any of the nested objects
-  // and move it down
+  // If there is no expanded field in the current object then check any of the 
+  // nested objects and move it down.
   if (!property_exists($object, 'expanded')) {
 
-    // It's a nested object if the value is an object
+    // It's a nested object if the value is an object.
     foreach ( (array)$object as $field_name => $field_value) {
       if (is_object($field_value)) {
 
-        // Check if the current nested object has an expanded array
+        // Check if the current nested object has an expanded array.
         if (isset($field_value->expanded)) {
 
-          // If so, then move it downwards
+          // If so, then move it downwards.
           $object->expanded = $field_value->expanded;
           unset($field_value->expanded);
         }
@@ -1091,10 +1125,11 @@ function chado_expand_var($object, $type, $to_expand, $table_options = array())
   }
 
   // Check again if there is an expanded field in the current object
-  // We check again because it might have been moved downwards above
+  // We check again because it might have been moved downwards above.
   if (property_exists($object, 'expanded')) {
 
-    // If so, then remove the expanded identifier from the correct expandable array
+    // If so, then remove the expanded identifier from the correct expandable 
+    // array..
     $expandable_name = 'expandable_' . $type . 's';
     if (property_exists($object, $expandable_name) and $object->{$expandable_name}) {
       $key_to_remove = array_search($object->expanded, $object->{$expandable_name});

+ 2 - 2
tripal_chado/includes/TripalFields/ChadoField.inc

@@ -78,7 +78,7 @@ class ChadoField extends TripalField {
     if ($chado_table == $base_table) {
       // Get the base table column that is associated with the term
       // passed as $condition['column'].
-      $base_field = tripal_get_chado_semweb_column($chado_table, $condition['column']);
+      $base_field = chado_get_semweb_column($chado_table, $condition['column']);
       $query->condition('base.' . $base_field , $condition['value'], $operator);
     }
     else {
@@ -106,7 +106,7 @@ class ChadoField extends TripalField {
     if ($chado_table == $base_table) {
       // Get the base table column that is associated with the term
       // passed as $condition['column'].
-      $base_field = tripal_get_chado_semweb_column($chado_table, $order['column']);
+      $base_field = chado_get_semweb_column($chado_table, $order['column']);
       $query->orderBy('base.' . $base_field, $order['direction']);
     }
     else {

+ 12 - 12
tripal_chado/includes/TripalFields/chado_linker__contact/chado_linker__contact.inc

@@ -62,9 +62,9 @@ class chado_linker__contact extends ChadoField {
   public function elementInfo() {
 
     $field_term = $this->getFieldTermID();
-    $type_term = tripal_get_chado_semweb_term('contact', 'type_id');
-    $name_term = tripal_get_chado_semweb_term('contact', 'name');
-    $description_term = tripal_get_chado_semweb_term('contact', 'description');
+    $type_term = chado_get_semweb_term('contact', 'type_id');
+    $name_term = chado_get_semweb_term('contact', 'name');
+    $description_term = chado_get_semweb_term('contact', 'description');
 
     return array(
       $field_term => array(
@@ -124,9 +124,9 @@ class chado_linker__contact extends ChadoField {
     $field_column = $this->instance['settings']['chado_column'];
     $base_table = $this->instance['settings']['base_table'];
 
-    $type_term = tripal_get_chado_semweb_term('contact', 'type_id');
-    $name_term = tripal_get_chado_semweb_term('contact', 'name');
-    $description_term = tripal_get_chado_semweb_term('contact', 'description');
+    $type_term = chado_get_semweb_term('contact', 'type_id');
+    $name_term = chado_get_semweb_term('contact', 'name');
+    $description_term = chado_get_semweb_term('contact', 'description');
 
     // Get the FK that links to the base record.
     $schema = chado_get_schema($field_table);
@@ -193,9 +193,9 @@ class chado_linker__contact extends ChadoField {
     $operator = $condition['operator'];
 
     $field_term_id = $this->getFieldTermID();
-    $type_term = tripal_get_chado_semweb_term('contact', 'type_id');
-    $name_term = tripal_get_chado_semweb_term('contact', 'name');
-    $description_term = tripal_get_chado_semweb_term('contact', 'description');
+    $type_term = chado_get_semweb_term('contact', 'type_id');
+    $name_term = chado_get_semweb_term('contact', 'name');
+    $description_term = chado_get_semweb_term('contact', 'description');
 
     $contact_linker = $this->instance['settings']['chado_table'];
     $base_table = $this->instance['settings']['base_table'];
@@ -234,9 +234,9 @@ class chado_linker__contact extends ChadoField {
   public function queryOrder($query, $order) {
     $alias = $this->field['field_name'];
     $field_term_id = $this->getFieldTermID();
-    $type_term = tripal_get_chado_semweb_term('contact', 'type_id');
-    $name_term = tripal_get_chado_semweb_term('contact', 'name');
-    $description_term = tripal_get_chado_semweb_term('contact', 'description');
+    $type_term = chado_get_semweb_term('contact', 'type_id');
+    $name_term = chado_get_semweb_term('contact', 'name');
+    $description_term = chado_get_semweb_term('contact', 'description');
 
     $contact_linker = $this->instance['settings']['chado_table'];
     $base_table = $this->instance['settings']['base_table'];

+ 3 - 3
tripal_chado/includes/TripalFields/chado_linker__contact/chado_linker__contact_formatter.inc

@@ -24,9 +24,9 @@ class chado_linker__contact_formatter extends ChadoFieldFormatter {
     // Get the settings
     $settings = $display['settings'];
 
-    $type_term = tripal_get_chado_semweb_term('contact', 'type_id');
-    $name_term = tripal_get_chado_semweb_term('contact', 'name');
-    $description_term = tripal_get_chado_semweb_term('contact', 'description');
+    $type_term = chado_get_semweb_term('contact', 'type_id');
+    $name_term = chado_get_semweb_term('contact', 'name');
+    $description_term = chado_get_semweb_term('contact', 'description');
 
     $headers = array('Name', 'Description', 'Type');
     $rows = array();

+ 1 - 1
tripal_chado/includes/TripalFields/chado_linker__contact/chado_linker__contact_widget.inc

@@ -37,7 +37,7 @@ class chado_linker__contact_widget extends ChadoFieldWidget {
     $name = '';
     $value = '';
 
-    $name_term = tripal_get_chado_semweb_term('contact', 'name');
+    $name_term = chado_get_semweb_term('contact', 'name');
 
     // If the field already has a value then it will come through the $items
     // array.  This happens when editing an existing record.

+ 14 - 4
tripal_chado/includes/TripalFields/chado_linker__prop/chado_linker__prop.inc

@@ -70,7 +70,7 @@ class chado_linker__prop extends ChadoField {
 
     $vocabulary = $this->instance['settings']['term_vocabulary'];
     $accession = $this->instance['settings']['term_accession'];
-    $cvterm = tripal_get_cvterm(array(
+    $cvterm = chado_get_cvterm(array(
       'dbxref_id' => array(
         'db_id' => array(
           'name' => $vocabulary,
@@ -124,6 +124,16 @@ class chado_linker__prop extends ChadoField {
         );
       }
     }
+
+    // Ensure there are no values if there are no properties.
+    // This is necessary to make sure the field is not rendered when there are no properies.
+    // @todo: We should revisit this in the future as none of the other fields do this.
+    //        It was added here to make it easier to detect when the field was empty
+    //        but in hindsight, we would just check $entity->{$field_name}['und'][$i]['value']
+    //        in the formatter.
+    if (empty($properties)) {
+      unset($entity->{$field_name});
+    }
   }
 
   /**
@@ -141,7 +151,7 @@ class chado_linker__prop extends ChadoField {
     $vocab = $this->instance['settings']['term_vocabulary'];
     $accession = $this->instance['settings']['term_accession'];
 
-    $cvterm = tripal_get_cvterm(array('id' => $vocab . ':' . $accession));
+    $cvterm = chado_get_cvterm(array('id' => $vocab . ':' . $accession));
 
     $this->queryJoinOnce($query, $prop_linker, $alias, "base.$bpkey = $alias.$bpkey");
     $query->condition("$alias.type_id", $cvterm->cvterm_id);
@@ -163,9 +173,9 @@ class chado_linker__prop extends ChadoField {
     $vocab = $this->instance['settings']['term_vocabulary'];
     $accession = $this->instance['settings']['term_accession'];
 
-    $cvterm = tripal_get_cvterm(array('id' => $vocab . ':' . $accession));
+    $cvterm = chado_get_cvterm(array('id' => $vocab . ':' . $accession));
 
     $this->queryJoinOnce($query, $prop_linker, $alias, "base.$bpkey = $alias.$bpkey AND $alias.type_id = $cvterm->cvterm_id", "LEFT OUTER");
     $query->orderBy("$alias.value", $order['direction']);
   }
-}
+}

+ 5 - 0
tripal_chado/includes/TripalFields/chado_linker__prop/chado_linker__prop_formatter.inc

@@ -29,6 +29,11 @@ class chado_linker__prop_formatter extends ChadoFieldFormatter {
       $list[$index] = $item['value'];
     }
 
+    // Also need to make sure to not return markup if the field is empty.
+    if (empty($list)) {
+      return;
+    }
+
     // If more than one value has been found display all values in an unordered
     // list.
     if (count($list) > 1) {

+ 1 - 1
tripal_chado/includes/TripalFields/chado_linker__prop/chado_linker__prop_widget.inc

@@ -66,7 +66,7 @@ class chado_linker__prop_widget extends ChadoFieldWidget {
     if (!$type_id) {
       $vocabulary = $this->instance['settings']['term_vocabulary'];
       $accession = $this->instance['settings']['term_accession'];
-      $cvterm = tripal_get_cvterm(array(
+      $cvterm = chado_get_cvterm(array(
         'dbxref_id' => array(
           'db_id' => array(
             'name' => $vocabulary,

+ 2 - 2
tripal_chado/includes/TripalFields/data__accession/data__accession.inc

@@ -91,7 +91,7 @@ class data__accession extends ChadoField {
     $field_column = $this->instance['settings']['chado_column'];
 
     $field_term_id = $this->getFieldTermID();
-    $accession_term = tripal_get_chado_semweb_term($field_table, $field_column);
+    $accession_term = chado_get_semweb_term($field_table, $field_column);
 
     // We don't offer any sub elements so the value coming in should
     // always be the field_name.
@@ -108,7 +108,7 @@ class data__accession extends ChadoField {
     $field_column = $this->instance['settings']['chado_column'];
 
     $field_term_id = $this->getFieldTermID();
-    $accession_term = tripal_get_chado_semweb_term($field_table, $field_column);
+    $accession_term = chado_get_semweb_term($field_table, $field_column);
 
     // We don't offer any sub elements so the value coming in should
     // always be the field_name.

+ 2 - 2
tripal_chado/includes/TripalFields/data__accession/data__accession_widget.inc

@@ -39,7 +39,7 @@ class data__accession_widget extends ChadoFieldWidget {
     }
 
     $schema = chado_get_schema('dbxref');
-    $options = tripal_get_db_select_options();
+    $options = chado_get_db_select_options();
 
     //$widget['#element_validate'] = array('chado_base__dbxref_id_widget_validate');
     $widget['#prefix'] =  "<span id='$field_name-dbxref--db-id'>";
@@ -137,7 +137,7 @@ class data__accession_widget extends ChadoFieldWidget {
           'db_id' => $db_id,
           'accession' => $accession,
         );
-        $dbxref = tripal_insert_dbxref($values);
+        $dbxref = chado_insert_dbxref($values);
         $form_state['values'][$field_name]['und'][$delta]['chado-' . $field_table . '__dbxref_id'] = $dbxref->dbxref_id;
         $form_state['values'][$field_name]['und'][$delta]['value'] = $dbxref->dbxref_id;
       }

+ 5 - 5
tripal_chado/includes/TripalFields/data__sequence/data__sequence.inc

@@ -120,7 +120,7 @@ class data__sequence extends ChadoField {
         '@type' => 'SO:0000316',
         'type' => 'coding_sequence',
         'label' => 'Coding sequence (CDS)',
-        'defline' => tripal_get_fasta_defline($feature, 'CDS', NULL, '', strlen($coding_seq)),
+        'defline' => chado_get_fasta_defline($feature, 'CDS', NULL, '', strlen($coding_seq)),
         'residues' => $coding_seq,
       );
     }
@@ -137,13 +137,13 @@ class data__sequence extends ChadoField {
         'residues' => $attrs['residues'],
         '@type' => 'SO:0000110',
         'type' => 'sequence_feature',
-        'defline' => tripal_get_fasta_defline($feature, '', $attrs['featureloc'], 'CDS', strlen($attrs['residues'])),
+        'defline' => chado_get_fasta_defline($feature, '', $attrs['featureloc'], 'CDS', strlen($attrs['residues'])),
         'label' => 'Sequence from alignment at ' . $attrs['location'],
       );
 
 
       // check to see if this alignment has any CDS. If so, generate a CDS sequence
-      $cds_sequence = tripal_get_feature_sequences(
+      $cds_sequence = chado_get_feature_sequences(
           array(
             'feature_id' => $feature->feature_id,
             'parent_id' => $attrs['featureloc']->srcfeature_id->feature_id,
@@ -159,7 +159,7 @@ class data__sequence extends ChadoField {
           );
 
       if (count($cds_sequence) > 0) {
-        // the tripal_get_feature_sequences() function can return multiple sequences
+        // the chado_get_feature_sequences() function can return multiple sequences
         // if a feature is aligned to multiple places. In the case of CDSs we expect
         // that one mRNA is only aligned to a single location on the assembly so we
         // can access the CDS sequence with index 0.
@@ -168,7 +168,7 @@ class data__sequence extends ChadoField {
             'residues' => $cds_sequence[0]['residues'],
             '@type' => 'SO:0000316',
             'type' => 'coding_sequence',
-            'defline' => tripal_get_fasta_defline($feature, '', $attrs['featureloc'], 'CDS', $cds_sequence[0]['length']),
+            'defline' => chado_get_fasta_defline($feature, '', $attrs['featureloc'], 'CDS', $cds_sequence[0]['length']),
             'label' => 'Coding sequence (CDS) from alignment at  ' . $attrs['location'],
           );
         }

+ 16 - 16
tripal_chado/includes/TripalFields/data__sequence_coordinates/data__sequence_coordinates.inc

@@ -62,10 +62,10 @@ class data__sequence_coordinates extends ChadoField {
     $field_term = $this->getFieldTermID();
 
     $reference_term = 'data:3002';
-    $fmin_term = tripal_get_chado_semweb_term('featureloc', 'fmin');
-    $fmax_term = tripal_get_chado_semweb_term('featureloc', 'fmax');
-    $strand_term = tripal_get_chado_semweb_term('featureloc', 'strand');
-    $phase_term = tripal_get_chado_semweb_term('featureloc', 'phase');
+    $fmin_term = chado_get_semweb_term('featureloc', 'fmin');
+    $fmax_term = chado_get_semweb_term('featureloc', 'fmax');
+    $strand_term = chado_get_semweb_term('featureloc', 'strand');
+    $phase_term = chado_get_semweb_term('featureloc', 'phase');
 
     return array(
       $field_term => array(
@@ -144,10 +144,10 @@ class data__sequence_coordinates extends ChadoField {
 
     $field_term_id = $this->getFieldTermID();
     $reference_term = $field_term_id . ',' . 'data:3002';
-    $fmin_term = $field_term_id . ',' . tripal_get_chado_semweb_term('featureloc', 'fmin');
-    $fmax_term = $field_term_id . ',' . tripal_get_chado_semweb_term('featureloc', 'fmax');
-    $strand_term = $field_term_id . ',' . tripal_get_chado_semweb_term('featureloc', 'strand');
-    $phase_term = $field_term_id . ',' . tripal_get_chado_semweb_term('featureloc', 'phase');
+    $fmin_term = $field_term_id . ',' . chado_get_semweb_term('featureloc', 'fmin');
+    $fmax_term = $field_term_id . ',' . chado_get_semweb_term('featureloc', 'fmax');
+    $strand_term = $field_term_id . ',' . chado_get_semweb_term('featureloc', 'strand');
+    $phase_term = $field_term_id . ',' . chado_get_semweb_term('featureloc', 'phase');
 
     // Join to the organism table for this field.
     $this->queryJoinOnce($query, 'featureloc', $alias, "base.feature_id = $alias.feature_id");
@@ -185,10 +185,10 @@ class data__sequence_coordinates extends ChadoField {
 
     $field_term_id = $this->getFieldTermID();
     $reference_term = $field_term_id . ',' . 'data:3002';
-    $fmin_term = $field_term_id . ',' . tripal_get_chado_semweb_term('featureloc', 'fmin');
-    $fmax_term = $field_term_id . ',' . tripal_get_chado_semweb_term('featureloc', 'fmax');
-    $strand_term = $field_term_id . ',' . tripal_get_chado_semweb_term('featureloc', 'strand');
-    $phase_term = $field_term_id . ',' . tripal_get_chado_semweb_term('featureloc', 'phase');
+    $fmin_term = $field_term_id . ',' . chado_get_semweb_term('featureloc', 'fmin');
+    $fmax_term = $field_term_id . ',' . chado_get_semweb_term('featureloc', 'fmax');
+    $strand_term = $field_term_id . ',' . chado_get_semweb_term('featureloc', 'strand');
+    $phase_term = $field_term_id . ',' . chado_get_semweb_term('featureloc', 'phase');
 
     $this->queryJoinOnce($query, 'featureloc', $alias, "base.feature_id = $alias.feature_id", "LEFT OUTER");
     if ($order['column'] == $reference_term) {
@@ -218,10 +218,10 @@ class data__sequence_coordinates extends ChadoField {
 
     $description = 'schema:description';
     $reference_term = 'data:3002';
-    $fmin_term = tripal_get_chado_semweb_term('featureloc', 'fmin');
-    $fmax_term = tripal_get_chado_semweb_term('featureloc', 'fmax');
-    $strand_term = tripal_get_chado_semweb_term('featureloc', 'strand');
-    $phase_term = tripal_get_chado_semweb_term('featureloc', 'phase');
+    $fmin_term = chado_get_semweb_term('featureloc', 'fmin');
+    $fmax_term = chado_get_semweb_term('featureloc', 'fmax');
+    $strand_term = chado_get_semweb_term('featureloc', 'strand');
+    $phase_term = chado_get_semweb_term('featureloc', 'phase');
 
     $options = array(
       'return_array' => TRUE,

+ 4 - 4
tripal_chado/includes/TripalFields/data__sequence_coordinates/data__sequence_coordinates_formatter.inc

@@ -15,10 +15,10 @@ class data__sequence_coordinates_formatter extends ChadoFieldFormatter {
   public function view(&$element, $entity_type, $entity, $langcode, $items, $display) {
 
     $reference_term = 'data:3002';
-    $fmin_term = tripal_get_chado_semweb_term('featureloc', 'fmin');
-    $fmax_term = tripal_get_chado_semweb_term('featureloc', 'fmax');
-    $strand_term = tripal_get_chado_semweb_term('featureloc', 'strand');
-    $phase_term = tripal_get_chado_semweb_term('featureloc', 'phase');
+    $fmin_term = chado_get_semweb_term('featureloc', 'fmin');
+    $fmax_term = chado_get_semweb_term('featureloc', 'fmax');
+    $strand_term = chado_get_semweb_term('featureloc', 'strand');
+    $phase_term = chado_get_semweb_term('featureloc', 'phase');
 
     $content = '';
     foreach ($items as $item) {

+ 1 - 1
tripal_chado/includes/TripalFields/go__gene_expression/go__gene_expression.inc

@@ -124,7 +124,7 @@ class go__gene_expression extends ChadoField {
         // Add the pub information if a real pub is associated with the record.
         $pub = $exp_linker->pub_id;
         if ($pub->uniquename != 'null') {
-          $pub_details = tripal_get_minimal_pub_info($pub);
+          $pub_details = chado_get_minimal_pub_info($pub);
 
           $entity->{$field_name}['und'][$i]['value']['publication'] = $pub_details;
           $entity->{$field_name}['und'][$i]['value']['publication']['type'] = $pub->type_id->name;

+ 12 - 12
tripal_chado/includes/TripalFields/local__contact/local__contact.inc

@@ -61,9 +61,9 @@ class local__contact extends ChadoField {
    */
   public function elementInfo() {
     $field_term = $this->getFieldTermID();
-    $type_term = tripal_get_chado_semweb_term('contact', 'type_id');
-    $name_term = tripal_get_chado_semweb_term('contact', 'name');
-    $description_term = tripal_get_chado_semweb_term('contact', 'description');
+    $type_term = chado_get_semweb_term('contact', 'type_id');
+    $name_term = chado_get_semweb_term('contact', 'name');
+    $description_term = chado_get_semweb_term('contact', 'description');
 
     return array(
       $field_term => array(
@@ -123,9 +123,9 @@ class local__contact extends ChadoField {
     $field_column = $this->instance['settings']['chado_column'];
     $base_table = $this->instance['settings']['base_table'];
 
-    $type_term = tripal_get_chado_semweb_term('contact', 'type_id');
-    $name_term = tripal_get_chado_semweb_term('contact', 'name');
-    $description_term = tripal_get_chado_semweb_term('contact', 'description');
+    $type_term = chado_get_semweb_term('contact', 'type_id');
+    $name_term = chado_get_semweb_term('contact', 'name');
+    $description_term = chado_get_semweb_term('contact', 'description');
 
 
     // Set some defaults for the empty record.
@@ -163,9 +163,9 @@ class local__contact extends ChadoField {
     $operator = $condition['operator'];
 
     $field_term_id = $this->getFieldTermID();
-    $type_term = tripal_get_chado_semweb_term('contact', 'type_id');
-    $name_term = tripal_get_chado_semweb_term('contact', 'name');
-    $description_term = tripal_get_chado_semweb_term('contact', 'description');
+    $type_term = chado_get_semweb_term('contact', 'type_id');
+    $name_term = chado_get_semweb_term('contact', 'name');
+    $description_term = chado_get_semweb_term('contact', 'description');
 
     if ($field_table == 'biomaterial') {
       if ($record) {
@@ -200,9 +200,9 @@ class local__contact extends ChadoField {
   public function queryOrder($query, $order) {
     $alias = $this->field['field_name'];
     $field_term_id = $this->getFieldTermID();
-    $type_term = tripal_get_chado_semweb_term('contact', 'type_id');
-    $name_term = tripal_get_chado_semweb_term('contact', 'name');
-    $description_term = tripal_get_chado_semweb_term('contact', 'description');
+    $type_term = chado_get_semweb_term('contact', 'type_id');
+    $name_term = chado_get_semweb_term('contact', 'name');
+    $description_term = chado_get_semweb_term('contact', 'description');
 
     if ($field_table == 'biomaterial') {
       if ($record) {

+ 3 - 3
tripal_chado/includes/TripalFields/local__contact/local__contact_formatter.inc

@@ -24,9 +24,9 @@ class local__contact_formatter extends ChadoFieldFormatter {
     // Get the settings
     $settings = $display['settings'];
 
-    $type_term = tripal_get_chado_semweb_term('contact', 'type_id');
-    $name_term = tripal_get_chado_semweb_term('contact', 'name');
-    $description_term = tripal_get_chado_semweb_term('contact', 'description');
+    $type_term = chado_get_semweb_term('contact', 'type_id');
+    $name_term = chado_get_semweb_term('contact', 'name');
+    $description_term = chado_get_semweb_term('contact', 'description');
 
     $headers = array('Name', 'Description', 'Type');
     $rows = array();

+ 1 - 1
tripal_chado/includes/TripalFields/local__contact/local__contact_widget.inc

@@ -29,7 +29,7 @@ class local__contact_widget extends ChadoFieldWidget {
     $name = '';
     $value = '';
 
-    $name_term = tripal_get_chado_semweb_term('contact', 'name');
+    $name_term = chado_get_semweb_term('contact', 'name');
 
     // Set the linker field appropriately.
     if ($field_table == 'biomaterial') {

+ 12 - 12
tripal_chado/includes/TripalFields/local__source_data/local__source_data.inc

@@ -61,9 +61,9 @@ class local__source_data extends ChadoField {
   public function elementInfo() {
     $field_term = $this->getFieldTermID();
 
-    $sourcename_term = tripal_get_chado_semweb_term('analysis', 'sourcename');
-    $sourceversion_term = tripal_get_chado_semweb_term('analysis', 'sourceversion');
-    $sourceuri_term = tripal_get_chado_semweb_term('analysis', 'sourceuri');
+    $sourcename_term = chado_get_semweb_term('analysis', 'sourcename');
+    $sourceversion_term = chado_get_semweb_term('analysis', 'sourceversion');
+    $sourceuri_term = chado_get_semweb_term('analysis', 'sourceuri');
 
     return array(
       $field_term => array(
@@ -112,9 +112,9 @@ class local__source_data extends ChadoField {
     $operator = $condition['operator'];
 
     $field_term_id = $this->getFieldTermID();
-    $sourcename_term = $field_term_id . ',' . tripal_get_chado_semweb_term('analysis', 'sourcename');
-    $sourceversion_term = $field_term_id . ',' . tripal_get_chado_semweb_term('analysis', 'sourceversion');
-    $sourceuri_term = $field_term_id . ',' . tripal_get_chado_semweb_term('analysis', 'sourceuri');
+    $sourcename_term = $field_term_id . ',' . chado_get_semweb_term('analysis', 'sourcename');
+    $sourceversion_term = $field_term_id . ',' . chado_get_semweb_term('analysis', 'sourceversion');
+    $sourceuri_term = $field_term_id . ',' . chado_get_semweb_term('analysis', 'sourceuri');
 
     if ($condition['column'] == $sourcename_term) {
       $query->condition("base.sourcename", $condition['value'], $operator);
@@ -128,9 +128,9 @@ class local__source_data extends ChadoField {
    */
   public function queryOrder($query, $order) {
     $field_term_id = $this->getFieldTermID();
-    $sourcename_term = $field_term_id . ',' . tripal_get_chado_semweb_term('analysis', 'sourcename');
-    $sourceversion_term = $field_term_id . ',' . tripal_get_chado_semweb_term('analysis', 'sourceversion');
-    $sourceuri_term = $field_term_id . ',' . tripal_get_chado_semweb_term('analysis', 'sourceuri');
+    $sourcename_term = $field_term_id . ',' . chado_get_semweb_term('analysis', 'sourcename');
+    $sourceversion_term = $field_term_id . ',' . chado_get_semweb_term('analysis', 'sourceversion');
+    $sourceuri_term = $field_term_id . ',' . chado_get_semweb_term('analysis', 'sourceuri');
 
     if ($order['column'] == $sourcename_term) {
       $query->orderBy("base.sourcename", $order['direction']);
@@ -151,9 +151,9 @@ class local__source_data extends ChadoField {
     $field_table = $this->instance['settings']['chado_table'];
     $field_column = $this->instance['settings']['chado_column'];
 
-    $sourcename_term = tripal_get_chado_semweb_term('analysis', 'sourcename');
-    $sourceversion_term = tripal_get_chado_semweb_term('analysis', 'sourceversion');
-    $sourceuri_term = tripal_get_chado_semweb_term('analysis', 'sourceuri');
+    $sourcename_term = chado_get_semweb_term('analysis', 'sourcename');
+    $sourceversion_term = chado_get_semweb_term('analysis', 'sourceversion');
+    $sourceuri_term = chado_get_semweb_term('analysis', 'sourceuri');
 
     $entity->{$field_name}['und'][0] = array(
       'value' => array(

+ 3 - 3
tripal_chado/includes/TripalFields/local__source_data/local__source_data_formatter.inc

@@ -13,9 +13,9 @@ class local__source_data_formatter extends ChadoFieldFormatter {
    */
   public function view(&$element, $entity_type, $entity, $langcode, $items, $display) {
 
-    $sourcename_term = tripal_get_chado_semweb_term('analysis', 'sourcename');
-    $sourceversion_term = tripal_get_chado_semweb_term('analysis', 'sourceversion');
-    $sourceuri_term = tripal_get_chado_semweb_term('analysis', 'sourceuri');
+    $sourcename_term = chado_get_semweb_term('analysis', 'sourcename');
+    $sourceversion_term = chado_get_semweb_term('analysis', 'sourceversion');
+    $sourceuri_term = chado_get_semweb_term('analysis', 'sourceuri');
 
     $content = 'The data source is not provided.';
     if ($items[0]['value']) {

+ 19 - 19
tripal_chado/includes/TripalFields/obi__organism/obi__organism.inc

@@ -93,10 +93,10 @@ class obi__organism extends ChadoField {
 
     // Get the terms for each of the keys for the 'values' property.
     $label_term = 'rdfs:label';
-    $genus_term = tripal_get_chado_semweb_term('organism', 'genus');
-    $species_term = tripal_get_chado_semweb_term('organism', 'species');
-    $infraspecific_name_term = tripal_get_chado_semweb_term('organism', 'infraspecific_name');
-    $infraspecific_type_term = tripal_get_chado_semweb_term('organism', 'type_id');
+    $genus_term = chado_get_semweb_term('organism', 'genus');
+    $species_term = chado_get_semweb_term('organism', 'species');
+    $infraspecific_name_term = chado_get_semweb_term('organism', 'infraspecific_name');
+    $infraspecific_type_term = chado_get_semweb_term('organism', 'type_id');
 
 
     // Set the linker field appropriately.
@@ -120,7 +120,7 @@ class obi__organism extends ChadoField {
         $organism = $record->organism_id;
       }
       $string = $settings['field_display_string'];
-      $label = tripal_replace_chado_tokens($string, $organism);
+      $label = chado_replace_tokens($string, $organism);
       $entity->{$field_name}['und'][0]['value'] = array(
         $label_term => $label,
         $genus_term => $organism->genus,
@@ -177,10 +177,10 @@ class obi__organism extends ChadoField {
     $headers = array('Token', 'Description');
     $rows = array();
 
-    // Here we use the tripal_get_chado_tokens rather than the
+    // Here we use the chado_get_tokens rather than the
     // tripal_get_entity_tokens because we can't gurantee that all organisms
     // have entities.
-    $tokens = tripal_get_chado_tokens('organism');
+    $tokens = chado_get_tokens('organism');
     foreach ($tokens as $token) {
       $rows[] = array(
         $token['token'],
@@ -211,10 +211,10 @@ class obi__organism extends ChadoField {
   public function elementInfo() {
     $field_term = $this->getFieldTermID();
 
-    $genus_term = tripal_get_chado_semweb_term('organism', 'genus');
-    $species_term = tripal_get_chado_semweb_term('organism', 'species');
-    $infraspecific_name_term = tripal_get_chado_semweb_term('organism', 'infraspecific_name');
-    $infraspecific_type_term = tripal_get_chado_semweb_term('organism', 'type_id');
+    $genus_term = chado_get_semweb_term('organism', 'genus');
+    $species_term = chado_get_semweb_term('organism', 'species');
+    $infraspecific_name_term = chado_get_semweb_term('organism', 'infraspecific_name');
+    $infraspecific_type_term = chado_get_semweb_term('organism', 'type_id');
 
     return array(
       $field_term => array(
@@ -285,10 +285,10 @@ class obi__organism extends ChadoField {
     $operator = $condition['operator'];
 
     $field_term_id = $this->getFieldTermID();
-    $genus_term = $field_term_id . ',' . tripal_get_chado_semweb_term('organism', 'genus');
-    $species_term = $field_term_id . ',' . tripal_get_chado_semweb_term('organism', 'species');
-    $infraspecific_name_term = $field_term_id . ',' . tripal_get_chado_semweb_term('organism', 'infraspecific_name');
-    $infraspecific_type_term = $field_term_id . ',' . tripal_get_chado_semweb_term('organism', 'type_id');
+    $genus_term = $field_term_id . ',' . chado_get_semweb_term('organism', 'genus');
+    $species_term = $field_term_id . ',' . chado_get_semweb_term('organism', 'species');
+    $infraspecific_name_term = $field_term_id . ',' . chado_get_semweb_term('organism', 'infraspecific_name');
+    $infraspecific_type_term = $field_term_id . ',' . chado_get_semweb_term('organism', 'type_id');
 
     // Join to the organism table for this field.
     $this->queryJoinOnce($query, 'organism', $alias, "base.organism_id = $alias.organism_id");
@@ -329,10 +329,10 @@ class obi__organism extends ChadoField {
     $alias = $this->field['field_name'];
 
     $field_term_id = $this->getFieldTermID();
-    $genus_term = $field_term_id . ',' . tripal_get_chado_semweb_term('organism', 'genus');
-    $species_term = $field_term_id . ',' . tripal_get_chado_semweb_term('organism', 'species');
-    $infraspecific_name_term = $field_term_id . ',' . tripal_get_chado_semweb_term('organism', 'infraspecific_name');
-    $infraspecific_type_term = $field_term_id . ',' . tripal_get_chado_semweb_term('organism', 'type_id');
+    $genus_term = $field_term_id . ',' . chado_get_semweb_term('organism', 'genus');
+    $species_term = $field_term_id . ',' . chado_get_semweb_term('organism', 'species');
+    $infraspecific_name_term = $field_term_id . ',' . chado_get_semweb_term('organism', 'infraspecific_name');
+    $infraspecific_type_term = $field_term_id . ',' . chado_get_semweb_term('organism', 'type_id');
 
     // Join to the organism table for this field.
     $this->queryJoinOnce($query, 'organism', $alias, "base.organism_id = $alias.organism_id");

+ 1 - 1
tripal_chado/includes/TripalFields/obi__organism/obi__organism_widget.inc

@@ -39,7 +39,7 @@ class obi__organism_widget extends ChadoFieldWidget {
       '#type' => 'value',
       '#value' => array_key_exists($delta, $items) ? $items[$delta]['value'] : '',
     );
-    $options = tripal_get_organism_select_options(FALSE);
+    $options = chado_get_organism_select_options(FALSE);
     $widget[$linker_field] = array(
       '#type' => 'select',
       '#title' => $element['#title'],

+ 24 - 24
tripal_chado/includes/TripalFields/ogi__location_on_map/ogi__location_on_map.inc

@@ -61,12 +61,12 @@ class ogi__location_on_map extends ChadoField {
     $field_term = $this->getFieldTermID();
 
     $map_term = 'data:1274';
-    $name_term = tripal_get_chado_semweb_term('featuremap', 'name');
-    $description_term = tripal_get_chado_semweb_term('featuremap', 'description');
-    $mappos_term = tripal_get_chado_semweb_term('featurepos', 'mappos');
-    $ref_feature_term = tripal_get_chado_semweb_term('featurepos', 'map_feature_id');
-    $ref_feature_name = tripal_get_chado_semweb_term('feature', 'name');
-    $ref_feature_id = tripal_get_chado_semweb_term('feature', 'uniquename');
+    $name_term = chado_get_semweb_term('featuremap', 'name');
+    $description_term = chado_get_semweb_term('featuremap', 'description');
+    $mappos_term = chado_get_semweb_term('featurepos', 'mappos');
+    $ref_feature_term = chado_get_semweb_term('featurepos', 'map_feature_id');
+    $ref_feature_name = chado_get_semweb_term('feature', 'name');
+    $ref_feature_id = chado_get_semweb_term('feature', 'uniquename');
     $ref_feature_type = 'rdfs:type';
 
     return array(
@@ -167,14 +167,14 @@ class ogi__location_on_map extends ChadoField {
     // Map details.
     $field_term_id = $this->getFieldTermID();
     $map_term = 'data:1274';
-    $name_term = $field_term_id . ',' . $map_term . ',' . tripal_get_chado_semweb_term('featuremap', 'name');
-    $description_term = $field_term_id . ',' . $map_term . ',' . tripal_get_chado_semweb_term('featuremap', 'description');
-    $mappos_term = $field_term_id . ',' . tripal_get_chado_semweb_term('featurepos', 'mappos');
+    $name_term = $field_term_id . ',' . $map_term . ',' . chado_get_semweb_term('featuremap', 'name');
+    $description_term = $field_term_id . ',' . $map_term . ',' . chado_get_semweb_term('featuremap', 'description');
+    $mappos_term = $field_term_id . ',' . chado_get_semweb_term('featurepos', 'mappos');
 
     // Reference sequence details.
-    $ref_feature_term = tripal_get_chado_semweb_term('featurepos', 'map_feature_id');
-    $ref_feature_name = $field_term_id . ',' . $ref_feature_term . ',' .tripal_get_chado_semweb_term('feature', 'name');
-    $ref_feature_id = $field_term_id . ',' . $ref_feature_term . ',' .tripal_get_chado_semweb_term('feature', 'uniquename');
+    $ref_feature_term = chado_get_semweb_term('featurepos', 'map_feature_id');
+    $ref_feature_name = $field_term_id . ',' . $ref_feature_term . ',' .chado_get_semweb_term('feature', 'name');
+    $ref_feature_id = $field_term_id . ',' . $ref_feature_term . ',' .chado_get_semweb_term('feature', 'uniquename');
     $ref_feature_type = $field_term_id . ',' . $ref_feature_term . ',' .'rdfs:type';
 
     $this->queryJoinOnce($query, 'featurepos', $alias, "base.feature_id = $alias.feature_id");
@@ -214,14 +214,14 @@ class ogi__location_on_map extends ChadoField {
     // Map details.
     $field_term_id = $this->getFieldTermID();
     $map_term = 'data:1274';
-    $name_term = $field_term_id . ',' . $map_term . ',' . tripal_get_chado_semweb_term('featuremap', 'name');
-    $description_term = $field_term_id . ',' . $map_term . ',' . tripal_get_chado_semweb_term('featuremap', 'description');
-    $mappos_term = $field_term_id . ',' . tripal_get_chado_semweb_term('featurepos', 'mappos');
+    $name_term = $field_term_id . ',' . $map_term . ',' . chado_get_semweb_term('featuremap', 'name');
+    $description_term = $field_term_id . ',' . $map_term . ',' . chado_get_semweb_term('featuremap', 'description');
+    $mappos_term = $field_term_id . ',' . chado_get_semweb_term('featurepos', 'mappos');
 
     // Reference sequence details.
-    $ref_feature_term = tripal_get_chado_semweb_term('featurepos', 'map_feature_id');
-    $ref_feature_name = $field_term_id . ',' . $ref_feature_term . ',' .tripal_get_chado_semweb_term('feature', 'name');
-    $ref_feature_id = $field_term_id . ',' . $ref_feature_term . ',' .tripal_get_chado_semweb_term('feature', 'uniquename');
+    $ref_feature_term = chado_get_semweb_term('featurepos', 'map_feature_id');
+    $ref_feature_name = $field_term_id . ',' . $ref_feature_term . ',' .chado_get_semweb_term('feature', 'name');
+    $ref_feature_id = $field_term_id . ',' . $ref_feature_term . ',' .chado_get_semweb_term('feature', 'uniquename');
     $ref_feature_type = $field_term_id . ',' . $ref_feature_term . ',' .'rdfs:type';
 
     $this->queryJoinOnce($query, 'featurepos', $alias, "base.feature_id = $alias.feature_id", 'LEFT OUTER');
@@ -265,14 +265,14 @@ class ogi__location_on_map extends ChadoField {
 
     // Map details
     $map_term = 'data:1274';
-    $name_term = tripal_get_chado_semweb_term('featuremap', 'name');
-    $description_term = tripal_get_chado_semweb_term('featuremap', 'description');
-    $mappos_term = tripal_get_chado_semweb_term('featurepos', 'mappos');
+    $name_term = chado_get_semweb_term('featuremap', 'name');
+    $description_term = chado_get_semweb_term('featuremap', 'description');
+    $mappos_term = chado_get_semweb_term('featurepos', 'mappos');
 
     // Reference sequence details.
-    $ref_feature_term = tripal_get_chado_semweb_term('featurepos', 'map_feature_id');
-    $ref_feature_name = tripal_get_chado_semweb_term('feature', 'name');
-    $ref_feature_id = tripal_get_chado_semweb_term('feature', 'uniquename');
+    $ref_feature_term = chado_get_semweb_term('featurepos', 'map_feature_id');
+    $ref_feature_name = chado_get_semweb_term('feature', 'name');
+    $ref_feature_id = chado_get_semweb_term('feature', 'uniquename');
     $ref_feature_type = 'rdfs:type';
 
     // Set some defaults for the empty record.

+ 13 - 13
tripal_chado/includes/TripalFields/sbo__database_cross_reference/sbo__database_cross_reference.inc

@@ -63,9 +63,9 @@ class sbo__database_cross_reference extends ChadoField {
   public function elementInfo() {
 
     $field_term = $this->getFieldTermID();
-    $dbname_term = tripal_get_chado_semweb_term('db', 'name');
-    $accession_term = tripal_get_chado_semweb_term('dbxref', 'accession');
-    $dburl_term = tripal_get_chado_semweb_term('db', 'url');
+    $dbname_term = chado_get_semweb_term('db', 'name');
+    $accession_term = chado_get_semweb_term('dbxref', 'accession');
+    $dburl_term = chado_get_semweb_term('db', 'url');
 
     return array(
       $field_term => array(
@@ -125,9 +125,9 @@ class sbo__database_cross_reference extends ChadoField {
     $fkey_lcolumn = key($schema['foreign keys'][$base_table]['columns']);
     $fkey_rcolumn = $schema['foreign keys'][$base_table]['columns'][$fkey_lcolumn];
 
-    $dbname_term = tripal_get_chado_semweb_term('db', 'name');
-    $accession_term = tripal_get_chado_semweb_term('dbxref', 'accession');
-    $dburl_term = tripal_get_chado_semweb_term('db', 'url');
+    $dbname_term = chado_get_semweb_term('db', 'name');
+    $accession_term = chado_get_semweb_term('dbxref', 'accession');
+    $dburl_term = chado_get_semweb_term('db', 'url');
 
     // Set some defaults for the empty record.
     $entity->{$field_name}['und'][0] = array(
@@ -153,7 +153,7 @@ class sbo__database_cross_reference extends ChadoField {
           continue;
         }
 
-        $URL = tripal_get_dbxref_url($dbxref);
+        $URL = chado_get_dbxref_url($dbxref);
         $entity->{$field_name}['und'][$i] = array(
           'value' => array(
             $dbname_term => $dbxref->db_id->name,
@@ -186,9 +186,9 @@ class sbo__database_cross_reference extends ChadoField {
     $operator = $condition['operator'];
 
     $field_term_id = $this->getFieldTermID();
-    $dbname_term = $field_term_id . ',' . tripal_get_chado_semweb_term('db', 'name');
-    $accession_term = $field_term_id . ',' . tripal_get_chado_semweb_term('dbxref', 'accession');
-    $dburl_term = $field_term_id . ',' . tripal_get_chado_semweb_term('db', 'url');
+    $dbname_term = $field_term_id . ',' . chado_get_semweb_term('db', 'name');
+    $accession_term = $field_term_id . ',' . chado_get_semweb_term('dbxref', 'accession');
+    $dburl_term = $field_term_id . ',' . chado_get_semweb_term('db', 'url');
 
     $this->queryJoinOnce($query, $field_table, $alias, "base.$bpkey = $alias.$bpkey");
     $this->queryJoinOnce($query, 'dbxref', $alias . '_DBX', $alias . "_DBX.dbxref_id = $alias.dbxref_id");
@@ -216,9 +216,9 @@ class sbo__database_cross_reference extends ChadoField {
     $alias = $this->field['field_name'];
 
     $field_term_id = $this->getFieldTermID();
-    $dbname_term = $field_term_id . ',' . tripal_get_chado_semweb_term('db', 'name');
-    $accession_term = $field_term_id . ',' . tripal_get_chado_semweb_term('dbxref', 'accession');
-    $dburl_term = $field_term_id . ',' . tripal_get_chado_semweb_term('db', 'url');
+    $dbname_term = $field_term_id . ',' . chado_get_semweb_term('db', 'name');
+    $accession_term = $field_term_id . ',' . chado_get_semweb_term('dbxref', 'accession');
+    $dburl_term = $field_term_id . ',' . chado_get_semweb_term('db', 'url');
 
     $this->queryJoinOnce($query, $field_table, $alias, "base.$bpkey = $alias.$bpkey", "LEFT OUTER");
     $this->queryJoinOnce($query, 'dbxref', $alias . '_DBX', $alias . "_DBX.dbxref_id = $alias.dbxref_id", "LEFT OUTER");

+ 5 - 5
tripal_chado/includes/TripalFields/sbo__database_cross_reference/sbo__database_cross_reference_formatter.inc

@@ -21,9 +21,9 @@ class sbo__database_cross_reference_formatter extends ChadoFieldFormatter {
     $base_table = $this->instance['settings']['base_table'];
     $linker_table = $base_table . '_dbxref';
 
-    $dbname_term = tripal_get_chado_semweb_term('db', 'name');
-    $accession_term = tripal_get_chado_semweb_term('dbxref', 'accession');
-    $dburl_term = tripal_get_chado_semweb_term('db', 'url');
+    $dbname_term = chado_get_semweb_term('db', 'name');
+    $accession_term = chado_get_semweb_term('dbxref', 'accession');
+    $dburl_term = chado_get_semweb_term('db', 'url');
 
     foreach ($items as $delta => $item) {
       if (!$item['value']) {
@@ -31,8 +31,8 @@ class sbo__database_cross_reference_formatter extends ChadoFieldFormatter {
       }
       $content = $item['value'][$dbname_term] . ':' . $item['value'][$accession_term];
       if ($item['value'][$dburl_term]) {
-        $dbxref = tripal_get_dbxref(array('dbxref_id' => $item['chado-' . $linker_table . '__dbxref_id']));
-        $url = tripal_get_dbxref_url($dbxref);
+        $dbxref = chado_get_dbxref(array('dbxref_id' => $item['chado-' . $linker_table . '__dbxref_id']));
+        $url = chado_get_dbxref_url($dbxref);
         $content = l($content, $url, array('attributes' => array('target' => '_blank')));
       }
       $element[$delta] = array(

+ 1 - 1
tripal_chado/includes/TripalFields/sbo__database_cross_reference/sbo__database_cross_reference_widget.inc

@@ -73,7 +73,7 @@ class sbo__database_cross_reference_widget extends ChadoFieldWidget {
       '#type' => 'value',
       '#default_value' => $dbxref_id,
     );
-    $options = tripal_get_db_select_options();
+    $options = chado_get_db_select_options();
     $widget['db_id'] = array(
       '#type' => 'select',
       '#title' => t('Database'),

+ 5 - 5
tripal_chado/includes/TripalFields/sbo__relationship/sbo__relationship.inc

@@ -618,7 +618,7 @@ class sbo__relationship extends ChadoField {
     //         as the relationship types. This select box will replace the vocabulary select box if the
     //         following value is set.'
     //     );
-    $vocs = tripal_get_cv_select_options();
+    $vocs = chado_get_cv_select_options();
     $element['relationships']['option1'] = array(
       '#type' => 'item',
       '#title' => 'Option #1',
@@ -725,7 +725,7 @@ class sbo__relationship extends ChadoField {
           if (strpos($type, '|')) {
             $tmp = explode('|', $type, 2);
             $type = trim($tmp[1]);
-            $cv = tripal_get_cv(array('name' => trim($tmp[0])));
+            $cv = chado_get_cv(array('name' => trim($tmp[0])));
             if($cv) {
               $sql = "SELECT cvterm_id FROM {cvterm} WHERE name = :name AND cv_id = :cv_id";
               $results = chado_query($sql, array(':name' => $type, ':cv_id' => $cv->cv_id));
@@ -753,7 +753,7 @@ class sbo__relationship extends ChadoField {
           if (strpos($type, '|')) {
             $tmp = explode('|', $type, 2);
             $type = trim($tmp[1]);
-            $cv = tripal_get_cv(array('name' => trim($tmp[0])));
+            $cv = chado_get_cv(array('name' => trim($tmp[0])));
             if ($cv) {
               $sql = "SELECT cvterm_id FROM {cvterm} WHERE name = :name AND cv_id = :cv_id";
               $results = chado_query($sql, array(':name' => $type, ':cv_id' => $cv->cv_id));
@@ -774,14 +774,14 @@ class sbo__relationship extends ChadoField {
     if ($option2) {
       $cv_id = $settings['option2_vocab'];
       $supertype = $settings['option2_parent'];
-      $term = tripal_get_cvterm(array(
+      $term = chado_get_cvterm(array(
         'name' => trim($supertype),
         'cv_id' => $cv_id,
       ));
       // Tripal cv autocomplete also allow cvterm synonyms, if the parent term doesn't match
       // a cvterm, try cvtermsynonym
       if (!$term) {
-        $synonym = tripal_get_cvterm(
+        $synonym = chado_get_cvterm(
             array(
               'synonym' => array(
                 'name' => trim($supertype),

+ 7 - 7
tripal_chado/includes/TripalFields/sbo__relationship/sbo__relationship_widget.inc

@@ -194,13 +194,13 @@ class sbo__relationship_widget extends ChadoFieldWidget {
         if (trim($rtype) == '') {
           continue;
         }
-        $term = tripal_get_cvterm(array('name' => trim($rtype)));
+        $term = chado_get_cvterm(array('name' => trim($rtype)));
         // Try to get term with vocabulary specified
         if (!$term) {
           $tmp = explode('|', trim($rtype), 2);
-          $cv = tripal_get_cv(array('name' => trim($tmp[0])));
+          $cv = chado_get_cv(array('name' => trim($tmp[0])));
           $rtype = trim($tmp[1]);
-          $term = tripal_get_cvterm(array('name' => $rtype, 'cv_id' => $cv->cv_id));
+          $term = chado_get_cvterm(array('name' => $rtype, 'cv_id' => $cv->cv_id));
         }
         $rtype_options[$term->cvterm_id] = $term->name;
       }
@@ -220,7 +220,7 @@ class sbo__relationship_widget extends ChadoFieldWidget {
         'cv_id' => $option2_vocab,
         'name' => $option2_parent
       );
-      $parent_term = tripal_get_cvterm($values);
+      $parent_term = chado_get_cvterm($values);
 
       // If the term wasn't found then see if it's a synonym.
       if(!$parent_term) {
@@ -229,7 +229,7 @@ class sbo__relationship_widget extends ChadoFieldWidget {
             'name' => trim($option2_parent),
           )
         );
-        $synonym = tripal_get_cvterm($values);
+        $synonym = chado_get_cvterm($values);
         if ($synonym && $synonym->cv_id->cv_id == $option2_vocab) {
           $parent_term = $synonym;
         }
@@ -283,11 +283,11 @@ class sbo__relationship_widget extends ChadoFieldWidget {
     else {
       // Set up available cvterms for selection
       $vocs = array(0 => 'Select a vocabulary');
-      $vocs = tripal_get_cv_select_options();
+      $vocs = chado_get_cv_select_options();
       $cv_id = isset($form_state['values'][$field_name]['und'][0]['vocabulary']) ? $form_state['values'][$field_name]['und'][0]['vocabulary'] : 0;
       // Try getting the cv_id from cvterm for existing records
       if (!$cv_id && $type_id) {
-        $cvterm = tripal_get_cvterm(array('cvterm_id' => $type_id));
+        $cvterm = chado_get_cvterm(array('cvterm_id' => $type_id));
         if (isset($cvterm->cv_id->cv_id)) {
           $cv_id = $cvterm->cv_id->cv_id;
           $default_term = $cvterm->name;

+ 2 - 2
tripal_chado/includes/TripalFields/schema__additional_type/schema__additional_type_widget.inc

@@ -68,8 +68,8 @@ class schema__additional_type_widget extends ChadoFieldWidget {
       }
     }
     elseif ($vocabulary) {
-      $cv = tripal_get_cv(array('name' => $vocabulary));
-      $options = tripal_get_cvterm_select_options($cv->cv_id);
+      $cv = chado_get_cv(array('name' => $vocabulary));
+      $options = chado_get_cvterm_select_options($cv->cv_id);
     }
     // If no vocabulary or parent term are provided then just give a generic
     // term finder.

+ 1 - 1
tripal_chado/includes/TripalFields/schema__publication/schema__publication.inc

@@ -107,7 +107,7 @@ class schema__publication extends ChadoField {
       $i = 0;
       foreach ($record->$linker_table as $index => $linker) {
         $pub = $linker->pub_id;
-        $pub_details = tripal_get_minimal_pub_info($pub);
+        $pub_details = chado_get_minimal_pub_info($pub);
 
         $entity->{$field_name}['und'][$i]['value'] = $pub_details;
         $entity->{$field_name}['und'][$i]['chado-' . $field_table . '__' . $pkey] = $linker->$pkey;

+ 1 - 1
tripal_chado/includes/TripalFields/schema__publication/schema__publication_widget.inc

@@ -37,7 +37,7 @@ class schema__publication_widget extends ChadoFieldWidget {
       $fkey_value = tripal_get_field_item_keyval($items, $delta, 'chado-' . $table_name . '__' . $fkey, $fkey_value);
       $pub_id = tripal_get_field_item_keyval($items, $delta, 'chado-' . $table_name . '__pub_id', $pub_id);
       if ($pub_id) {
-        $pub = tripal_get_publication(array('pub_id' => $pub_id));
+        $pub = chado_get_publication(array('pub_id' => $pub_id));
         $title =  $pub->title . ' [id:' . $pub->pub_id . ']';
       }
     }

+ 13 - 13
tripal_chado/includes/TripalFields/sio__annotation/sio__annotation.inc

@@ -92,9 +92,9 @@ class sio__annotation extends ChadoField {
     $field_table = $this->instance['settings']['chado_table'];
     $schema = chado_get_schema($field_table);
 
-    $vocabulary_term = tripal_get_chado_semweb_term('cvterm', 'cv_id');
-    $accession_term = tripal_get_chado_semweb_term('dbxref', 'accession');
-    $definition_term = tripal_get_chado_semweb_term('cvterm', 'definition');
+    $vocabulary_term = chado_get_semweb_term('cvterm', 'cv_id');
+    $accession_term = chado_get_semweb_term('dbxref', 'accession');
+    $definition_term = chado_get_semweb_term('cvterm', 'definition');
 
     $field_term = $this->getFieldTermID();
     $info = array(
@@ -134,7 +134,7 @@ class sio__annotation extends ChadoField {
     );
 
     if (array_key_exists('is_not', $schema['fields'])) {
-      $negation_term = tripal_get_chado_semweb_term($field_table, 'is_not');
+      $negation_term = chado_get_semweb_term($field_table, 'is_not');
       $info[$field_term]['elements'][$negation_term] = array(
         'sortable' => FALSE,
         'searchable' => FALSE,
@@ -145,7 +145,7 @@ class sio__annotation extends ChadoField {
       );
     }
     if (array_key_exists('rank', $schema['fields'])) {
-      $rank_term = tripal_get_chado_semweb_term($field_table, 'rank');
+      $rank_term = chado_get_semweb_term($field_table, 'rank');
       $info[$field_term]['elements'][$rank_term] = array(
         'sortable' => FALSE,
         'searchable' => FALSE,
@@ -177,9 +177,9 @@ class sio__annotation extends ChadoField {
 
     $field_term_id = $this->getFieldTermID();
 
-    $vocabulary_term = $field_term_id . ',' . tripal_get_chado_semweb_term('cvterm', 'cv_id');
-    $accession_term = $field_term_id . ',' . tripal_get_chado_semweb_term('dbxref', 'accession');
-    $definition_term = $field_term_id . ',' . tripal_get_chado_semweb_term('cvterm', 'definition');
+    $vocabulary_term = $field_term_id . ',' . chado_get_semweb_term('cvterm', 'cv_id');
+    $accession_term = $field_term_id . ',' . chado_get_semweb_term('dbxref', 'accession');
+    $definition_term = $field_term_id . ',' . chado_get_semweb_term('cvterm', 'definition');
 
 
     // Join to the xxx_cvterm table for this field.
@@ -218,9 +218,9 @@ class sio__annotation extends ChadoField {
 
     $field_term_id = $this->getFieldTermID();
 
-    $vocabulary_term = $field_term_id . ',' . tripal_get_chado_semweb_term('cvterm', 'cv_id');
-    $accession_term = $field_term_id . ',' . tripal_get_chado_semweb_term('dbxref', 'accession');
-    $definition_term = $field_term_id . ',' . tripal_get_chado_semweb_term('cvterm', 'definition');
+    $vocabulary_term = $field_term_id . ',' . chado_get_semweb_term('cvterm', 'cv_id');
+    $accession_term = $field_term_id . ',' . chado_get_semweb_term('dbxref', 'accession');
+    $definition_term = $field_term_id . ',' . chado_get_semweb_term('cvterm', 'definition');
 
     // Join to the xxx_cvterm table for this field.
     $this->queryJoinOnce($query, $field_table, $alias, "base.$fkey_rcolumn = $alias.$fkey_lcolumn");
@@ -264,10 +264,10 @@ class sio__annotation extends ChadoField {
     $name = tripal_get_chado_semweb_term('cvterm', 'name');
 
     if (array_key_exists('is_not', $schema['fields'])) {
-      $negation = tripal_get_chado_semweb_term($field_table, 'is_not');
+      $negation = chado_get_semweb_term($field_table, 'is_not');
     }
     if (array_key_exists('rank', $schema['fields'])) {
-      $rank_term = tripal_get_chado_semweb_term($field_table, 'rank');
+      $rank_term = chado_get_semweb_term($field_table, 'rank');
     }
 
     // Set some defaults for the empty record.

+ 3 - 2
tripal_chado/includes/TripalFields/sio__annotation/sio__annotation_formatter.inc

@@ -22,8 +22,9 @@ class sio__annotation_formatter extends ChadoFieldFormatter {
     $accession_term = tripal_get_chado_semweb_term('dbxref', 'accession');
     $definition_term = tripal_get_chado_semweb_term('cvterm', 'definition');
     $name_term = tripal_get_chado_semweb_term('cvterm', 'name');
+
     if (array_key_exists('is_not', $schema['fields'])) {
-      $negation_term = tripal_get_chado_semweb_term($field_table, 'is_not');
+      $negation_term = chado_get_semweb_term($field_table, 'is_not');
     }
 
     $chado_table = $this->instance['settings']['chado_table'];
@@ -36,7 +37,7 @@ class sio__annotation_formatter extends ChadoFieldFormatter {
         // Build the accession.
         $accession = $dbxref->db_id->name . ':' . $dbxref->accession;
         if ($dbxref->db_id->urlprefix) {
-          $accession = l($accession, tripal_get_dbxref_url($dbxref), array('attributes' => array('target' => '_blank')));
+          $accession = l($accession, chado_get_dbxref_url($dbxref), array('attributes' => array('target' => '_blank')));
         }
 
         $row = array(

+ 10 - 10
tripal_chado/includes/TripalFields/sio__annotation/sio__annotation_widget.inc

@@ -27,11 +27,11 @@ class sio__annotation_widget extends ChadoFieldWidget {
     $fkey_lcolumn = key($schema['foreign keys'][$base_table]['columns']);
     $fkey_rcolumn = $schema['foreign keys'][$base_table]['columns'][$fkey_lcolumn];
 
-    $vocabulary = tripal_get_chado_semweb_term('cvterm', 'cv_id');
-    $accession = tripal_get_chado_semweb_term('dbxref', 'accession');
-    $definition = tripal_get_chado_semweb_term('cvterm', 'definition');
+    $vocabulary = chado_get_semweb_term('cvterm', 'cv_id');
+    $accession = chado_get_semweb_term('dbxref', 'accession');
+    $definition = chado_get_semweb_term('cvterm', 'definition');
     if (array_key_exists('is_not', $schema['fields'])) {
-      $negation = tripal_get_chado_semweb_term($field_table, 'is_not');
+      $negation = chado_get_semweb_term($field_table, 'is_not');
     }
 
     // Get the field defaults.
@@ -118,7 +118,7 @@ class sio__annotation_widget extends ChadoFieldWidget {
       '#default_value' => $fk_value,
     );
 
-    $cvs = tripal_get_cv_select_options();
+    $cvs = chado_get_cv_select_options();
     $widget['cv_id'] = array(
       '#type' => 'select',
       '#title' => t('Vocabulary'),
@@ -192,11 +192,11 @@ class sio__annotation_widget extends ChadoFieldWidget {
     $fkey_lcolumn = key($schema['foreign keys'][$base_table]['columns']);
     $fkey_rcolumn = $schema['foreign keys'][$base_table]['columns'][$fkey_lcolumn];
 
-    $vocabulary = tripal_get_chado_semweb_term('cvterm', 'cv_id');
-    $accession = tripal_get_chado_semweb_term('dbxref', 'accession');
-    $definition = tripal_get_chado_semweb_term('cvterm', 'definition');
+    $vocabulary = chado_get_semweb_term('cvterm', 'cv_id');
+    $accession = chado_get_semweb_term('dbxref', 'accession');
+    $definition = chado_get_semweb_term('cvterm', 'definition');
     if (array_key_exists('is_not', $schema['fields'])) {
-      $negation = tripal_get_chado_semweb_term($field_table, 'is_not');
+      $negation = chado_get_semweb_term($field_table, 'is_not');
     }
 
     $record_id = $form_state['values'][$field_name]['und'][$delta]['chado-' . $field_table . '__' . $pkey];
@@ -214,7 +214,7 @@ class sio__annotation_widget extends ChadoFieldWidget {
       }
       // Use the NULL pub.
       else {
-        $pub = tripal_get_publication(array('uniquename' => 'null'));
+        $pub = chado_get_publication(array('uniquename' => 'null'));
         $form_state['values'][$field_name][$langcode][$delta]['chado-' . $field_table . '__pub_id'] = $pub->pub_id;
       }
     }

+ 1 - 1
tripal_chado/includes/TripalFields/sio__references/sio__references.inc

@@ -129,7 +129,7 @@ class sio__references extends ChadoField {
               ->execute()
               ->fetchObject();
             if ($mapping) {
-              $cvterm = tripal_get_cvterm(array('cvterm_id' => $mapping->cvterm_id));
+              $cvterm = chado_get_cvterm(array('cvterm_id' => $mapping->cvterm_id));
               $entity->{$field_name}['und'][$delta]['value']['rdfs:type'] = $cvterm->name;
             }
           }

+ 1 - 1
tripal_chado/includes/TripalFields/sio__vocabulary/sio__vocabulary_widget.inc

@@ -30,7 +30,7 @@ class sio__vocabulary_widget extends ChadoFieldWidget {
       // Use the bundle to get the cv_id choosen for this cvterm-based entity.
       // ASSUMPTION: the cv_id is saved as the "type_value" of the bundle.
       $bundle = tripal_load_bundle_entity(array('name' => $widget['#bundle']));
-      $cv = tripal_get_cv(array('cv_id' => $bundle->type_value));
+      $cv = chado_get_cv(array('cv_id' => $bundle->type_value));
 
       // Now populate the items array with defaults based on the cv.
       if ($cv) {

+ 2 - 2
tripal_chado/includes/TripalFields/so__cds/so__cds.inc

@@ -81,7 +81,7 @@ class so__cds extends ChadoField {
 
     foreach($featurelocs as $featureloc){
       // Generate a CDS sequence if one exsits for this feature alignment.
-      $cds_sequence = tripal_get_feature_sequences(
+      $cds_sequence = chado_get_feature_sequences(
         array(
           'feature_id' => $feature->feature_id,
           'parent_id' => $featureloc->srcfeature_id->feature_id,
@@ -101,7 +101,7 @@ class so__cds extends ChadoField {
       );
 
       if (count($cds_sequence) > 0) {
-        // the tripal_get_feature_sequences() function can return multiple sequences
+        // the chado_get_feature_sequences() function can return multiple sequences
         // if a feature is aligned to multiple places. In the case of CDSs we expect
         // that one mRNA is only aligned to a single location on the assembly so we
         // can access the CDS sequence with index 0.

+ 8 - 8
tripal_chado/includes/TripalFields/taxrank__infraspecific_taxon/taxrank__infraspecific_taxon.inc

@@ -61,8 +61,8 @@ class taxrank__infraspecific_taxon extends ChadoField {
     $field_term = $this->getFieldTermID();
 
     $label_term = 'rdfs:label';
-    $infraspecific_name_term = tripal_get_chado_semweb_term('organism', 'infraspecific_name');
-    $infraspecific_type_term = tripal_get_chado_semweb_term('organism', 'type_id');
+    $infraspecific_name_term = chado_get_semweb_term('organism', 'infraspecific_name');
+    $infraspecific_type_term = chado_get_semweb_term('organism', 'type_id');
 
     return array(
       $field_term => array(
@@ -115,8 +115,8 @@ class taxrank__infraspecific_taxon extends ChadoField {
 
     $field_term_id = $this->getFieldTermID();
     $label_term = $field_term_id . ',' . 'rdfs:label';
-    $infraspecific_name_term = $field_term_id . ',' . tripal_get_chado_semweb_term('organism', 'infraspecific_name');
-    $infraspecific_type_term = $field_term_id . ',' . tripal_get_chado_semweb_term('organism', 'type_id');
+    $infraspecific_name_term = $field_term_id . ',' . chado_get_semweb_term('organism', 'infraspecific_name');
+    $infraspecific_type_term = $field_term_id . ',' . chado_get_semweb_term('organism', 'type_id');
 
     if ($condition['column'] == $label_term or $condition['column'] == $field_term_id) {
       $this->queryJoinOnce($query, 'cvterm', $alias . '_cvterm', $alias . "_cvterm.cvterm_id = base.type_id");
@@ -138,8 +138,8 @@ class taxrank__infraspecific_taxon extends ChadoField {
 
     $field_term_id = $this->getFieldTermID();
     $label_term = $field_term_id . ',' . 'rdfs:label';
-    $infraspecific_name_term = $field_term_id . ',' . tripal_get_chado_semweb_term('organism', 'infraspecific_name');
-    $infraspecific_type_term = $field_term_id . ',' . tripal_get_chado_semweb_term('organism', 'type_id');
+    $infraspecific_name_term = $field_term_id . ',' . chado_get_semweb_term('organism', 'infraspecific_name');
+    $infraspecific_type_term = $field_term_id . ',' . chado_get_semweb_term('organism', 'type_id');
 
     if ($order['column'] == $infraspecific_name_term) {
       $query->orderBy('base.infraspecific_name', $order['direction']);
@@ -170,8 +170,8 @@ class taxrank__infraspecific_taxon extends ChadoField {
     }
 
     $label_term = 'rdfs:label';
-    $infraspecific_name_term = tripal_get_chado_semweb_term('organism', 'infraspecific_name');
-    $infraspecific_type_term = tripal_get_chado_semweb_term('organism', 'type_id');
+    $infraspecific_name_term = chado_get_semweb_term('organism', 'infraspecific_name');
+    $infraspecific_type_term = chado_get_semweb_term('organism', 'type_id');
 
     // Set some defaults for the empty record.
     $entity->{$field_name}['und'][0] = array(

+ 2 - 2
tripal_chado/includes/TripalFields/taxrank__infraspecific_taxon/taxrank__infraspecific_taxon_formatter.inc

@@ -14,8 +14,8 @@ class taxrank__infraspecific_taxon_formatter extends ChadoFieldFormatter {
   public function view(&$element, $entity_type, $entity, $langcode, $items, $display) {
 
     $label_term = 'rdfs:label';
-    $infraspecific_name_term = tripal_get_chado_semweb_term('organism', 'infraspecific_name');
-    $infraspecific_type_term = tripal_get_chado_semweb_term('organism', 'type_id');
+    $infraspecific_name_term = chado_get_semweb_term('organism', 'infraspecific_name');
+    $infraspecific_type_term = chado_get_semweb_term('organism', 'type_id');
 
     if (is_array($items[0]['value']) and array_key_exists($infraspecific_name_term, $items[0]['value'])) {
       $infraspecific_name = $items[0]['value'][$infraspecific_name_term];

+ 2 - 2
tripal_chado/includes/TripalFields/taxrank__infraspecific_taxon/taxrank__infraspecific_taxon_widget.inc

@@ -48,8 +48,8 @@ class taxrank__infraspecific_taxon_widget extends ChadoFieldWidget {
       '#value' =>  $infra_name,
     );
 
-    $cv = tripal_get_cv(array('name' => 'taxonomic_rank'));
-    $terms = tripal_get_cvterm_select_options($cv->cv_id);
+    $cv = chado_get_cv(array('name' => 'taxonomic_rank'));
+    $terms = chado_get_cvterm_select_options($cv->cv_id);
 
     // Unfortunately the taxonomic_rank vocabulary is not properly organized
     // such that we only include terms below 'species'. Therefore we will

+ 2 - 2
tripal_chado/includes/TripalFields/uo__unit/uo__unit_widget.inc

@@ -31,8 +31,8 @@ class uo__unit_widget extends ChadoFieldWidget {
       '#type' => 'value',
       '#value' => array_key_exists($delta, $items) ? $items[$delta]['value'] : '',
     );
-    $cv = tripal_get_cv(array('name' => 'featuremap_units'));
-    $options = tripal_get_cvterm_select_options($cv->cv_id);
+    $cv = chado_get_cv(array('name' => 'featuremap_units'));
+    $options = chado_get_cvterm_select_options($cv->cv_id);
     unset($options[0]);
     $widget['chado-' . $field_table . '__unittype_id'] = array(
       '#type' => 'select',

+ 5 - 5
tripal_chado/includes/TripalImporter/GFF3Importer.inc

@@ -907,7 +907,7 @@ class GFF3Importer extends TripalImporter {
             TGPT.feature_id, TGPT.fmin, TGPT.fmax, TGCT.strand, FLM.uniquename
         ";
         $results = chado_query($sql);
-        $protein_cvterm = tripal_get_cvterm(array(
+        $protein_cvterm = chado_get_cvterm(array(
           'name' => 'polypeptide',
           'cv_id' => array(
             'name' => 'sequence'
@@ -952,7 +952,7 @@ class GFF3Importer extends TripalImporter {
             $feature = $this->loadFeature($organism, $analysis_id,
                 $protein_cvterm, $uname, $name, '', 'f', 'f', 1, 0);
             // Add the derives_from relationship.
-            $cvterm = tripal_get_cvterm(array('cvterm_id' => $result->cvterm_id));
+            $cvterm = chado_get_cvterm(array('cvterm_id' => $result->cvterm_id));
             $this->loadDerivesFrom($feature, $cvterm,
                 $result->uniquename, $organism, $pfmin, $pfmax);
             // Add the featureloc record. Set the start of the protein to
@@ -1060,7 +1060,7 @@ class GFF3Importer extends TripalImporter {
     $result = chado_select_record('tripal_gff_temp', array('type_name'), $values);
     $type_id = NULL;
     if (count($result) > 0) {
-      $otype = tripal_get_cvterm(array(
+      $otype = chado_get_cvterm(array(
         'name' => $result[0]->type_name,
         'cv_id' => array(
           'name' => 'sequence'
@@ -1477,7 +1477,7 @@ class GFF3Importer extends TripalImporter {
         'cv_name' => $syncv->name,
         'is_relationship' => FALSE
       );
-      $syntype = tripal_insert_cvterm($term, array('update_existing' => TRUE));
+      $syntype = chado_insert_cvterm($term, array('update_existing' => TRUE));
       if (!$syntype) {
         $this->logMessage("Cannot add synonym type: internal:$type.", array(), TRIPAL_WARNING);
         return 0;
@@ -1917,7 +1917,7 @@ class GFF3Importer extends TripalImporter {
         'cv_name' => 'feature_property',
         'is_relationship' => FALSE
       );
-      $cvterm = (object) tripal_insert_cvterm($term, array('update_existing' => FALSE));
+      $cvterm = (object)chado_insert_cvterm($term, array('update_existing' => FALSE));
       if (!$cvterm) {
         $this->logMessage("Cannot add cvterm, $property.", array(), TRIPAL_WARNING);
         return 0;

Some files were not shown because too many files changed in this diff