Selaa lähdekoodia

Updated 6.x-1482618-API_for_default_views_integration branch to current 6.x-0.4-dev

Lacey Sanderson 12 vuotta sitten
vanhempi
commit
18d7fa4d75
98 muutettua tiedostoa jossa 9323 lisäystä ja 18248 poistoa
  1. 0 339
      LICENSE.txt
  2. 69 2
      README.txt
  3. 0 177
      extensions/tripal_gbrowse/node-tripal_gbrowse.tpl.php
  4. 0 148
      extensions/tripal_gbrowse/template.conf
  5. 0 48
      extensions/tripal_gbrowse/theme/tripal_gbrowse/tripal_gbrowse_database_details.tpl.php
  6. 0 45
      extensions/tripal_gbrowse/theme/tripal_gbrowse/tripal_gbrowse_details.tpl.php
  7. 0 28
      extensions/tripal_gbrowse/theme/tripal_gbrowse/tripal_gbrowse_gbrowse_instance.tpl.php
  8. 0 42
      extensions/tripal_gbrowse/theme/tripal_gbrowse/tripal_gbrowse_loaded_sources.tpl.php
  9. 0 34
      extensions/tripal_gbrowse/theme/tripal_gbrowse/tripal_gbrowse_teaser.tpl.php
  10. 0 647
      extensions/tripal_gbrowse/tripal_gbrowse.align_features.inc
  11. 0 5
      extensions/tripal_gbrowse/tripal_gbrowse.info
  12. 0 119
      extensions/tripal_gbrowse/tripal_gbrowse.install
  13. 0 2994
      extensions/tripal_gbrowse/tripal_gbrowse.module
  14. 0 606
      extensions/tripal_gbrowse/tripal_gbrowse.views.inc
  15. 47 7
      tripal_analysis/tripal_analysis.admin.inc
  16. 111 110
      tripal_analysis/tripal_analysis.api.inc
  17. 70 65
      tripal_analysis/tripal_analysis.install
  18. 130 105
      tripal_analysis/tripal_analysis.module
  19. 7 7
      tripal_analysis/tripal_analysis.views.inc
  20. 0 567
      tripal_analysis/tripal_analysis.views.inc.orig
  21. 13 4
      tripal_analysis/tripal_analysis_privacy.inc
  22. 165 2131
      tripal_bulk_loader/tripal_bulk_loader.admin.inc
  23. 2149 2426
      tripal_bulk_loader/tripal_bulk_loader.admin.templates.inc
  24. 11 0
      tripal_bulk_loader/tripal_bulk_loader.coder_ignores.txt
  25. 9 8
      tripal_bulk_loader/tripal_bulk_loader.constants.inc
  26. 2 2
      tripal_bulk_loader/tripal_bulk_loader.install
  27. 163 33
      tripal_bulk_loader/tripal_bulk_loader.loader.inc
  28. 0 733
      tripal_bulk_loader/tripal_bulk_loader.loader.inc.orig
  29. 132 139
      tripal_bulk_loader/tripal_bulk_loader.module
  30. 0 647
      tripal_bulk_loader/tripal_bulk_loader.module.orig
  31. 2 2
      tripal_contact/tripal_contact.api.inc
  32. 9 9
      tripal_contact/tripal_contact.module
  33. 12 12
      tripal_contact/tripal_contact.views.inc
  34. 159 65
      tripal_core/tripal_core.api.inc
  35. 9 12
      tripal_core/tripal_core.coder_ignores.txt
  36. 2 0
      tripal_core/tripal_core.schema.api.inc
  37. 1 5
      tripal_cv/tripal_cv.coder_ignores.txt
  38. 3 2
      tripal_cv/tripal_cv.module
  39. 1 1
      tripal_cv/tripal_cv.views.inc
  40. 73 74
      tripal_db/tripal_db.api.inc
  41. 21 21
      tripal_db/tripal_db.install
  42. 238 239
      tripal_db/tripal_db.module
  43. 2 2
      tripal_db/tripal_db.views.inc
  44. 665 644
      tripal_feature/fasta_loader.php
  45. 617 605
      tripal_feature/gff_loader.php
  46. 146 139
      tripal_feature/indexFeatures.php
  47. 379 370
      tripal_feature/syncFeatures.php
  48. 116 116
      tripal_feature/tripal_feature-db_references.inc
  49. 142 143
      tripal_feature/tripal_feature-delete.inc
  50. 79 79
      tripal_feature/tripal_feature-properties.inc
  51. 110 112
      tripal_feature/tripal_feature-relationships.inc
  52. 461 462
      tripal_feature/tripal_feature.admin.inc
  53. 99 99
      tripal_feature/tripal_feature.api.inc
  54. 21 0
      tripal_feature/tripal_feature.coder_ignores.txt
  55. 146 146
      tripal_feature/tripal_feature.install
  56. 436 437
      tripal_feature/tripal_feature.module
  57. 12 12
      tripal_feature/tripal_feature.views.inc
  58. 1 1
      tripal_feature/views_handlers/views_handler_field_residues.inc
  59. 2 2
      tripal_genetic/tripal_genetic.module
  60. 7 7
      tripal_genetic/tripal_genetic.views.inc
  61. 12 7
      tripal_library/reindex.php
  62. 11 7
      tripal_library/taxonify.php
  63. 4 4
      tripal_library/tripal_library.api.inc
  64. 101 101
      tripal_library/tripal_library.install
  65. 531 531
      tripal_library/tripal_library.module
  66. 7 7
      tripal_library/tripal_library.views.inc
  67. 2 2
      tripal_natural_diversity/tripal_natural_diversity.module
  68. 8 8
      tripal_natural_diversity/tripal_natural_diversity.views.inc
  69. 18 18
      tripal_organism/tripal_organism.api.inc
  70. 61 61
      tripal_organism/tripal_organism.install
  71. 442 441
      tripal_organism/tripal_organism.module
  72. 14 14
      tripal_organism/tripal_organism.views.inc
  73. 2 2
      tripal_phenotype/tripal_phenotype.module
  74. 13 13
      tripal_phenotype/tripal_phenotype.views.inc
  75. 3 3
      tripal_project/tripal_project.admin.inc
  76. 3 3
      tripal_project/tripal_project.install
  77. 63 63
      tripal_project/tripal_project.module
  78. 7 7
      tripal_project/tripal_project.views.inc
  79. 5 6
      tripal_pub/tripal_pub.install
  80. 483 491
      tripal_pub/tripal_pub.module
  81. 13 13
      tripal_pub/tripal_pub.views.inc
  82. 8 0
      tripal_search/tripal_search.coder_ignores.txt
  83. 28 15
      tripal_search/tripal_search.module
  84. 3 3
      tripal_stock/other_module_api_functions.inc
  85. 147 147
      tripal_stock/tripal_stock-administration.inc
  86. 25 25
      tripal_stock/tripal_stock-db_references.inc
  87. 20 20
      tripal_stock/tripal_stock-properties.inc
  88. 29 29
      tripal_stock/tripal_stock-relationships.inc
  89. 10 3
      tripal_stock/tripal_stock.install
  90. 92 92
      tripal_stock/tripal_stock.module
  91. 46 46
      tripal_stock/tripal_stock.views.inc
  92. 9 16
      tripal_views/tripal_views.coder_ignores.txt
  93. 7 0
      tripal_views/tripal_views.views.inc
  94. 6 6
      tripal_views/tripal_views_integration.inc
  95. 4 3
      tripal_views/views/chado_linking.TMP.inc
  96. 1 0
      tripal_views/views/handlers/views_handler_field_dbxref_accession_link.inc
  97. 1 0
      tripal_views/views/handlers/views_handler_filter_chado_select_cvterm_name.inc
  98. 35 5
      tripal_views/views/handlers/views_handler_filter_chado_select_string.inc

+ 0 - 339
LICENSE.txt

@@ -1,339 +0,0 @@
-                    GNU GENERAL PUBLIC LICENSE
-                       Version 2, June 1991
-
- Copyright (C) 1989, 1991 Free Software Foundation, Inc.,
- 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
- Everyone is permitted to copy and distribute verbatim copies
- of this license document, but changing it is not allowed.
-
-                            Preamble
-
-  The licenses for most software are designed to take away your
-freedom to share and change it.  By contrast, the GNU General Public
-License is intended to guarantee your freedom to share and change free
-software--to make sure the software is free for all its users.  This
-General Public License applies to most of the Free Software
-Foundation's software and to any other program whose authors commit to
-using it.  (Some other Free Software Foundation software is covered by
-the GNU Lesser General Public License instead.)  You can apply it to
-your programs, too.
-
-  When we speak of free software, we are referring to freedom, not
-price.  Our General Public Licenses are designed to make sure that you
-have the freedom to distribute copies of free software (and charge for
-this service if you wish), that you receive source code or can get it
-if you want it, that you can change the software or use pieces of it
-in new free programs; and that you know you can do these things.
-
-  To protect your rights, we need to make restrictions that forbid
-anyone to deny you these rights or to ask you to surrender the rights.
-These restrictions translate to certain responsibilities for you if you
-distribute copies of the software, or if you modify it.
-
-  For example, if you distribute copies of such a program, whether
-gratis or for a fee, you must give the recipients all the rights that
-you have.  You must make sure that they, too, receive or can get the
-source code.  And you must show them these terms so they know their
-rights.
-
-  We protect your rights with two steps: (1) copyright the software, and
-(2) offer you this license which gives you legal permission to copy,
-distribute and/or modify the software.
-
-  Also, for each author's protection and ours, we want to make certain
-that everyone understands that there is no warranty for this free
-software.  If the software is modified by someone else and passed on, we
-want its recipients to know that what they have is not the original, so
-that any problems introduced by others will not reflect on the original
-authors' reputations.
-
-  Finally, any free program is threatened constantly by software
-patents.  We wish to avoid the danger that redistributors of a free
-program will individually obtain patent licenses, in effect making the
-program proprietary.  To prevent this, we have made it clear that any
-patent must be licensed for everyone's free use or not licensed at all.
-
-  The precise terms and conditions for copying, distribution and
-modification follow.
-
-                    GNU GENERAL PUBLIC LICENSE
-   TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
-
-  0. This License applies to any program or other work which contains
-a notice placed by the copyright holder saying it may be distributed
-under the terms of this General Public License.  The "Program", below,
-refers to any such program or work, and a "work based on the Program"
-means either the Program or any derivative work under copyright law:
-that is to say, a work containing the Program or a portion of it,
-either verbatim or with modifications and/or translated into another
-language.  (Hereinafter, translation is included without limitation in
-the term "modification".)  Each licensee is addressed as "you".
-
-Activities other than copying, distribution and modification are not
-covered by this License; they are outside its scope.  The act of
-running the Program is not restricted, and the output from the Program
-is covered only if its contents constitute a work based on the
-Program (independent of having been made by running the Program).
-Whether that is true depends on what the Program does.
-
-  1. You may copy and distribute verbatim copies of the Program's
-source code as you receive it, in any medium, provided that you
-conspicuously and appropriately publish on each copy an appropriate
-copyright notice and disclaimer of warranty; keep intact all the
-notices that refer to this License and to the absence of any warranty;
-and give any other recipients of the Program a copy of this License
-along with the Program.
-
-You may charge a fee for the physical act of transferring a copy, and
-you may at your option offer warranty protection in exchange for a fee.
-
-  2. You may modify your copy or copies of the Program or any portion
-of it, thus forming a work based on the Program, and copy and
-distribute such modifications or work under the terms of Section 1
-above, provided that you also meet all of these conditions:
-
-    a) You must cause the modified files to carry prominent notices
-    stating that you changed the files and the date of any change.
-
-    b) You must cause any work that you distribute or publish, that in
-    whole or in part contains or is derived from the Program or any
-    part thereof, to be licensed as a whole at no charge to all third
-    parties under the terms of this License.
-
-    c) If the modified program normally reads commands interactively
-    when run, you must cause it, when started running for such
-    interactive use in the most ordinary way, to print or display an
-    announcement including an appropriate copyright notice and a
-    notice that there is no warranty (or else, saying that you provide
-    a warranty) and that users may redistribute the program under
-    these conditions, and telling the user how to view a copy of this
-    License.  (Exception: if the Program itself is interactive but
-    does not normally print such an announcement, your work based on
-    the Program is not required to print an announcement.)
-
-These requirements apply to the modified work as a whole.  If
-identifiable sections of that work are not derived from the Program,
-and can be reasonably considered independent and separate works in
-themselves, then this License, and its terms, do not apply to those
-sections when you distribute them as separate works.  But when you
-distribute the same sections as part of a whole which is a work based
-on the Program, the distribution of the whole must be on the terms of
-this License, whose permissions for other licensees extend to the
-entire whole, and thus to each and every part regardless of who wrote it.
-
-Thus, it is not the intent of this section to claim rights or contest
-your rights to work written entirely by you; rather, the intent is to
-exercise the right to control the distribution of derivative or
-collective works based on the Program.
-
-In addition, mere aggregation of another work not based on the Program
-with the Program (or with a work based on the Program) on a volume of
-a storage or distribution medium does not bring the other work under
-the scope of this License.
-
-  3. You may copy and distribute the Program (or a work based on it,
-under Section 2) in object code or executable form under the terms of
-Sections 1 and 2 above provided that you also do one of the following:
-
-    a) Accompany it with the complete corresponding machine-readable
-    source code, which must be distributed under the terms of Sections
-    1 and 2 above on a medium customarily used for software interchange; or,
-
-    b) Accompany it with a written offer, valid for at least three
-    years, to give any third party, for a charge no more than your
-    cost of physically performing source distribution, a complete
-    machine-readable copy of the corresponding source code, to be
-    distributed under the terms of Sections 1 and 2 above on a medium
-    customarily used for software interchange; or,
-
-    c) Accompany it with the information you received as to the offer
-    to distribute corresponding source code.  (This alternative is
-    allowed only for noncommercial distribution and only if you
-    received the program in object code or executable form with such
-    an offer, in accord with Subsection b above.)
-
-The source code for a work means the preferred form of the work for
-making modifications to it.  For an executable work, complete source
-code means all the source code for all modules it contains, plus any
-associated interface definition files, plus the scripts used to
-control compilation and installation of the executable.  However, as a
-special exception, the source code distributed need not include
-anything that is normally distributed (in either source or binary
-form) with the major components (compiler, kernel, and so on) of the
-operating system on which the executable runs, unless that component
-itself accompanies the executable.
-
-If distribution of executable or object code is made by offering
-access to copy from a designated place, then offering equivalent
-access to copy the source code from the same place counts as
-distribution of the source code, even though third parties are not
-compelled to copy the source along with the object code.
-
-  4. You may not copy, modify, sublicense, or distribute the Program
-except as expressly provided under this License.  Any attempt
-otherwise to copy, modify, sublicense or distribute the Program is
-void, and will automatically terminate your rights under this License.
-However, parties who have received copies, or rights, from you under
-this License will not have their licenses terminated so long as such
-parties remain in full compliance.
-
-  5. You are not required to accept this License, since you have not
-signed it.  However, nothing else grants you permission to modify or
-distribute the Program or its derivative works.  These actions are
-prohibited by law if you do not accept this License.  Therefore, by
-modifying or distributing the Program (or any work based on the
-Program), you indicate your acceptance of this License to do so, and
-all its terms and conditions for copying, distributing or modifying
-the Program or works based on it.
-
-  6. Each time you redistribute the Program (or any work based on the
-Program), the recipient automatically receives a license from the
-original licensor to copy, distribute or modify the Program subject to
-these terms and conditions.  You may not impose any further
-restrictions on the recipients' exercise of the rights granted herein.
-You are not responsible for enforcing compliance by third parties to
-this License.
-
-  7. If, as a consequence of a court judgment or allegation of patent
-infringement or for any other reason (not limited to patent issues),
-conditions are imposed on you (whether by court order, agreement or
-otherwise) that contradict the conditions of this License, they do not
-excuse you from the conditions of this License.  If you cannot
-distribute so as to satisfy simultaneously your obligations under this
-License and any other pertinent obligations, then as a consequence you
-may not distribute the Program at all.  For example, if a patent
-license would not permit royalty-free redistribution of the Program by
-all those who receive copies directly or indirectly through you, then
-the only way you could satisfy both it and this License would be to
-refrain entirely from distribution of the Program.
-
-If any portion of this section is held invalid or unenforceable under
-any particular circumstance, the balance of the section is intended to
-apply and the section as a whole is intended to apply in other
-circumstances.
-
-It is not the purpose of this section to induce you to infringe any
-patents or other property right claims or to contest validity of any
-such claims; this section has the sole purpose of protecting the
-integrity of the free software distribution system, which is
-implemented by public license practices.  Many people have made
-generous contributions to the wide range of software distributed
-through that system in reliance on consistent application of that
-system; it is up to the author/donor to decide if he or she is willing
-to distribute software through any other system and a licensee cannot
-impose that choice.
-
-This section is intended to make thoroughly clear what is believed to
-be a consequence of the rest of this License.
-
-  8. If the distribution and/or use of the Program is restricted in
-certain countries either by patents or by copyrighted interfaces, the
-original copyright holder who places the Program under this License
-may add an explicit geographical distribution limitation excluding
-those countries, so that distribution is permitted only in or among
-countries not thus excluded.  In such case, this License incorporates
-the limitation as if written in the body of this License.
-
-  9. The Free Software Foundation may publish revised and/or new versions
-of the General Public License from time to time.  Such new versions will
-be similar in spirit to the present version, but may differ in detail to
-address new problems or concerns.
-
-Each version is given a distinguishing version number.  If the Program
-specifies a version number of this License which applies to it and "any
-later version", you have the option of following the terms and conditions
-either of that version or of any later version published by the Free
-Software Foundation.  If the Program does not specify a version number of
-this License, you may choose any version ever published by the Free Software
-Foundation.
-
-  10. If you wish to incorporate parts of the Program into other free
-programs whose distribution conditions are different, write to the author
-to ask for permission.  For software which is copyrighted by the Free
-Software Foundation, write to the Free Software Foundation; we sometimes
-make exceptions for this.  Our decision will be guided by the two goals
-of preserving the free status of all derivatives of our free software and
-of promoting the sharing and reuse of software generally.
-
-                            NO WARRANTY
-
-  11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY
-FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW.  EXCEPT WHEN
-OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES
-PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED
-OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
-MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.  THE ENTIRE RISK AS
-TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU.  SHOULD THE
-PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING,
-REPAIR OR CORRECTION.
-
-  12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
-WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR
-REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES,
-INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING
-OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED
-TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY
-YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER
-PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE
-POSSIBILITY OF SUCH DAMAGES.
-
-                     END OF TERMS AND CONDITIONS
-
-            How to Apply These Terms to Your New Programs
-
-  If you develop a new program, and you want it to be of the greatest
-possible use to the public, the best way to achieve this is to make it
-free software which everyone can redistribute and change under these terms.
-
-  To do so, attach the following notices to the program.  It is safest
-to attach them to the start of each source file to most effectively
-convey the exclusion of warranty; and each file should have at least
-the "copyright" line and a pointer to where the full notice is found.
-
-    <one line to give the program's name and a brief idea of what it does.>
-    Copyright (C) <year>  <name of author>
-
-    This program is free software; you can redistribute it and/or modify
-    it under the terms of the GNU General Public License as published by
-    the Free Software Foundation; either version 2 of the License, or
-    (at your option) any later version.
-
-    This program is distributed in the hope that it will be useful,
-    but WITHOUT ANY WARRANTY; without even the implied warranty of
-    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
-    GNU General Public License for more details.
-
-    You should have received a copy of the GNU General Public License along
-    with this program; if not, write to the Free Software Foundation, Inc.,
-    51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
-
-Also add information on how to contact you by electronic and paper mail.
-
-If the program is interactive, make it output a short notice like this
-when it starts in an interactive mode:
-
-    Gnomovision version 69, Copyright (C) year name of author
-    Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
-    This is free software, and you are welcome to redistribute it
-    under certain conditions; type `show c' for details.
-
-The hypothetical commands `show w' and `show c' should show the appropriate
-parts of the General Public License.  Of course, the commands you use may
-be called something other than `show w' and `show c'; they could even be
-mouse-clicks or menu items--whatever suits your program.
-
-You should also get your employer (if you work as a programmer) or your
-school, if any, to sign a "copyright disclaimer" for the program, if
-necessary.  Here is a sample; alter the names:
-
-  Yoyodyne, Inc., hereby disclaims all copyright interest in the program
-  `Gnomovision' (which makes passes at compilers) written by James Hacker.
-
-  <signature of Ty Coon>, 1 April 1989
-  Ty Coon, President of Vice
-
-This General Public License does not permit incorporating your program into
-proprietary programs.  If your program is a subroutine library, you may
-consider it more useful to permit linking proprietary applications with the
-library.  If this is what you want to do, use the GNU Lesser General
-Public License instead of this License.

+ 69 - 2
README.txt

@@ -1,3 +1,70 @@
-This branch is tested to work with drupal core version 6.22.
-Mileage will vary with 6.x .
+What is Tripal?
+Tripal is a collection of open-source freely available Drupal modules 
+and is a member of the GMOD family of tools. Tripal serves as a web 
+interface for the GMOD Chado database and is designed to allow anyone 
+with genomic data to quickly create an online genomic database using 
+community supported tools.
 
+Features
+ - a Chado installer
+ - Data loaders for ontologies (controlled vocabularies), GFF files, 
+   and FASTA files
+ - Generic Data Loader Modules allows for creation of custom loading 
+   templates
+ - Drupal nodes (web pages) are automatically generated for organisms,
+   genomic features, biological libraries, and stocks
+ - Web pages can be enriched with analysis results from BLAST, 
+   KAAS/KEGG, InterProScan, and Gene Ontology (GO)
+ - Views Integration allows for custom listings of data
+ - Content pieces exposed as blocks allowing the use of Panels for 
+   custom layouts of Tripal Nodes
+
+Required Modules
+ - Drupal 6.x (work is currently underway for a 7.x compatible 
+   version)
+ - Drupal Core Modules: Search and Path
+ - Database containing GMOD Chado Schema (can be installed by the 
+   Tripal Core module)
+NOTE: A PostgreSQL database is required for installation of the 
+Chado Schema
+
+Highly Recommended Modules
+ - Views 2.x (Views 3.x compatible version already exists in 6.x-0.4-dev)
+ - Views Data Export
+
+Installation
+1. Enable/Install the Tripal Core Module
+2. Install a Chado database
+     - Either allow Tripal to add a chado database in a separate 
+       schema to your Drupal database (recommended) by navigating to 
+       Administer -> Tripal Management -> Install Chado 
+       (admin/tripal/chado_1_11_install) and click "Install Chado" OR
+     - Edit the settings.php file to connect to an external chado 
+       database
+3. Enable/Install any other Tripal modules that are applicable to 
+   your site.
+4. Check the module page for each enabled Tripal module for further 
+   module-specific instructions and a list of features and quick 
+   links (Administer -> Tripal Managment -> [Module Name]
+
+Customization
+Tripal can be used “as is” but also allows for complete customization.
+PHP-based template files are provided for all data types to allow for 
+precise customizations as required by the community. A well-developed 
+Tripal API provides a uniform set of variables and functions for 
+accessing any and all data within the Chado database.
+
+Future Work
+Currently, Tripal only supports visualization of a subset of the 
+current Chado schema, but further development is underway. Meanwhile, 
+others can use the Tripal API to develop their own extensions. Those 
+extensions can in turn be made available for anyone to use. These 
+custom extensions, the Tripal package, and access to support resource 
+such as an active mailing list can be found on the Tripal website 
+(http://tripal.sourceforge.net).
+
+For more information, see the recent publication:
+Stephen P. Ficklin, Lacey-Anne Sanderson, Chun-Huai Cheng, Margaret 
+Staton, Taein Lee, Il-Hyung Cho, Sook Jung, Kirstin E Bett, Dorrie 
+Main. Tripal: a construction Toolkit for Online Genome Databases. 
+Database, Sept 2011. Vol 2011.

+ 0 - 177
extensions/tripal_gbrowse/node-tripal_gbrowse.tpl.php

@@ -1,177 +0,0 @@
-<?php
-// Developed by: Chad N.A Krilow at The University of Saskatchewan
-//
-// Purpose: This template provides the layout of the Tripal GBrowse Instances node (page)
-//   using the same templates used for the various Tripal GBrowse blocks. An I-Frame is 
-//	 included to show the representation of the GBrowse instance(including tracks). Along with 
-//	 the I-Frame, a link to open a external I-Frame in a new window is supplied
-//
-// To Customize the Stock Node Page:
-//   - This Template: customize basic layout and which elements are included
-//   - Using Panels: Override the node page using Panels3 and place the blocks
-//       of content as you please. This method requires no programming. See
-//       the Tripal User Guide for more details
-//
-// Variables Available:
-//   - $node: a standard object which contains all the fields associated with
-//       nodes and it also includes Tripal GBrowse specific fields.
-//
-//   NOTE: For a full listing of fields available in the node object the
-//       print_r $node line below or install the Drupal Devel module which 
-//       provides an extra tab at the top of the node page labelled Devel
-?>
-
-
-<?php
- //uncomment this line to see a full listing of the fields avail. to $node
- //print '<pre>'.print_r($node,TRUE).'</pre>';
- drupal_add_css('./tripal-node-templates.css');
-?>
-
-<?php if ($teaser) { 
-  
-  include('tripal_gbrowse/tripal_gbrowse_teaser.tpl.php');
-} else { ?>
-	  
-<script type="text/javascript">
- if (Drupal.jsEnabled) {
-   $(document).ready(function() {
-      // hide all tripal info boxes at the start
-      $(".tripal-info-box").hide();
- 
-      // iterate through all of the info boxes and add their titles
-      // to the table of contents
-      $(".tripal-info-box-title").each(function(){
-        var parent = $(this).parent();
-        var id = $(parent).attr('id');
-        var title = $(this).text();
-        $('#tripal_gbrowse_toc_list').append('<li><a href="#'+id+'" class="tripal_gbrowse_toc_item">'+title+'</a></li>');
-      });
-
-      // when a title in the table of contents is clicked, then
-      // show corresponding item in details box
-      $(".tripal_gbrowse_toc_item").click(function(){
-         $(".tripal-info-box").hide();
-         href = $(this).attr('href');
-         $(href).fadeIn('slow');
-         // make sure table of contents and the details
-         // box stay the same height
-         $("#tripal_gbrowse_toc").height($(href).parent().height());
-         return false;
-      }); 
-
-      // base details show up when the page is first shown 
-      // unless the user specified a specific block
-      var block = window.location.href.match(/\?block=.*/);
-      if(block != null){
-         block_title = block.toString().replace(/\?block=/g,'');
-         $("#tripal_gbrowse-"+block_title+"-box").show();
-      } else {
-         $("#tripal_gbrowse-base-box").show();
-      }
-
-      $("#tripal_gbrowse_toc").height($("#tripal_gbrowse-base-box").parent().height());
-   });
-}
-</script>
-
-<style type="text/css">
-  /* these styles are specific for this template and is not included 
-     in the main CSS files for the theme as it is anticipated that the
-     elements on this page may not be used for other customizations */
-  #tripal_gbrowse_toc {
-     float: left;
-     width: 20%;
-     background-color: #EEEEEE;
-     -moz-border-radius: 15px;
-     border-radius: 15px;
-     -moz-box-shadow: 3px 3px 4px #888888;
-	  -webkit-box-shadow: 3px 3px 4px #888888;
-	  box-shadow: 3px 3px 4px #888888;
-     padding: 20px;
-     min-height: 200px;
-     border-style:solid;
-     border-width:1px;
-  }
-  #tripal_gbrowse_toc ul {
-    margin-left: 0px;
-    margin-top: 5px;
-    padding-left: 15px;
-  }
-  #tripal_gbrowse_toc_title {
-     font-size: 1.5em;
-  }
-  #tripal_gbrowse_toc_desc {
-    font-style: italic;
-  }
-  #tripal_gbrowse_details {
-     float: left;
-     width: 70%;
-     background-color: #FFFFFF;
-     -moz-border-radius: 15px;
-     border-radius: 15px;
-     -moz-box-shadow: 3px 3px 4px #888888;
-	  -webkit-box-shadow: 3px 3px 4px #888888;
-	  box-shadow: 3px 3px 4px #888888;
-     padding: 20px;
-     min-height: 200px;
-     margin-right: 10px;
-     border-style:solid;
-     border-width:1px;
-  }
-  #tripal_gbrowse-base-box img {
-    float: left;
-    margin-bottom: 10px;
-  }
-  #tripal_gbrowse-table-base {
-    float: left;
-    width: 400px;
-    margin-left: 10px;
-    margin-bottom: 10px;
-  }
-  #tripal_gbrowse_addtional_content {
-		clear:both;
-  	width: 100%;
-  }
-</style>
-
-<div id ="tripal_gbrowse_content">
-<div id="tripal_gbrowse_details" class="tripal_details"><h2>
-
-   <!-- Basic Details Theme -->
-   <?php include('tripal_gbrowse/tripal_gbrowse_details.tpl.php'); ?>
-
-   <!-- GBrowse Details -->
-   <?php 
-   global $account;
-   if(user_access('access database-related details',$account)){
-     include('tripal_gbrowse/tripal_gbrowse_database_details.tpl.php'); 
-	 }?>
-   <?php print $content ?>
-   
-    <!-- GBrowse Loaded Sources -->
-   <?php 
-     include('tripal_gbrowse/tripal_gbrowse_loaded_sources.tpl.php');
-     ?>
-   <?php print $content ?>
- 
-</div>
-
-<!-- Table of contents -->
-<div id="tripal_gbrowse_toc" class="tripal_toc">
-   <div id="tripal_gbrowse_toc_title" class="tripal_toc_title">Resources</div>
-   <span id="tripal_gbrowse_toc_desc" class="tripal_toc_desc"></span>
-   <ul id="tripal_gbrowse_toc_list" class="tripal_toc_list">
-
-   </ul>
-</div>
-</div>
-
-<!--- I-Frame Code Section --->
-<div id="tripal_gbrowse_addtional_content">
-
-	<!--- Include for file that makes the I-Frame and external window possible --->
- <?php include('tripal_gbrowse/tripal_gbrowse_gbrowse_instance.tpl.php'); ?>
-
-</div>
-<?php } ?>

+ 0 - 148
extensions/tripal_gbrowse/template.conf

@@ -1,148 +0,0 @@
-[GENERAL]
-description   = <#gbrowse_name#>
-db_adaptor    = Bio::DB::SeqFeature::Store
-db_args       = -adaptor DBI::mysql
-	      	-dsn dbi:mysql:database=<#database_name#>;host=localhost
-		-user 'www-data'
-
-plugins = BatchDumper FastaDumper Submitter
-
-# Web site configuration info
-gbrowse root = gbrowse
-stylesheet   = gbrowse.css
-buttons      = images/buttons
-js           = js
-tmpimages    = tmp
-
-region segment = 100000
-
-# advanced features
-balloon tips    = 1
-balloon style = GBox
-drag and drop = 1
-
-# one hour
-cache time    = 0
-
-# where to link to when user clicks in detailed view
-link          = AUTO
-
-# what image widths to offer
-image widths  = 450 640 800 1024
-
-# default width of detailed view (pixels)
-default width = 640
-
-# max and default segment sizes for detailed view
-max segment     = 500000
-default segment = 50000
-
-# zoom levels
-zoom levels    = 50 100 200 1000 2000 5000 10000 20000 40000 100000 200000 500000 1000000
-
-# whether to show the sources popup menu (0=false, 1=true; defaults to true)
-show sources   = 1
-
-# colors of the overview, detailed map and key
-overview bgcolor = #EAF3D1
-detailed bgcolor = #EAF3D1
-key bgcolor      = lightgrey
-
-# color of the selection rectangle  
-hilite fill    = honeydew
-hilite outline = darkseagreen
-
-# examples to show in the introduction
-#examples = MtChr1:325500..329900 MtChr1:182000..199000 MtChr1:148000..193000 MtChr3:42058653..42059652
-
-# "automatic" classes to try when an unqualified identifier is given
-automatic classes = Symbol Gene Clone
-
-### HTML TO INSERT AT VARIOUS STRATEGIC LOCATIONS ###
-# inside the <head></head> section
-head = 
-
-# at the top...
-#header = <font color="white">Pulse Crop GBrowse</font>
-
-# a footer
-#footer = <hr>
-#	<table width="100%"><TR><TD align="LEFT">
-#	For the source code for this browser, see the <a href="http://www.gmod.org">Generic Model Organism Database Project.</a>  For other questions, send
-#	mail to <a href="mailto:lacey.sanderson@usask.ca">lacey.sanderson@usask.ca</a>.
-#	</TD></TR></table>
-#	<hr><pre>$Id: Medicago Assembly 3.5, Pulse GBrowse v 1.0 02/02/2011 laceysanderson Exp $</pre>
-
-# Various places where you can insert your own HTML -- see configuration docs
-html1 = 
-#html2 = <p align="center"><b>All features are displayed on the Medicago 3.5 chromosomes regardless of species of origin.</b></p>
-html3 = 
-html4 = 
-html5 = 
-html6 = 
-
-# Advanced feature: custom balloons
-custom balloons = [balloon]
-                  delayTime = 500
-
-		  [GBox]
-                  balloonImage  = Box.png
-                  stem          = 0
-                  vOffset       = 20
-                  hOffset       = 20
-                  padding       = 1
-                  shadow        = 0
-
-
-# Advanced feature: an example of a customized popup mentu for rubber band selection
-[OVERVIEW SELECT MENU]
-width = 100
-html  =  <table style="width:100%"> 
-         <tr><th style="background:lightgrey">Overview</span></th></tr>
-         <tr><td><span style="color:blue;cursor:pointer" onclick="SelectArea.prototype.clearAndSubmit()">Zoom</span></td></tr>
-         <tr><td><span style="color:blue;cursor:pointer" onclick="SelectArea.prototype.cancelRubber()">Cancel</span></td></tr>
-        </table>
-
-
-[DETAIL SELECT MENU]
-width = 250
-html  = <table style="width:100%">
-         <tr><th style="background:lightgrey;cell-padding:5">SELECTION
-             <span style="right:0px;position:absolute;color:blue;cursor:pointer" onclick="SelectArea.prototype.cancelRubber()"> [X] </span> </th></tr>
-         <tr><td><span style="color:blue;cursor:pointer" onclick="SelectArea.prototype.clearAndSubmit()">Zoom in</span></td></tr>
-         <tr><td><span style="color:blue;cursor:pointer" onclick="SelectArea.prototype.clearAndRecenter()">Recenter on this region</span></td></tr>
-         <tr><td onmouseup="SelectArea.prototype.cancelRubber()"><a href="?plugin=FastaDumper;plugin_action=Go;name=SELECTION" target="_BLANK">
-               Dump selection as FASTA</a></td></tr>
-         <tr><td onmouseup="SelectArea.prototype.cancelRubber()"><a href="?name=SELECTION;plugin=Submitter;plugin_do=Go;Submitter.target=NCBI_BLAST" target="_BLANK">
-               Submit selection to NCBI BLAST</a></td></tr>
-       </table>
-
-# Configuration for submitter plugin (used in above menu)
-[Submitter:plugin]
-submitter = [NCBI_BLAST]
-            confirm   = 1
-            url       = http://www.ncbi.nlm.nih.gov/blast/Blast.cgi
-            seq_label = QUERY
-            PAGE      = Nucleotides
-            PROGRAM   = blastn
-            DATABASE  = nr
-            CLIENT    = web
-            CMD       = put
-
-
-
-# Default glyph settings
-[TRACK DEFAULTS]
-glyph       = generic
-height      = 8
-bgcolor     = cyan
-fgcolor     = cyan
-label density = 25
-bump density  = 100
-link = AUTO
-link_target = _blank
-
-[Genes]
-feature		= gene
-glyph		= transcript
-key		= Genes

+ 0 - 48
extensions/tripal_gbrowse/theme/tripal_gbrowse/tripal_gbrowse_database_details.tpl.php

@@ -1,48 +0,0 @@
-<?php
-// Developed by: Chad N.A Krilow at The University of Saskatchewan
-//
-// Purpose: Provide layout and content for the GBrowse database details. This
-//   includes database related fields in the tripal_gbrowse_instances table.
-//
-// Note: This template controls the layout/content for the default tripal_gbrowse node
-//   template (node-tripal_grbowse.tpl.php) and the Database Details Block
-//
-// Variables Available:
-//   - $node: a standard object which contains includes GBrowse Databse specific fields such as  
-//			 database_name, database_user, user_password, etc.
-?>
-
-<?php
- //uncomment this line to see a full listing of the fields avail. to $node
- //print '<pre>'.print_r($node,TRUE).'</pre>';
-?>  
-
-<?php
-
-$gbrowse = $node->gbrowse;
-
-?>
-<div id="tripal_gbrowse-database-box" class="tripal_gbrowse-info-box tripal-info-box">
-  <div class="tripal_gbrowse-info-box-title tripal-info-box-title"> Data Base Details</div>
-  <div class="tripal_gbrowse-info-box-desc tripal-info-box-desc"></div>
-
-   <?php //if the gbrowse is deleted/removed issue a warning
-   if(strcmp($gbrowse->is_obsolete,'t')==0){ 
-   ?>
-      <div class="tripal_gbrowse-obsolete">This GBrowse Instance is obsolete or has been deleted/removed</div>
-   <?php }?>
-   <table id="tripal_gbrowse-base-table" class="tripal_gbrowse-table tripal-table tripal-table-vert">
-      <tr class="tripal_gbrowse-table-even-row tripal-table-even-row">
-        <th>Data Base Name</th>
-        <td><?php print $node->gbrowse->database_name; ?></td>
-      </tr>
-      <tr class="tripal_gbrowse-table-odd-row tripal-table-odd-row">
-        <th nowrap>Database User Name</th>
-        <td><?php print $node->gbrowse->database_user; ?></td>
-      </tr>
-      <tr class="tripal_gbrowse-table-even-row tripal-table-even-row">
-        <th>User Password</th>
-        <td><?php print $node->gbrowse->user_password; ?></td>
-      </tr>     	                                
-   </table>
-</div>

+ 0 - 45
extensions/tripal_gbrowse/theme/tripal_gbrowse/tripal_gbrowse_details.tpl.php

@@ -1,45 +0,0 @@
-<?php
-// Developed by: Chad N.A Krilow at The University of Saskatchewan 
-//
-// Purpose: Provide layout and content for the GBrowse database details. This
-//   includes databse user specific fields in the tripal_gbrowse_instances table.
-//
-// Note: This template controls the layout/content for the default tripal_gbrowse node
-//   template (node-tripal_grbowse.tpl.php) and the Database Details Block
-//
-// Variables Available:
-//   - $node: a standard object which contains all the fields associated with
-//       nodes. It also includes GBrowse specific fields such as gbrowse_name, 
-//			 database_link, config_file.
-?>
-
-<?php
- //uncomment this line to see a full listing of the fields avail. to $node
- //print '<pre>'.print_r($node,TRUE).'</pre>';
-?> 
-
-
-<?php $gbrowse = $node->gbrowse; ?>
-
-<div id="tripal_gbrowse-base-box" class="tripal_gbrowse-info-box tripal-info-box">
-  <div class="tripal_gbrowse-info-box-title tripal-info-box-title"> GBrowse Details</div>
-  <div class="tripal_gbrowse-info-box-desc tripal-info-box-desc"></div>
-
-   <?php if(strcmp($gbrowse->is_obsolete,'t')==0){ ?>
-      <div class="tripal_gbrowse-obsolete">This GBrowse Instance is obsolete or has been deleted/removed</div>
-   <?php }?>
-   <table id="tripal_gbrowse-base-table" class="tripal_gbrowse-table tripal-table tripal-table-vert">
-      <tr class="tripal_gbrowse-table-even-row tripal-table-even-row">
-        <th>GBrowse Instance</th>
-        <td><?php print $node->gbrowse->gbrowse_name; ?></td>
-      </tr>
-      <tr class="tripal_gbrowse-table-odd-row tripal-table-odd-row">
-        <th nowrap>GBrowse Instance Link</th>
-        <td><?php print $node->gbrowse->gbrowse_link; ?></td>
-      </tr>
-      <tr class="tripal_gbrowse-table-even-row tripal-table-even-row">
-        <th>Configuration File</th>
-        <td><?php print $node->gbrowse->config_file; ?></td>
-      </tr>     	                                
-   </table>
-</div>

+ 0 - 28
extensions/tripal_gbrowse/theme/tripal_gbrowse/tripal_gbrowse_gbrowse_instance.tpl.php

@@ -1,28 +0,0 @@
-<?php
-// Developed by: Chad N.A Krilow at The University of Saskatchewan
-//
-// Purpose: Provide a in window I-Frame that displays the GBrowse instance. As well,
-// a link to open the GBrowse instance in a external window is provided. If the window can not be
-// opened a warning is issued
-//   
-// Variables Available:
-//   - $node: a standard object which contains all the fields associated with
-//       nodes. Here it is utilized for accessing the link to a specific GBrowse instance.
-//
-//   NOTE: For a full listing of fields available in the node object the
-//       print_r $node line below or install the Drupal Devel module which 
-//       provides an extra tab at the top of the node page labelled Devel
-?>
-
-<?php
- //uncomment this line to see a full listing of the fields avail. to $node
- //print '<pre>'.print_r($node,TRUE).'</pre>';
-?>
-
-<br />
-<h3><a href="<?php print $node->gbrowse->gbrowse_link; ?>" target="_blank">Open GBrowse Instance in new Window</a></h3>
-<br />
-
-<iframe src="<?php print $node->gbrowse->gbrowse_link; ?>" width="100%" height="800">
-  <p>Your browser does not support iframes.</p>
-</iframe>

+ 0 - 42
extensions/tripal_gbrowse/theme/tripal_gbrowse/tripal_gbrowse_loaded_sources.tpl.php

@@ -1,42 +0,0 @@
-<?php
-// Developed by: Chad N.A Krilow at The University of Saskatchewan
-//
-// Variables Available:
-//   - $node: a standard object which contains includes GBrowse Databse specific fields such as  
-//			 database_name, database_user, user_password, etc.
-?>
-
-<?php
- //uncomment this line to see a full listing of the fields avail. to $node
- //print '<pre>'.print_r($node,TRUE).'</pre>';
-?>  
-
-<?php
-
-$gbrowse = $node->gbrowse;
-$node->sources = tripal_gbrowse_getloaded_sources($node->gbrowse);
-
-?>
-<div id="tripal_gbrowse-source-box" class="tripal_gbrowse-info-box tripal-info-box">
-  <div class="tripal_gbrowse-info-box-title tripal-info-box-title"> Loaded Sources</div>
-  <div class="tripal_gbrowse-info-box-desc tripal-info-box-desc">A source can be either a library or analysis or any other grouping of features.</div>
-
-   <?php //if the gbrowse is deleted/removed issue a warning
-   if(strcmp($gbrowse->is_obsolete,'t')==0){ 
-   ?>
-      <div class="tripal_gbrowse-obsolete">This GBrowse Library is obsolete or has been deleted/removed</div>
-   <?php }?>
-   <table id="tripal_gbrowse-base-table" class="tripal_gbrowse-table tripal-table tripal-table-vert">
-   <tr><th>Name</th></tr>
-   
-   
-   <?php 
-   if(!empty($node->sources)){
-   	foreach($node->sources as $key => $source){
-   ?>
-      <tr class="tripal_gbrowse-table-even-row tripal-table-even-row">
-        <td><?php print $source; ?></td>
-      </tr>
-		<?php }} //end of foreach library & end of if statement ?>  	                                
-   </table>
-</div>

+ 0 - 34
extensions/tripal_gbrowse/theme/tripal_gbrowse/tripal_gbrowse_teaser.tpl.php

@@ -1,34 +0,0 @@
-<?php
-// Developed by: Chad N.A Krilow at The University of Saskatchewan
-//
-// Purpose: Provide layout and content for the Tripal Gbrowse details.Represents
-// what the user will see if the there is no information in the node
-//
-// Variables Available:
-//   - $node: a standard object which contains all the fields associated with
-//       nodes including nid, gbrowse_id.
-//   NOTE: For a full listing of fields available in the node object the
-//       print_r $node line below or install the Drupal Devel module which 
-//       provides an extra tab at the top of the node page labelled Devel
-?>
-
-<?php
- //uncomment this line to see a full listing of the fields avail. to $node
- //print '<pre>'.print_r($node,TRUE).'</pre>';
-?>
-
-<div id="tripal_gbrowse-base-box" class="tripal_gbrowse-info-box tripal-info-box">
-  <div class="tripal_gbrowse-info-box-title tripal-info-box-title">
-  
-  	<!-- Title -->  	
-    <?php print l($node->gbrowse->gbrowse_name, 'node/'.$node->nid); ?>
-
-		
-  </div>
-  <div class="tripal_gbrowse-info-box-desc tripal-info-box-desc"></div>
-
-<p>This is a representation of a created GBrowse instance.<p>
-<?php print l('See More Details', 'node/'.$node->nid); ?>
-
- 
-</div>

+ 0 - 647
extensions/tripal_gbrowse/tripal_gbrowse.align_features.inc

@@ -1,647 +0,0 @@
-<?php
-
-/**
- * Form to initialize an align library tripal job
- */
-function tripal_gbrowse_align_features_form ($form_state) {
-  $form = array();
-  
-  // compile all analysis' as options
-  $analysis_options = array();
-  $results = tripal_core_chado_select('analysis',array('analysis_id','name', 'program'), array());
-  foreach ($results as $r) {
-    $analysis_options[ 'A'.$r->analysis_id ] = $r->name .' --'.$r->program;
-  }
-  
-  // compile all libraries as options
-  $library_options = array();
-  $results = tripal_core_chado_select('library',array('library_id','name', 'uniquename'), array());
-  foreach ($results as $r) {
-    $library_options[ 'L'.$r->library_id ] = $r->name .' --'.$r->uniquename;
-  }  
-  
-  $form['description'] = array(
-    '#type' => 'item',
-    '#value' => 'This form allows you to select a query library/analysis and align the '
-      .'features that are part of that query library/analysis against those from a database '
-      .'library/analysis using BLAST. Depending upon the Alignment Criteria, the top BLAST '
-      .'result(s) for each query feature will be used to determine the location of the query '
-      .'feature on a database feature.',
-  );
-  
-  $form['q'] = array(
-    '#type' => 'fieldset',
-    '#title' => 'Features to be Aligned (Query)',
-    '#description' => 'Please select the library or analysis below which groups the features you '
-      .'want aligned together.',
-  );
-  
-  $form['q']['query'] = array(
-    '#type' => 'select',
-    '#title' => 'Query Features',
-    '#options' => array(
-      'Libraries' => $library_options,
-      "Analaysis'" => $analysis_options
-    ),
-    '#default_value' => $form_state['values']['query'],
-  );
-  
-  $form['d'] = array(
-    '#type' => 'fieldset',
-    '#title' => 'Features to Align To (Database)',
-    '#description' => 'Please select the library of analysis below, which contains the features '
-      .'you want to align the query features selected above to. Only features in the selected '
-      .'library/analysis with sequence data will be used.',
-  );
-
-  $form['d']['database'] = array(
-    '#type' => 'select',
-    '#title' => 'Database Features',
-    '#options' => array(
-      'Libraries' => $library_options,
-      "Analaysis'" => $analysis_options
-    ),
-    '#default_value' => $form_state['values']['database'],
-  );
-  
-  $form['b'] = array(
-    '#type' => 'fieldset',
-    '#title' => 'Alignment Criteria',
-  );
-  
-  $form['b']['program'] = array(
-  	'#type' => 'radios',
-  	'#title' => 'Alignment Program',
-  	'#options' => array(
-  		'blast' => 'BLAST',
-  		'blat' => 'BLAT',
-  	),
-  	'#default_value' => 'blat',
-  );
-
-  $form['b']['blat'] = array(
-  	'#type' => 'fieldset',
-  	'#title' => 'BLAT Options',
-  	'#collapsible' => TRUE,
-		'#collapsed' => TRUE,
-  );
-  
-  $form['b']['blat']['min_identity'] = array(
-  	'#type' => 'textfield',
-  	'#title' => 'Minimum Identity',
-  	'#default_value' => '90',
-  );
-  
-  $form['b']['blast'] = array(
-  	'#type' => 'fieldset',
-  	'#title' => 'BLAST Options',
-  	'#collapsible' => TRUE,
-		'#collapsed' => TRUE,
-  );
-  
-  $form['b']['blast']['gapped_alignment'] = array(
-  	'#type' => 'checkbox',
-  	'#title' => 'Gapped Alignment?',
-  	'#default_value' => TRUE,
-  );
-  
-  $form['b']['blast']['evalue'] = array(
-  	'#type' => 'textfield',
-  	'#title' => 'Expectation Values (E-value) Cutoff',
-  	'#description' => 'To enter in scientific notation (ie: 5 x 10-6), enter [base number]e[power] (ie: 5e-6)',
-  	'#default_value' => 10.0
-  );
-  
-  $form['g'] = array(
-  	'#type' => 'fieldset',
-  	'#title' => 'GBrowse Information',
-  );
-  
-  $form['g']['source'] = array(
-  	'#type' => 'textfield',
-  	'#title' => 'Source of Features',
-  	'#description' => 'The source of the features grouped by the selected query library'
-  );
-  
-  //Sending query to the database
-  $resource = db_query('SELECT * FROM {tripal_gbrowse_instances}');
-	$items = array();
-	while($record = db_fetch_object($resource)){
-		$items[$record->gbrowse_id]= $record->gbrowse_name;
-	}
-   
-  //GBrowse Instances
-  $form['g']['gbrowse_id'] = array(
-    '#type' => 'select',
-    '#title' => t('GBrowse Instances'),
-    '#options' => $items,
-    '#description' => t('Selected GBrowse Instances to load the query features into.'),
-  );
-  
-  $form['submit'] = array(
-    '#type' => 'submit',
-    '#name' => 'align',
-    '#value' => 'Align Features',
-  );
-  
-  return $form;
-}
-
-/**
- * Form submit to initialize an align library tripal job
- */
-function tripal_gbrowse_align_features_form_submit ($form, &$form_state) {
-  
-  switch($form_state['clicked_button']['#name']) {
-    case 'align':
-      $options = array();
-      // Query
-      if (preg_match('/(L|A)(\d+)/',$form_state['values']['query'], $matches)) {
-        if ($matches[1] == 'L') {
-          $options['query_type'] = 'library';
-        } else {
-          $options['query_type'] = 'analysis';
-        }
-        $options['query_id'] = $matches[2];
-      }
-      
-      // Database
-      if (preg_match('/(L|A)(\d+)/',$form_state['values']['database'], $matches)) {
-        if ($matches[1] == 'L') {
-          $options['db_type'] = 'library';
-        } else {
-          $options['db_type'] = 'analysis';
-        }
-        $options['db_id'] = $matches[2];
-      } 
-      
-      $options['source'] = $form_state['values']['source'];
-      
-      // db options
-      $sql = 'SELECT * FROM {tripal_gbrowse_instances} WHERE gbrowse_id = %d';
-      $r = db_fetch_object(db_query($sql,$form_state['values']['gbrowse_id']));
-      $options['dbname'] = $r->database_name;
-      $options['dbuser'] = $r->database_user;
-      $options['dbpass'] = $r->user_password;
-
-			if ($form_state['values']['program'] == 'blat') { 
-				// blat options
-				$options['min_identity'] = $form_state['values']['min_identity'];
-				
-				global $user;
-				tripal_add_job(
-					'Align '.$options['query_type'].' features ('.$options['query_type'].'_id='.$options['query_id'].')',
-					'tripal_gbrowse',
-					'tripal_gbrowse_align_features_by_blat',
-					array(serialize($options)),
-					$user->uid
-				);			
-			} elseif ($form_state['values']['program'] == 'blast') {      
-				// blast options
-				$options['evalue'] = $form_state['values']['evalue'];
-				$options['gapped_alignment'] = $form_state['values']['gapped_alignment'];
-			
-				global $user;
-				tripal_add_job(
-					'Align '.$options['query_type'].' features ('.$options['query_type'].'_id='.$options['query_id'].')',
-					'tripal_gbrowse',
-					'tripal_gbrowse_align_features_by_blast',
-					array(serialize($options)),
-					$user->uid
-				);
-      }
-      
-    break;
-  }
-}
-
-/**
- * Aligns feature from a query library/analysis to a database library/analysis,
- * saving the results as a GFF3 file and then loading it into the selected gbrowse instance
- *
- * @param $options
- *   An array containing options needed to align features and create featurelocs
- *    -query_type: the type of chado grouping containing query features (either library or analysis)
- *    -query_id: the library_id/analysis_id containing the query features
- *    -db_type: the type of chado grouping containing database features (either library or analysis)
- *    -db_id: the library_id/analysis_id containing the database features
- *    -dbname: name of the MySQL GBrowse database to load into
- *    -dbuser: name of the user with permission to load into the above database
- *    -dbpass: the password for the above user
- */
-function tripal_gbrowse_align_features_by_blast ($options) {
-  $options = unserialize($options);
-  print 'Query: '.$options['query_type'].' where '.$options['query_type'].'_id='.$options['query_id']."\n";
-  print 'Database: '.$options['db_type'].' where '.$options['db_type'].'_id='.$options['db_id']."\n";
-  
-  // Generate FASTA ---------------------------------------
-  print "\nGenerating fasta files for query and database...\n";
-  $query_file = tripal_gbrowse_export_fasta_for_features( $options['query_type'], $options['query_id'], TRUE );
-  print "\t".$query_file['file']."\n";
-  
-  $db_file = tripal_gbrowse_export_fasta_for_features( $options['db_type'], $options['db_id'], TRUE, TRUE );
-  print "\t".$db_file['file']."\n";
-  
-  // Align using BLAST ------------------------------------
-  print "\nAligning features using BLAST...\n";
-  
-  print "\tFormating Database FASTA into BLASTdb...\n";
-  $db = '/tmp/exported_'.$options['db_type'].'_'.$options['db_id'];
-  $formatdb_cmd = 'formatdb -n '.$db.' -p F -i '.$db_file['file'];
-	print "\t\t".$formatdb_cmd."\n";  
-  exec($formatdb_cmd);
-	
-	print "\tExecuting BLAST...\n";
-	$blast_outfile = $db.'_by_'.$options['query_type'].'_'.$options['query_id'].'.blast.xml';
-	$blastall_cmd = 'blastall -p blastn -d '.$db.' -i '.$query_file['file'].' -m 7 -o '.$blast_outfile.' -e '.$options['evalue'];
-	if ($options['gapped_alignment']) {
-		$blastall_cmd .= ' -g';
-	}
-	print "\t\t".$blastall_cmd."\n";
-	exec($blastall_cmd);
-  
-  // Parse BLAST results ----------------------------------
-  print "\nParsing Blast Results into GFF3...\n";
-  $gff3_file = $db.'_by_'.$options['query_type'].'_'.$options['query_id'].'.gff3';
-  $fgff3 = fopen($gff3_file, 'w');
-  fwrite($fgff3, "##gff-version 3\n");
-  $iteration = tripal_gbrowse_get_next_xml_record ($blast_outfile, "<Iteration>");
-  while ($iteration) {
-  	//print "Record:".$iteration['record']->asXML()."\n";
-  	//print "Query: ".$iteration['record']->{'Iteration_query-def'}."\n";
-		
-		// Find the best Hit by looking at the bit scores of the hsps
-		// the larger the bit score the better the alignment
-		$hits = array();
-		$scores = array();
-  	foreach ($iteration['record']->Iteration_hits->Hit as $hit) {
-  		$score = 0;
-  		$num = 0;
-  		foreach ($hit->{'Hit_hsps'}->{'Hsp'} as $hsp) {
-  			//print 'HSP:'.$hsp->asXML()."\n";
-  			$score = $score + $hsp->{'Hsp_bit-score'};
-  			$num++;
-  		}
-  		$avg = round($score / $num,2);
-  		$hit->{'Hit_bit-score'} = $avg;
-  		$hits[] = array('score' => $avg, 'hit' => $hit);
-  	}
-  	usort($hits, 'tripal_gbrowse_sort_by_score');
-  	$best_hit = $hits[0]['hit'];
-  	//print "\tBest Hit:".$best_hit->Hit_def.' ('.$best_hit->{'Hit_bit-score'}.")\n";
-  	
-  	// generate gff3 for the best hit 
-  	$query_name = $iteration['record']->{'Iteration_query-def'};
-  	$db_name = $best_hit->Hit_def;  
-  	if (isset($db_file['noseq_features'][$db_name])) {
-  	  $db_offset = $db_file['noseq_features'][$db_name]['start'];
-  	  $db_name = $db_file['noseq_features'][$db_name]['parent']['uniquename'];
-  	} else {
-  	  $db_offset = 0;
-  	}
-		$lines = array();
-		$hit_start = 99999999999999999999;
-		$hit_end = 0;
-  	foreach ($best_hit->{'Hit_hsps'}->{'Hsp'} as $hsp) {
-  		if ($hit_start > (int) $hsp->{'Hsp_hit-from'}[0]) { $hit_start = (int) $hsp->{'Hsp_hit-from'}[0]; } 
-  		if ($hit_end < (int) $hsp->{'Hsp_hit-to'}[0]) { $hit_end = (int) $hsp->{'Hsp_hit-to'}; }
-  		$lines[] = implode("\t", array(
-  			$db_name, 
-  			$options['source'],
-  			'match_part',
-  			$hsp->{'Hsp_hit-from'} + $db_offset,
-  			$hsp->{'Hsp_hit-to'} + $db_offset,
-  			$hsp->{'Hsp_bit-score'},
-  			'.',
-  			'.',
-  			'ID='.$query_name.'_'.$hsp->{'Hsp_num'}.';Parent='.$query_name
-  		))."\n";
-  	}
-  	fwrite($fgff3, implode("\t", array(
-			$db_name, 
-			$options['source'],
-			'match',
-			$hit_start + $db_offset,
-			$hit_end + $db_offset,
-			$best_hit->{'Hit_bit-score'},
-			'.',
-			'.',
-			'ID='.$query_name.';Name='.$query_name
-		))."\n");
-		fwrite($fgff3,implode('',$lines));
-  	
-  	// get next iteration xml record
-  	$last_iteration = $iteration;
-  	//print "Getting Iteration...\n";
-  	$iteration = tripal_gbrowse_get_next_xml_record ($blast_outfile, "<Iteration>", $last_iteration['start_line_num']);
-  }
-  
-  print "\nLoading GFF3 into GBrowse...\n";
-  //The loading script: bp_seqfeature_load.pl, allows loading of data to specific file 
-  $command= "bp_seqfeature_load.pl -u '" .$options['dbuser']. "' -p '" .$options['dbpass']. "' -d " .$options['dbname']. " " . $gff3_file;
-  print "\t".$command."\n";
-
-  exec($command);
-}
-
-/**
- * Aligns feature from a query library/analysis to a database library/analysis,
- * saving the results as a GFF3 file and then loading it into the selected gbrowse instance
- *
- * @param $options
- *   An array containing options needed to align features and create featurelocs
- *    -query_type: the type of chado grouping containing query features (either library or analysis)
- *    -query_id: the library_id/analysis_id containing the query features
- *    -db_type: the type of chado grouping containing database features (either library or analysis)
- *    -db_id: the library_id/analysis_id containing the database features
- *    -dbname: name of the MySQL GBrowse database to load into
- *    -dbuser: name of the user with permission to load into the above database
- *    -dbpass: the password for the above user
- */
-function tripal_gbrowse_align_features_by_blat ($options,$job_id) {
-  $options = unserialize($options);
-  print 'Query: '.$options['query_type'].' where '.$options['query_type'].'_id='.$options['query_id']."\n";
-  print 'Database: '.$options['db_type'].' where '.$options['db_type'].'_id='.$options['db_id']."\n";
-  
-  // Generate FASTA ---------------------------------------
-  print "\nGenerating fasta files for query and database...\n";
-  $query_file = tripal_gbrowse_export_fasta_for_features( $options['query_type'], $options['query_id'], TRUE );
-  print "\t".$query_file['file']."\n";
-  tripal_job_set_progress($job_id, 12);
-  
-  $db_file = tripal_gbrowse_export_fasta_for_features( $options['db_type'], $options['db_id'], TRUE, TRUE );
-  print "\t".$db_file['file']."\n";
-  tripal_job_set_progress($job_id, 25);
-  
-  // Align using BLAT ------------------------------------
-  print "\nAligning features using BLAT...\n";
-	$blat_outfile = '/tmp/alignment_'.$options['db_type'].'-'.$options['db_id'].'_by_'.$options['query_type'].'-'.$options['query_id'].'.psl';
-	$blat_cmd = 'blat '.$db_file['file'].' '.$query_file['file'].' -q=dnax -t=dnax -noHead -minIdentity='.$options['min_identity'].' '.$blat_outfile;
-	print "\t\t".$blat_cmd."\n";
-	exec($blat_cmd);
-	tripal_job_set_progress($job_id, 50);
-	
-	// Parse BLAST results ----------------------------------
-	$total_lines = trim(`wc --lines < $blat_outfile`);
-	$interval = intval($total_lines/5);
-	$percent_per_line = 25/$total_lines;
-	$num_lines = 0;
-	$query_seq = array();
-	
-	print "\nParsing BLAT results into GFF3 (".$total_lines." lines)...\n";
-	$gff3_file = '/tmp/alignment_'.$options['db_type'].'-'.$options['db_id'].'_by_'.$options['query_type'].'-'.$options['query_id'].'.gff3';
-  $fgff3 = fopen($gff3_file, 'w');
-  fwrite($fgff3, "##gff-version 3\n");
-	$bh = fopen($blat_outfile, 'r');
-	while (!feof($bh)) {
-		$line = explode("\t", fgets($bh));
-		$num_lines++;
-		if (($num_lines%$interval) == 0) { tripal_job_set_progress($job_id, intval($percent_per_line * $num_lines)); }
-		
-		$print_match = TRUE;
-    $db_name = $line[13];
-  	if (isset($db_file['noseq_features'][$db_name])) {
-  	  $db_offset = $db_file['noseq_features'][$db_name]['start'];
-  	  $db_name = $db_file['noseq_features'][$db_name]['parent']['uniquename'];
-  	} else {
-  	  $db_offset = 0;
-  	}
-  	
-  	$query_id = $line[9];
-  	if (!isset($query_seq[ $line[9] ])) {
-  		$query_seq[ $line[9] ]['id'] = 0;
-  		$query_seq[ $line[9] ]['start'] = $line[15] + $db_offset;
-  		$query_seq[ $line[9] ]['end'] = $line[16] + $db_offset;
-  		$query_id .= '_0';
-  	} elseif ( abs($line[15]+$db_offset-$query_seq[ $line[9] ]['start']) < 5 ) {
-  		$print_match = FALSE;
-  		$query_id .= '_' . $query_seq[ $line[9] ]['id'];
-  	}else {
-  		$query_seq[ $line[9] ]['id']++;
-  		$query_id .= '_' . $query_seq[ $line[9] ]['id'];
-  	}
-  	
-		// match line
-		if ($print_match) {
-			fwrite($fgff3, implode("\t", array(
-				$db_name, 
-				$options['source'],
-				'match',
-				$line[15] + $db_offset,
-				$line[16] + $db_offset,
-				'.',
-				$line[8][1],
-				'.',
-				'ID='.$query_id.';Name='.$line[9]
-			))."\n");
-		}
-		
-		// match parts
-		$parts_size = explode(',',trim($line[18]));
-		$parts_start = explode(',',trim($line[20]));
-		foreach ($parts_size as $k => $length) {
-
-			if (!empty($parts_start[$k])) {
-				fwrite($fgff3, implode("\t", array(
-					$db_name, 
-					$options['source'],
-					'match_part',
-					$parts_start[$k] + $db_offset,
-					$parts_start[$k] + $length + $db_offset,
-					'.',
-					$line[8][1],
-					'.',
-					'ID='.$query_id.'_'.$k.';Parent='.$query_id
-				))."\n");
-  		}
-  		
-		}
-	}
-	tripal_job_set_progress($job_id, 75);
-	
-	// Load into GBrowse ------------------------------------
-  print "\nLoading GFF3 into GBrowse...\n";
-  //The loading script: bp_seqfeature_load.pl, allows loading of data to specific file 
-  $command= "bp_seqfeature_load.pl -u '" .$options['dbuser']. "' -p '" .$options['dbpass']. "' -d " .$options['dbname']. " " . $gff3_file;
-  print "\t".$command."\n";
-	exec($command);
-
-}
-
-/**
- * Creates a fasta file for a given chado grouping of features
- *
- * @param $type
- *   The type of chado grouping. Allowed values are either library or analysis
- * @param $id
- *   The library_id/analysis_id of the chado grouping
- * @return
- *   The name of the multi-fasta file containing records for all features with residues
- *   in the supplied library/analysis
- */
-function tripal_gbrowse_export_fasta_for_features ($type, $id, $use_parent_seq = FALSE, $save_offset = FALSE) {
-
-  $fasta_file = '/tmp/exported_fasta-'.$type.'-'.$id.'.fasta';
-  $noseq_features = array();
-  
-  $fh = fopen($fasta_file,'w');
-  
-  $sql = 'SELECT f.uniquename, f.residues, fl.fmin, fl.fmax, fl.srcfeature_id as parent_feature_id FROM feature f '
-  	.'LEFT JOIN featureloc fl ON fl.feature_id=f.feature_id ';
-  $parent_sql = 'SELECT p.feature_id as parent_feature_id, p.uniquename as parent_uniquename, count(fl.feature_id) FROM feature p '
-  	.'LEFT JOIN featureloc fl ON fl.srcfeature_id=p.feature_id '
-  	."WHERE fl.feature_id IN (SELECT feature_id FROM feature WHERE residues='') AND ";
-  if ($type == 'library') { 
-  	$sql .= 'LEFT JOIN library_feature lf ON f.feature_id=lf.feature_id WHERE lf.library_id=%d';
-  	$parent_sql .= 'fl.feature_id IN (SELECT feature_id FROM library_feature WHERE library_id=%d) GROUP BY p.uniquename, p.feature_id';
-    
-  } elseif ($type == 'analysis') {
-  	$sql .= 'LEFT JOIN analysisfeature af ON f.feature_id=af.feature_id WHERE af.analysis_id=%d';
-		$parent_sql .= 'fl.feature_id IN (SELECT feature_id FROM analysisfeature WHERE analysis_id=%d) GROUP BY p.uniquename, p.feature_id';
-    $resource = db_query($sql, $id);
-  } else {
-    print "ERROR: Unable to generate FASTA due to unrecognized type -".$type."!\n";
-    return FALSE;
-  }
-
-  
-  // check if some don't have sequence but are aligned on a parent who does
-	//print "SQL: ".$parent_sql."\n";
-  $resource = db_query($parent_sql, $id);
-	$parent_seq = array();
-	$residues_seq = 'SELECT residues FROM feature WHERE feature_id=%d';
-  while ($r = db_fetch_object($resource)) {
-  	//print 'Creating index for '.$r->parent_feature_id. " (".$r->parent_uniquename.")\n";
-  	$seq = db_fetch_object(db_query($residues_seq, $r->parent_feature_id));
-  	//print "Residues:".$seq->residues."\n";
-  	if (!empty($seq->residues)) {
-	  	//print "\tGot Seq!\n";
-	  }
-		$parent_seq[ $r->parent_feature_id ] = array(
-			'residues' => $seq->residues,
-			'uniquename' => $r->parent_uniquename
-		);
-  }
-  
-	$resource = db_query($sql, $id);
-  while ($r = db_fetch_object($resource)) {
-    if (!empty($r->residues)) {
-      fwrite($fh, '>'.$r->uniquename."\n");
-      fwrite($fh, wordwrap($r->residues,80,"\n",TRUE)."\n");
-    } else {
-	    //print $r->uniquename." (based on ".$r->parent_feature_id.' -'.$parent_seq[$r->parent_feature_id]['uniquename'].")\n";
-      if (!empty($parent_seq[$r->parent_feature_id]['residues'])) {
-      	//print "\tHave Seq\n";
-      	fwrite($fh, '>'.$r->uniquename." (based on ".$parent_seq[$r->parent_feature_id]['uniquename'].")\n");
-        $seq = substr($parent_seq[$r->parent_feature_id]['residues'], $r->fmin, $r->fmax - $r->fmin);
-        fwrite($fh, wordwrap($seq,80,"\n",TRUE)."\n");
-        if ($save_offset) {
-          $noseq_features[ $r->uniquename ] = array(
-            'start' => $r->fmin,
-            'end' => $r->fmax,
-            'parent' => array(
-              'uniquename' => $parent_seq[$r->parent_feature_id]['uniquename'],
-            ),
-          );
-        }
-      }
-    }
-  }
-  
-  fclose($fh);
-  return array(
-    'file' => $fasta_file,
-    'noseq_features' => $noseq_features
-  );
-}
-
-/**
- * Retrieves the next xml record with $record_identifier
- *
- * Assumption: the end tag for $record_identifier is one line before the next opening tag
- * @param $xml_file
- *   The file containing the xml records; must supply the full path
- * @param $record_identifier
- *   The opening tag enclosing a record (ie: <Iteration>)
- * @param $last_record_line_num
- *   The line number of the openin tag for the last record
- * 
- * @return
- *   An array describing the next xml record
- *    -record: the simpleXML record
- *    -start_line_num: the line number in the file that this record starts at
- *    -end_line_num: the line number in the file that this record ends at
- */
-function tripal_gbrowse_get_next_xml_record ($xml_file, $record_identifier, $last_record_line_num = NULL) {
-
-	// If first record ------------------------------------------------
-	if (!$last_record_line_num) {
-		$cmd = 'grep -n "'.$record_identifier.'" -m 2 '.$xml_file;
-		exec($cmd, $line_num_raw);
-
-		// get start of next record
-		if (preg_match('/(\d+):.*/',$line_num_raw[0],$matches)) {
-			$start = $matches[1];
-		} else {
-			return FALSE;
-		}
-
-		// get end of next record
-		if (preg_match('/(\d+):.*/',$line_num_raw[1],$matches)) {
-			$end = $matches[1] -1;
-		} else {
-			return FALSE;
-		}
-
-	// If not first record --------------------------------------------
-	} else {
-
-		$cmd = 'tail --lines=+'.($last_record_line_num+1).' '.$xml_file.' 2>/dev/null | grep -n "'.$record_identifier.'" -m 2 2>/dev/null ';
-		exec($cmd, $line_num_raw);
-
-		// get start of next record
-		if (preg_match('/(\d+):.*/',$line_num_raw[0],$matches)) {
-			$start = $matches[1] + $last_record_line_num;
-		} else {
-			return FALSE;
-		}
-
-		// get end of next record
-		if (preg_match('/(\d+):.*/',$line_num_raw[1],$matches)) {
-			$end = $matches[1] + $last_record_line_num -1;
-		} else {
-			return FALSE;
-		}
-		
-	}
-	
-	$cmd = 'tail --lines=+'.$start.' '.$xml_file.' 2>/dev/null | head -n '.($end-$start+1).' 2>/dev/null';
-	exec($cmd, $xml);
-	
-	//print "XML:".implode("\n",$xml)."\n";
-	if (!$xml) {
-		return FALSE;
-	}
-	
-	$xml_record = new SimpleXMLElement(implode("\n",$xml));
-	return array(
-		'record' => $xml_record,
-		'start_line_num' => $start,
-		'end_line_num' => $end,
-	);
-}
-
-/**
- * Custom sort function to be used with usort
- * Sorts an array( 'score' => \d+, 'hit' => simplexml obj)
- */
-function tripal_gbrowse_sort_by_score ($a, $b) {
-
-	if ($a['score'] == $b['score']) {
-		return 0;
-	} elseif ($a['score'] < $b['score']) {
-		return 1;
-	} else {
-		return -1;
-	}
-}

+ 0 - 5
extensions/tripal_gbrowse/tripal_gbrowse.info

@@ -1,5 +0,0 @@
-; $Id$ 
-name = "GBrowse Management" 
-description = "Provides an interface to sync Tripal/Chado Features with a specified GBrowse instance. Management of GBrowse instances including creation and deletion is also provided." 
-core = 6.x
-package = Tripal Extensions

+ 0 - 119
extensions/tripal_gbrowse/tripal_gbrowse.install

@@ -1,119 +0,0 @@
-<?php
-// $Id$
-
-/**
- * @file
- * This file contains all the functions which describe and implement drupal database tables
- * needed by this module. This module was developed by Chad N.A. Krilow and Lacey-Anne Sanderson, 
- * University of Saskatchewan. 
- *
- * The GBrowse manamgenet module allows you to sync data in a chado/Tripal instance with
- * multiple GBrowse/mysql instances as well as manage and create such GBrowse instances
- */
-
-/**
- * Implementation of hook_install()
- */
-function tripal_gbrowse_install() {
-	drupal_install_schema('tripal_gbrowse');
-}
-
-
-
-function tripal_gbrowse_update_2 (&$sandbox) {
-
-	$ret = array();
-	
-  db_add_field($ret, 'tripal_gbrowse_instances', 'nid', array('type' => 'int','unsigned' => FALSE, 'not null' => TRUE));
-  
-  db_add_field($ret, 'tripal_gbrowse_instances', 'vid', array('type' => 'int','unsigned' => FALSE, 'not null' => TRUE));
-  
-  return $ret;
-}
-
-
-/**
- * Implementation of hook_uninstall() 
- */
-function tripal_gbrowse_uninstall() {
-	drupal_uninstall_schema('tripal_gbrowse');
-}
-
-/**
- * Implementation of hook_schema()
- */
-function tripal_gbrowse_schema() {
-
-	//specification for 'tripal_gbrowse_instances'
-	$schema['tripal_gbrowse_instances'] = array(
-		
-		'fields' => array(
-
-			//a int field that cannot be null and acts as a unique identifier for all nid's
-      'nid' => array(
-				'type' => 'int',
-				'unsigned' => FALSE,
-				'not null' => TRUE,
- 	 	  ),
-		
-	    //a int field that cannot be null and is vid 	  
-  		'vid' => array(
-   	   	'type' => 'int',
-   	   	'unsigned' => FALSE,
-   	   	'not null' => TRUE,
-  	  ),
-			
-	    //a serial field that cannot be null and acts as a unique identifier for all gbrowse instances
-      'gbrowse_id' => array(
-				'type' => 'serial',
-				'unsigned' => TRUE,
-				'not null' => TRUE,
- 	 	  ),
-		
-	    //a varchar field that cannot be null and is the name of a gbrowse instance  	  
-  		'database_name' => array(
-   	   	'type' => 'varchar',
-   	   	'not null' => TRUE,
-  	  ),
-   	 	
-      //a varchar field, not null and is name of a mysql user that has insert and select permissions on the database
-    	 'database_user' => array(
-   	   	'type' => 'varchar',
-   	   	'not null' => TRUE,
-    	),
-    	 	
-	    //user_password: a varchar field that is the password for the above user 	
-    	'user_password' => array(
-   	   	'type' => 'varchar',
-   	   	'not null' => TRUE,
-    	),
-    	
-      //name: a varchar which is a human-readable name for the gbrowse instance    	
-    	'gbrowse_name' => array(
-   	   	'type' => 'varchar',
-   	   	'not null' => TRUE,
-    	),
-    	
-    	
-      //link: a varchar which is the link to the gbrowse instance    	
-    	'gbrowse_link' => array(
-   	   	'type' => 'varchar',
-   	   	'not null' => TRUE,
-    	),
-    	
-    	
-      //config_file: fully qualified location to the gbrowse configuration file    	
-    	'config_file' => array(
-   	   	'type' => 'varchar',
-   	   	'not null' => TRUE,
-    	),
-  	  	
-    ),//end of shema
-  	
-  	'primary key' => array('gbrowse_id'),
-	
-	);
-
-  return $schema;
-}
-

+ 0 - 2994
extensions/tripal_gbrowse/tripal_gbrowse.module

@@ -1,2994 +0,0 @@
-<?php
-// $Id$
-
-/**
- * @file
- * This file contains all the functions which provide functionality to this module.
- * This module was developed by Chad N.A. Krilow and Lacey-Anne Sanderson, 
- * University of Saskatchewan. 
- *
- * The GBrowse manamgenet module allows you to sync data in a chado/Tripal instance with
- * multiple GBrowse/mysql instances as well as manage and create such GBrowse instances
- */
-
-include('tripal_gbrowse.align_features.inc');
-
-//-----------------------------------------------------------------------------
-//  SECTION: Main Outline Menu for GBrowse Management 
-//-----------------------------------------------------------------------------
-
-
-/**
- * Tripal-GBrowse-Menu
- *
- * Implemets hook_menu(): Adds menu items for the tripal_gbrowse module menu. This section
- * gives the outline for the main menu of the Tripal-GBrowse module
- *
- * @return
- *   An array of menu items that is visible within the Drupal Menu, returned as soon
- *   as the program is ran
- */
-function tripal_gbrowse_menu() {
-  
-  $items = array();
-  
-  $items[ 'admin/tripal/tripal_gbrowse' ]= array(
-    'title' => t('GBrowse Management'),
-    'description' => ('GBrowse management allows a user to create a database, register
-     a GBrowse instance and to load/delete feature libraries'),
-    'page callback' => 'tripal_gbrowse_administration_description_page',
-    'access arguments' => array('administer site configuration'),
-    'type' => MENU_NORMAL_ITEM
-  ); 
-
-  $items['admin/tripal/tripal_gbrowse/configuration'] = array(
-    'title' => t('Configuration'),
-    'description' => t('Configuration for this module'),
-    'page callback' => 'drupal_get_form',
-    'page arguments' => array('tripal_gbrowse_administration_form'),
-    'access arguments' => array('administer site configuration'),
-    'type' => MENU_NORMAL_ITEM
-  );
-
-  $items['admin/tripal/tripal_gbrowse/register_gbrowse'] = array(
-    'title' => t('Register GBrowse Instance'),
-    'description' => t('Interface to enter gbrowse details and save to the database'), 
-    'page callback' => 'drupal_get_form',
-    'page arguments' => array('tripal_gbrowse_register_gbrowse_form'), 
-    'access arguments' => array('administer site configuration'),
-    'weight' => 20,
-    'type' => MENU_NORMAL_ITEM
-  );
-  
-  $items['admin/tripal/tripal_gbrowse/unregister_gbrowse']=array(
-    'title' => t('Un-Register GBrowse Instance'),
-    'description' => t('Interface to remove gbrowse details from the database'), 
-    'page callback' => 'drupal_get_form',
-    'page arguments' => array('tripal_gbrowse_unregister_gbrowse_instances_form'), 
-    'access arguments' => array('administer site configuration'),
-    'type' => MENU_NORMAL_ITEM
-  );
-  
-  $items['admin/tripal/tripal_gbrowse/load_library_features'] = array(
-    'title' => t('Load Library Features'),
-    'description' => t('Load features associated with a specified library into a GBrowse instance.'),
-    'page callback' => 'drupal_get_form',
-    'page arguments' => array('tripal_gbrowse_load_library_features_form'),
-    'access arguments' => array('administer site configuration'),
-    'type' => MENU_NORMAL_ITEM
-  );
-  
-  $items['admin/tripal/tripal_gbrowse/load_analysis_features'] = array(
-    'title' => t('Load Analysis Features'),
-    'description' => t('Load features associated with a specified analyses into a GBrowse instance.'),
-    'page callback' => 'drupal_get_form',
-    'page arguments' => array('tripal_gbrowse_load_analyses_form'),
-    'access arguments' => array('administer site configuration'),
-    'type' => MENU_NORMAL_ITEM
-  );
-  
-  $items['admin/tripal/tripal_gbrowse/delete_library_features']=array(
-    'title' => t('Delete Library Features'),
-    'description' => t('Interface to delete features of a given library from a GBrowse Instance'), 
-    'page callback' => 'drupal_get_form',
-    'page arguments' => array('tripal_gbrowse_delete_library_features_from_gbrowse_form'), 
-    'access arguments' => array('administer site configuration'),
-    'type' => MENU_NORMAL_ITEM
-  );
-  
-  $items['admin/tripal/tripal_gbrowse/delete_analysis_features']=array(
-    'title' => t('Delete Analysis Features'),
-    'description' => t('Interface to delete features of a given analysis from a GBrowse Instance'), 
-    'page callback' => 'drupal_get_form',
-    'page arguments' => array('tripal_gbrowse_delete_analysis_features_from_gbrowse_form'), 
-    'access arguments' => array('administer site configuration'),
-    'type' => MENU_NORMAL_ITEM
-  );
-  
-  $items['admin/tripal/tripal_gbrowse/add_tracks']=array(
-      'title' => t('Add Tracks'),
-      'description' => t('Interface for Adding tracks to a GBrowse Instance'), 
-      'page callback' => 'drupal_get_form',
-      'page arguments' => array('tripal_gbrowse_add_tracks_form'), 
-      'access arguments' => array('administer site configuration'),
-      'type' => MENU_NORMAL_ITEM
-  );
-  
-  $items['admin/tripal/tripal_gbrowse/delete_tracks']=array(
-      'title' => t('Delete Tracks'),
-      'description' => t('Interface for Deleting tracks from a GBrowse Instance'), 
-      'page callback' => 'drupal_get_form',
-      'page arguments' => array('tripal_gbrowse_delete_tracks_form'), 
-      'access arguments' => array('administer site configuration'),
-      'type' => MENU_NORMAL_ITEM
-  );
-  
-  $items['admin/tripal/tripal_gbrowse/align_features']=array(
-      'title' => t('Align Features'),
-      'description' => t('Align a group of features (either library or analysis) against another grouping of features.'), 
-      'page callback' => 'drupal_get_form',
-      'page arguments' => array('tripal_gbrowse_align_features_form'), 
-      'access arguments' => array('administer site configuration'),
-      'type' => MENU_NORMAL_ITEM
-  );  
-
-  return $items;
-}
-
-/**
- * Implements hook_theme_registry_alter().
- */
-function tripal_gbrowse_theme_registry_alter(&$info) {
-  // Inject our module into the node theme registry as being an available theme
-  // path so that we can override the node template for our content type.
-  array_splice($info['node']['theme paths'], 1, 0, array(drupal_get_path('module', 'tripal_gbrowse')));
-}
-
-
-/**
- * Implements hook_theme(): Register themeing functions for this module
- *
- * Contains the seperate tripal_gbrowse_X.tpl.php files, so as they can be included in the
- * theme for the designed module
- *
- * @return
- *   An array of themeing functions to register
- *
- */
-function tripal_gbrowse_theme() {
-	
-	$path = drupal_get_path('module', 'tripal_gbrowse_theme') . '/theme/tripal_gbrowse';
-	
-	return array(
-    // Block Templates------------------------------
-    'tripal_gbrowse_database_details' => array (
-      'arguments' => array('node'=> null),
-      'template' => 'tripal_gbrowse_database_details',
-      'path' => $path,
-    ),
-    'tripal_gbrowse_details' => array (
-      'arguments' => array('node'=> null),
-      'template' => 'tripal_gbrowse_details',
-      'path' => $path,
-    ),
-    'tripal_gbrowse_gbrowse_instance' => array (
-      'arguments' => array('node'=> null),
-      'template' => 'tripal_gbrowse_gbrowse_instance',
-      'path' => $path,
-    ),
-    'tripal_gbrowse_teaser' => array (
-      'arguments' => array('node'=> null),
-      'template' => 'tripal_gbrowse_teaser',
-      'path' => $path,
-    ),
-    'tripal_gbrowse_loaded_sources' => array (
-      'arguments' => array('node'=> null),
-      'template' => 'tripal_gbrowse_loaded_sources',
-      'path' => $path,
-    ),
-	);
-}
-
-
-/**
- * Purpose: Implement Blocks relating to Tripal GBrowse content
- *
- * @param $op
- *   What kind of information to retrieve about the block or blocks. 
- *   Possible values include list, configure, save, view.
- * @param $delta
- *   Which block to return (not applicable if $op is 'list').
- * @param $edit
- *   If $op is 'save', the submitted form data from the configuration form.
- *
- * @return
- *   One of the following depending on $op: An array of block descriptions (list), the configuration 
- *   form (configure), nothing (save), an array defining subject and content for the block indexed 
- *   by $delta (view)
- *
- */
-function tripal_gbrowse_block ($op = 'list', $delta = 0, $edit=array()) {
-  switch($op) {
-    case 'list':
-      $blocks['database_details']['info'] = t('Tripal GBrowse Database Details');
-      $blocks['database_details']['cache'] = BLOCK_NO_CACHE;
-
-      $blocks['details']['info'] = t('Tripal GBrowse Details');
-      $blocks['details']['cache'] = BLOCK_NO_CACHE;
-         
-      $blocks['gbrowse_instance']['info'] = t('Tripal GBrowse Instance');
-      $blocks['gbrowse_instance']['cache'] = BLOCK_NO_CACHE;
-         
-      $blocks['teaser']['info'] = t('Tripal GBrowse Teaser');
-      $blocks['teaser']['cache'] = BLOCK_NO_CACHE;
-      
-      $blocks['teaser']['info'] = t('Tripal GBrowse Sources');
-      $blocks['teaser']['cache'] = BLOCK_NO_CACHE;
-      
-      return $blocks;
-
- 		case 'view':
- 			if(user_access('access tripal_gbrowse content') and arg(0) == 'node' and is_numeric(arg(1))) {
-      	$nid = arg(1);
-      	$node = node_load($nid);
- 
-        $block = array();
-        switch($delta){
-					case 'database_details':
-						$block['subject'] = t('Tripal GBrowse Database Details');
-						$block['content'] = theme('tripal_gbrowse_database_details',$node);
-						break;
-						
-					case 'details':
-						$block['subject'] = t('Tripal GBrowse Details');
-						$block['content'] = theme('tripal_gbrowse_details',$node);
-						break;
-						
-					case 'gbrowse_instance':
-						$block['subject'] = t('Tripal GBrowse Instance');
-						$block['content'] = theme('tripal_gbrowse_gbrowse_instance',$node);
-						break;
-						
-					case 'teaser':
-						$block['subject'] = t('Tripal GBrowse Teaser');
-						$block['content'] = theme('tripal_gbrowse_teaser',$node);
-						break;
-						
-					case 'teaser':
-						$block['subject'] = t('Tripal GBrowse Sources');
-						$block['content'] = theme('tripal_gbrowse_loaded_sources',$node);
-						break;	
-							
-        }
-				return $block;
-			}
-	}
-}
-
-
-/**
- * Implements hook_views_api()
- * Purpose: Essentially this hook tells drupal that there is views support
- *  for this module which then includes tripal_db.views.inc where all the
- *  views integration code is
- */ 
-function tripal_gbrowse_views_api() {
-   return array(
-      'api' => 2.0,
-   );
-}
-
-
-/**
- * This section uses HTML to output the descriptions of the module, through the Tripal Management
- * Administation window.Any installation instructions are given as well as included features
- * as well as a overview of the purpose Module.
- *
- * @return
- *   Returns '$text'The HTML description of the Module, its instructions, features, and any other 
- *   important aspects. This is returned when the Administration page is selected.
- */
-function tripal_gbrowse_administration_description_page() {
-
-  $text = ' ';
-
-  $text .= '</p><h3>GBrowse Feature Administrative Tools Quick Links:</h3>';
-  
-  $text .= "<ul>";
-  
-  $text .= "<li>".l("Configuration", "admin/tripal/tripal_gbrowse/configuration"). "</li>";
-	$text .= "<li>".l('Register GBrowse Instance', 'node/add/tripal-gbrowse')."</li>";
-  $text .= "<li>".l("Load Library Features", "admin/tripal/tripal_gbrowse/load_library_features"). "</li>";
-  $text .= "<li>".l("Delete Library Features", "admin/tripal/tripal_gbrowse/delete_library_features"). "</li>";
-  $text .= "<li>".l("Load Analysis Features", "admin/tripal/tripal_gbrowse/load_analysis_features"). "</li>";
-  $text .= "<li>".l("Delete Analysis Features", "admin/tripal/tripal_gbrowse/delete_analysis_features"). "</li>";
-  $text .= "<li>".l("Add Tracks","admin/tripal/tripal_gbrowse/add_tracks"). "</li>";
-  $text .= "<li>".l("Delete Tracks","admin/tripal/tripal_gbrowse/delete_tracks"). "</li>";
-
-   
-   $text .= "</ul>";
- 
-  $text .= '<h3>Module Description:</h3>';
-  $text .= '<p>This module provides an interface to register already existing GBrowse instances with Drupal/Tripal and/or create new '
-            .'GBrowse Instances. Furthermore, it allows basic management of these GBrowse instances including un-registering and/or '
-            .'deleting and loading of features in Tripal/Chado into a MySQL GBrowse instance. As such, it provides interoperability '
-            .'and syncronization between a Tripal/Chado installation and GBrowse</p>';
-
-  $text .= '<h3>Setup Instructions:</h3>';
-  $text .= '<ol>';
-  $text .= '<li><b>Ensure the PHP-MySQL extension is installed:</b> Installation instructions are dependant upon your operating system.</li>';
-  $text .= '<li><b>Move Template Configuration File:</b> Move the template.conf file included with this module into the GBrowse configuration file directory.</li>';
-    $text .= '<li><b>Set GBrowse Instance Defaults :</b> Set default repository for Configuration files, also set the default GBrowse web link address.</li>'
-						.'<a href="tripal_gbrowse/configuration">Administration -> Tripal Management -> GBrowse Management -> Configuration</a>.</li>';
-  
-  $text .= '<li><b>Register Existing GBrowse Instances</b>: Register any existing GBrowse instances through the form provided at '
-            .'<a href="tripal_gbrowse/register_gbrowse">Administration -> Tripal Management -> GBrowse Management -> Register GBrowse Instance</a>.</li>';
-  $text .= '<li><b>Load desired Feature Libraries into GBrowse Instances</b>: Additional feature libraries should be loaded through the form provided at '.l('Administration -> Tripal Management -> GBrowse Management -> Load Features','admin/tripal/tripal_gbrowse/load_features').'</li>';
-  $text .= '<ol>';
-  
-  $text .= '<h3>Features of this Module:</h3>';
-    $text .= '<ul>';
-      $text .= '<li><b>Register GBrowse Instance:</b> In order to load features into a GBrowse instance you need to first register it with Tripal/Drupal. Any existing '
-                .'GBrowse instance that utilizes a MySQL database can be registered with the module. Furthermore, you can create new GBrowse Instances '
-                .'through this module by selecting that option in the register GBrowse Instance form. This'
-                .'newly created GBrowse instance uses a MySQL database with is created and '
-                .'a user name and password is setup and a default configuration file is created. Finally, the database is initialized and the first sequence '
-                .'set is loaded into the GBrowse instance.</li>';
-    
-      $text .= '<li><b>Un-Register/Delete GBrowse Instance:</b> Un-registering a GBrowse instance alone will remove the GBrowse instance from the Drupal site.'
-                .'When removing the entire instance, the database and the configuration file will be deleted. This cannot be undone!</li>';
-    	
-    	$text .='<li><b>Intergrated GBrowse Node/Page:</b> Allows users to easily access GBrowse instances that have been created.' 
-    						.'This module provides details for a registered GBrowse Instance, including an I-Frame, providing instance access to the GBrowse display,' 
-    						.'as well,the module provides a link to a GBrowse instance in a new window.</li>';
-    
-      $text .= '<li><b>Load Library Features:</b> Simply by selecting a Tripal Library and a GBrowse Instance, '
-              .'the features associated with the selected Library are loaded into the selected GBrowse Instance. Libraries can also be updated by selecting that option. This removes all of the pre-existing'
-              .'features associated with that library, then reloades them. Both loading and updating utilize the Perl script "bp_seqfeature_load.pl" which should be installed when you install GBrowse.</li>';
-    
-    	$text .= '<li><b>Load Analysis Features:</b> Simply by selecting a Tripal Analysis and a GBrowse Instance, '
-              .'the analyses associated with the selected Library are loaded into the selected GBrowse Instance. Analyses can also be updated by selecting that option. This removes all of the pre-existing'
-              .'features associated with that analysis, then reloades them. Both loading and updating utilize the Perl script "bp_seqfeature_load.pl" which should be installed when you install GBrowse.</li>';
-    
-      $text .= '<li><b>Delete Feature (Libraries) Libraries:</b> A user can select a desired Tripal Library and a specific GBrowse instance and all of the features associated with that library in the selected isntance are removed.'
-              .' This section uses the Perl "script bp_seqfeature_delete.pl" to delete the specified features.</li>';
-      $text .= '<li><b>Delete (Libraries) Analysis :</b> A user can select a desired Tripal Analysis  and a specific GBrowse instance and all of the features associated with that analysis in the selected isntance are removed.'
-              .' This section uses the Perl "script bp_seqfeature_delete.pl" to delete the specified features.</li>';
-              
-      $text .= '<li><b>Add Tracks:</b> Allows a user to add tracks to a given GBrowse instance. This allows them to define exactly how they want their features to be displayed, as well as, to separate their features into their own GBrowse track.</li>';
-      
-      $text .= '<li><b>Delete Tracks:</b> Allows a user to delete default tracks or user created  tracks for a given GBrowse instance.</li>';
-              
-  $text .= '</ul>';
-  
-  return $text;
-}
-
-
-/**
- *  Implements hook_job_describe_args()
- *
- *  This function modifies the Job Arguments page and represents the job arguments with
- *  meaningfull descriptive names, sends a link to the library and shows if the database  
- *  was cleared or not.
- *
- *  @param $call_back
- *    The name of the function being called by tripal_jobs
- *
- *  @param $args
- *    The arguments that are passed, given if the selected proccess is 
- *				1-'tripal_gbrowse_delete_library_features_from_gbrowse'
- *				2-'tripal_gbrowse_load_library_features_into_gbrowse'*				
- *				3-'tripal_gbrowse_delete_analysis_features_from_gbrowse'
- *				3-'tripal_gbrowse_load_analysis_features_into_gbrowse'
- *    If 1- then the arguments are based on deleting a library feature from GBrowse.
- *    If 2- then the arguments are based on loading library features into GBrowse.
- *    If 3- then the arguments are based on deleting a analysis feature from GBrowse.
- *    If 4- then the arguments are based on loading analysis features into GBrowse.
- *
- * @return
- *     Job arguments:Database name, user Name, Password, Library ID, If GBrowse database was cleared, 
- *    to be displayed in Job Details page. 
- */
-function tripal_gbrowse_job_describe_args($call_back, $args){
-
-  switch ($call_back){
-  
-    case 'tripal_gbrowse_delete_library_features_from_gbrowse':
-        
-        $new_args['GBrowse Database Name']=$args[0];
-        
-        $new_args['User Name']=$args[1];
-        
-        $new_args['Password']=$args[2];
-        $result = db_fetch_object(db_query("SELECT nid FROM chado_library WHERE library_id=%d",$args[3]));
-        
-        $node = node_load($result->nid);
-        
-        $new_args['Library']= l($node->title, 'node/'.$result->nid);
-        
-          if(empty($args[4])){
-            $new_args['Clear GBrowse Database']= 'No';
-          }else{
-            $new_args['Clear GBrowse Database']= 'Yes';
-          }
-      
-        break;
-  
-    case 'tripal_gbrowse_load_library_features_into_gbrowse':
-        
-        $new_args['GBrowse Database Name']=$args[0];
-        
-        $new_args['User Name']=$args[1];
-        
-        $new_args['Password']=$args[2];
-        
-        $result = db_fetch_object(db_query("SELECT nid FROM chado_library WHERE library_id=%d",$args[3]));
-        
-        $node = node_load($result->nid);
-        
-        $new_args['Library']= l($node->title, 'node/'.$result->nid);
-        
-          if(empty($args[4])){
-            $new_args['Clear GBrowse Database']= 'No';
-          }else{
-            $new_args['Clear GBrowse Database']= 'Yes';
-          }
-      
-        break;
-        
-  case 'tripal_gbrowse_delete_analysis_features_from_gbrowse':
-        
-        $new_args['GBrowse Database Name']=$args[0];
-        
-        $new_args['User Name']=$args[1];
-        
-        $new_args['Password']=$args[2];
-        $result = db_fetch_object(db_query("SELECT nid FROM chado_analysis WHERE analysis_id=%d",$args[3]));
-        
-        $node = node_load($result->nid);
-        
-        $new_args['Analysis']= l($node->title, 'node/'.$result->nid);
-        
-          if(empty($args[4])){
-            $new_args['Clear GBrowse Database']= 'No';
-          }else{
-            $new_args['Clear GBrowse Database']= 'Yes';
-          }
-      
-        break;
-  
-  case 'tripal_gbrowse_load_analysis_features_into_gbrowse':
-        
-        $new_args['GBrowse Database Name']=$args[0];
-        
-        $new_args['User Name']=$args[1];
-        
-        $new_args['Password']=$args[2];
-        
-        $result = db_fetch_object(db_query("SELECT nid FROM chado_analysis WHERE analysis_id=%d",$args[3]));
-        
-        $node = node_load($result->nid);
-        
-        $new_args['Analysis']= l($node->title, 'node/'.$result->nid);
-        
-          if(empty($args[4])){
-            $new_args['Clear GBrowse Database']= 'No';
-          }else{
-            $new_args['Clear GBrowse Database']= 'Yes';
-          }
-      
-        break;
-  
-  }
-
-  return $new_args;
-
-}
-
-
-//-----------------------------------------------------------------------------
-//  SECTION: Database API
-//-----------------------------------------------------------------------------
-
-
-/**
- * The purpose of this function is to retrieve the previousley loaded libraries from database.
- *
- * @param $gbrowse
- *   A GBrowse instance that contains the information of the current instance	
- *
- * @return 
- * 	An array of libraries that have been loaded into the database
- */
-function tripal_gbrowse_getloaded_sources($gbrowse){
-
-  $loaded_libraries = array();
-	
-	$link = mysql_connect('localhost', $gbrowse->database_user, $gbrowse->user_password);
-	
-	if (!$link) {
-		drupal_set_message('Could not connect to database: ' . mysql_error(), 'error');
-	}
- 
-	//Sending query to the database
-	$resource = mysql_query('use ' .$gbrowse->database_name);
-	
-	if (empty($resource)) {
-		drupal_set_message ('Database is empty or Non-existent','error');
-	}
-	
-	$resource = mysql_query('select * from typelist');
-	
-	if (empty($resource)) {
-		drupal_set_message ('Missing table typelist in database. Check sequence backbone has been loaded (Execute: tripal jobs) ','error');
-	}  else {
-	
-		$library_array = array();
-		
-		while($record = mysql_fetch_object($resource)){
-				preg_match('/^[^:]+:(.+)/', $record->tag, $matches);	
-				$library_array[$matches[1]]= $matches[1];
-		}
-	}
-	mysql_close($link);
-
-	return $library_array;
-
-}
-
-
-/**
- * The purpose of this function is to firstly create a file for backup purposes. Secondly, this
- * function uses a 'mysqldump' the contents of the selected database to a backup file. It then
- * access the database, drops the old database, creates a new one with the modified infromation,
- * then uploads the previously backed up infromation into the newly created database.
- * 
- *
- *  @param $node
- *    A node object containing the data and infromation of the GBrowse instance
- *
- *  @param $old_database
- *    The name of the originally created database, which will be replaced if the user
- *	  changes the name of the database that they have created
- *
- *  @return FALSE
- *    If error in creating database, or creating database, else nothing is returned
- */
-function tripal_gbrowse_database_modification($node,$old_database){
-		
-  global $user;
-		
-	$user_name = $node->database_user;
-		
-	$user_password = $node->user_password;
-		
-	//creating a file in the /tmp directory for back-up purposes
-	$back_upfile = '/tmp/' .$old_database .'_'.time().'.sql';
-	
-	//Using the 'mysqldump' command to dump the database for backup purposses
-	$command = 'mysqldump -u' .$user_name .' -p' .$user_password .' ' .$old_database .' > ' .$back_upfile;
-		
-	exec($command);
-		
-	//To create a database use the mysql_query() function to execute an SQL query
-	$link = mysql_connect('localhost', $user_name,$user_password);
-			
-	//Link operation verification
-	if (!$link) {      
-		drupal_set_message('Could not connect: ' . mysql_error(), 'error');
-		return false;
-	}
-
-	//Dropping original database name and information
-	$sql = 'DROP DATABASE ' . $old_database;
-			
-	if(mysql_query($sql, $link)){
-		drupal_set_message( "Database Dropped Successfully\n");
-	}else{
-		drupal_set_message( 'Error Dropping Database: ' . mysql_error(), 'error');
-		return false;
-	}
-
-	$sql = 'CREATE DATABASE ' . $node->database_name;
-
-	if (mysql_query($sql, $link)) {
-		drupal_set_message( "Database Created Successfully\n");
-	} 
-	else {
-		drupal_set_message( 'Error Creating Database: ' . mysql_error() . "\n");  
-		return false;
-	}
-
-	mysql_query( "GRANT SELECT ON " .$node->database_name.".* TO 'www-data'@'localhost'",$link);
-	
-	$command = 'mysql -u' .$user_name .' -p' .$user_password .' ' .$node->database_name .' < ' .$back_upfile;
-	
-	exec($command);
-	
-	mysql_close($link);
-	
-}
-
-
-//-----------------------------------------------------------------------------
-//  SECTION: Node Capability
-//-----------------------------------------------------------------------------
-
-
-/**
-* Implementation of hook_tripal_gbrowse_node_info()
-*
-* This node_info, is a simple node that describes the functionallity of the module. It specifies
-* that the title(gbrowse Name) and body(Description) set to true so that they information can be
-* entered
-*
-*/
-function tripal_gbrowse_node_info() {
-  return array(
-    'tripal_gbrowse' => array(
-      'name' => t('GBrowse Instance'),
-      'module' => 'tripal_gbrowse',
-      'description' => t('A module for interfacing the GMOD database with Drupal, providing:
-      Registration,Alteration and Deletion of GBrowse Instances,Configuration Files and Databases
-      and the option to load/delete Sequence & Analysis Libraries'),
-    	'has_title' => TRUE,
-    	'title_label' =>t('gbrowse Name'),
-    	'had_body' => FALSE,
-    )
-  );
-}
-
-
-/**
-* Implementation of tripal_gbrowse_form().
-*
-*  This form takes the gbrowse Title infromation and the gbrowse description from the user. It 
-*  then puts the infromation into the Chado_gbrowse database table.
-*
-*  @parm &$node
-*    The node that is created when the database is initialized
-*
-*  @parm $form_state
-*    The state of the form, that has the user entered information that is neccessary for, setting
-*    up the database of the gbrowse
-*
-*  @return $form
-*    The information that was enterd allong with   
-*
-*/
-function tripal_gbrowse_form(&$node, $form_state) {
-  
-  $type = node_get_types('type', $node);
-
-  //Creating Fieldset for multiple fields in form
-  $form['register_gbrowse'] = array(
-    '#type' => 'fieldset',
-    '#title' => t('Data Base Specific Fields'),
-  );
-  
-   //field for the name of the database
-   $form['register_gbrowse']['database_name'] = array(
-    '#type' => 'textfield',
-    '#title' => t('GBrowse Database Name'),
-    '#size' => 30,
-    '#maxlength' => 64,
-    '#description' => t('Desired Database Name Field'),
-    '#default_value' => isset($node->gbrowse->database_name) ? $node->gbrowse->database_name : '',
-    '#required' => TRUE,
-  );
-  
-   //User of database 
-   $form['register_gbrowse']['database_user'] = array(
-    '#type' => 'textfield',
-    '#title' => t('GBrowse User'),
-    '#size' => 30,
-    '#maxlength' => 64,
-    '#description' => t('GBrowse MySQL User Field'),
-    '#default_value' => isset($node->gbrowse->database_user) ? $node->gbrowse->database_user : '',
-    '#required' => TRUE,
-  );
-  
-   //Specified password for access to database 
-   $form['register_gbrowse']['user_password'] = array(
-    '#type' => 'password',
-    '#title' => t('Password'),
-    '#size' => 30,
-    '#maxlength' => 64,
-    '#description' => t('User Password Field'),
-    '#default_value' => isset($node->gbrowse->user_password) ? $node->gbrowse->user_password : '',
-    '#required' => TRUE,
-  );
-  
-   //Creating Fieldset for multiple fields in form
-   $form['gbrowse_details'] = array(
-     '#type' => 'fieldset',
-     '#title'=>'GBrowse Specifications' ,
-   );
-  
-   //Human-readable name for the gbrowse instance 
-   $form['gbrowse_details']['title'] = array(
-    '#type' => 'textfield',
-    '#title' => t('GBrowse Name'),
-    '#size' => 30,
-    '#maxlength' => 256,
-    '#description' => t('GBrowse Instance'),
-    '#default_value' => isset($node->gbrowse->gbrowse_name) ? $node->gbrowse->gbrowse_name : '',
-    '#required' => TRUE,
-  );
-  
-   //$_SERVER: takes the current url and sets to variable
-   $default_value = variable_get('tripal_gbrowse_gbrowse_address_stub', '');
-    
-   //Link to the gbrowse instance
-   $form['gbrowse_details']['gbrowse_link'] = array(
-    '#type' => 'textfield',
-    '#title' => t('GBrowse Link'),
-    '#size' => 30,
-    '#maxlength' => 256,
-    '#description'=>t('Enter Full HTML address Including Host 
-    (ex:http://knowpulse2.usask.ca/) of the new GBrowse instance. By default this is '.$default_value.'[configuration file name] where the configuration file name is the same as that entered below except without .conf'),
-    '#default_value' => isset($node->gbrowse->gbrowse_link) ? $node->gbrowse->gbrowse_link : $default_value,
-    '#required' => TRUE,
-  );
-
-  //Fully qualified location to the gbrowse configuration file 
-   $form['gbrowse_details']['config_file'] = array(
-    '#type' => 'textfield',
-    '#title' => t('Configuration File'),
-    '#size' => 30,
-    '#maxlength' => 256,
-    '#description' => t('Enter Fully Qualified File Name including Path (ex: file.conf) '),
-    '#default_value' => isset($node->gbrowse->config_file) ? $node->gbrowse->config_file : variable_get('tripal_gbrowse_configuration_file_path', ''),
-    '#required' => TRUE,
-  );
-  
-  $result = tripal_core_chado_select ( 'library', array('library_id','name'), array() );
-
-  foreach ($result as $value) {
-  
-    $newArray[$value->library_id]=$value->name;        //options for the select list
-	
-	}
-	
-	if (!$node->gbrowse->gbrowse_id) {
-	
-	 		// Creating Fieldset for multiple fields in form
-  		$form['create_instance'] = array(
-    		'#type' => 'fieldset',
-    		'#title' => t('Create New GBrowse Instance'),
-  		);
-	
-		if(empty($newArray)){
-		
-			drupal_set_message('There are currently no libraries to load.','error');
-		
-			$form['create_instance']['check_box'] = array(
-				'#type' => 'item',
-				'#value'=>'A GBrowse instance can not be created without a valid loadable backbone. 
-				To make a valid loadable backbone available, please load features grouped in a library using 
-				any of the feature loaders available.'
-			);
-		
-		
-		}else { 
-		
-			//A box if checked creates GBrowse Instances if they do not exist
-			$form['create_instance']['check_box'] = array(
-				'#type' => 'checkbox',
-				'#title' => t('Create Instance'),
-				'#description' => t('Create GBrowse Instane Unless Previous Existance'),
-			);
-		
-				//Library ID
-				$form['create_instance']['library_id'] = array(
-					'#type' => 'select',
-					'#title' => t('Sequence BackBone'),
-					'#options' => $newArray,
-					'#description' => t('Sequence Features Locations'),
-				);
-		}
-	
-	}
-	
-  return $form;
-  
-}
-
-function tripal_gbrowse_validate ($node, $form) {
-
-  if (!preg_match('/\.conf$/',$node->config_file)) {
-    form_set_error('config_file','Configuration file must end in .conf');
-  }
-  
-  if (!preg_match('/^http:\/\//',$node->gbrowse_link)) {
-    form_set_error('gbrowse_link','GBrowse Link must be an absolute path (include http://)');
-  }
-}
-
-/**
- *  Implements tripal_gbrowse_help()
- *
- *  This function simply states, in HTML tags, the creator of the the module and the contact	
- *  for the programmer
- *
- *  @parm $path
- *    The absolute path of the module and help information
- *
- *  @parm $arg
- *    The argument
- */
-function tripal_gbrowse_help($path, $arg) {
-  switch ($path) {
-    
-    case 'admin/help#tripal_gbrowse':
-      
-      return '<p>'. t('Module created by:Chad Krilow (e-mail:cnk046@mail.usask.ca)') .'</p>';
-			
-			break;
-  }
-}
-
-
-/**
- * Implements hook_perm()
- *
- *  This function sets the permission for the user to access the information in the database.
- *  This includes creating, inserting, deleting and updating of information in the database
- *
- */
-function tripal_gbrowse_perm(){
-
-  return array('create tripal_gbrowse', 'edit own tripal_gbrowse', 'access database-related details' ,'access tripal_gbrowse content');
-
-}
-
-
-/**
- * Implements tripal_gbrowse_access()
- *
- *  This function sets the access permission for operations on the database.
- *  
- *
- *  @parm $op
- *    The operation that is to be performed
- *
- *  @parm $node
- *    The specific node that is to have the operation performed  
- *
- *  @parm $account
- *    The account of the user that is performing the operations  
- *
- *  @return
- *    True if a operation was performed
- *
- */
-function tripal_gbrowse_access($op, $node, $account) {
-
-  if($op == 'create') {
-    // Only users with permission to do so may create this node type.
-    if(!user_access('create tripal_gbrowse', $account)){
-       return FALSE;
-    }  
-  }
-
-  // Users who create a node may edit or delete it later, assuming they have the
-  // necessary permissions.
-  if($op == 'update' || $op == 'delete') {   
-    if(!user_access('edit own tripal_gbrowse',$account)){
-       return FALSE;
-    } 
-    if(user_access('edit own tripal_gbrowse',$account) && 
-       $account->uid != $node->uid){
-      return FALSE;
-    }
-  }
-  return NULL;
-}
-
-
-/**
-* Implementation of tripal_gbrowse_insert()
-*
-* This function inserts user entered information pertaining to the GBrowse instance into the
-* 'tripal_gbrowse_instances' talble of the database, requiring that a 'Check Box' has been selected.
-*
-*  @parm $node
-*    Then node which contains the information stored within the node-ID
-*
-*
-*
-*/
-function tripal_gbrowse_insert($node) {
-		
-  $values = array(
-    'database_name'=> $node->database_name,
-    'database_user'=> $node->database_user,
-    'user_password'=> $node->user_password,
-    'gbrowse_name'=> $node->title,
-    'gbrowse_link'=> $node->gbrowse_link,
-    'config_file'=> $node->config_file,
-    'library_id'=>$node->library_id,
-    'nid'=>$node->nid,
-    'vid'=>$node->vid,
-   );
-  
-  //used to write to a database table described by Drupal Schema (not workable for chado)
-  drupal_write_record('tripal_gbrowse_instances', $values);
-  
-  if($node->check_box==1){
-  	tripal_gbrowse_create_gbrowse_instance($values);
-	}else{
-		drupal_set_message("Create instance check box not selected, unable initialize instance");
-	}
-	
-}
-
-
-/**
-* Implementation of tripal_gbrowse_delete().
-*
-* This function takes a node and if the variable 'tripal_gbrowse_delete_all' has been defined,
-* the GBrowse instance pertaining to the node passed into the function is deleted. Following,
-* given the node-ID, the instance will be deleted from the 'tripal_gbrowse_instances' table.
-*
-*
-*  @parm $node
-*    Then node which contains the information stored within the node-ID
-*
-*/
-function tripal_gbrowse_delete($node){
-  
- 	if(variable_get('tripal_gbrowse_delete_all', '')){ 
- 		tripal_gbrowse_delete_gbrowse_instance($node->gbrowse);
- 	}
- 	
- 	//deleteing in drupal chado_gbrowse table
-  db_query('DELETE FROM {tripal_gbrowse_instances} WHERE nid = %d', $node->nid);
-	
-}
-
-
-/*
-*
-* Implements hook_update
-*
-* The purpose of the function is to allow the module to take action when an edited node is being 
-* updated in the database. It also updates any name changes to the configuration file that was
-* created upon registering a GBrowse instance. This is done by moving the contents of the original 
-* configuration file to the newly named file.As well, the database will be changed, if the name
-* is altered by a registered user.If this is the case, the function 'tripal_gbrowse_database_modification'
-* is called and the node and the old database infromation is passed, so as it may be altered and updated
-* accordingley.
-*
-* @param $node 
-*   The node being updated
-*
-*/
-function tripal_gbrowse_update($node){
-	
-	//select from table before doing this, cause i wont be able to see the old details afterwards	
-	$old_data = db_fetch_object(
-  db_query('SELECT database_name,config_file FROM {tripal_gbrowse_instances} WHERE nid=%d AND vid=%d',
-	$node->nid, $node->vid));
-	
-	$old_config_file=$old_data->config_file;
-	
-	$old_database_name=$old_data->database_name;
-		
-	$match= array(
-		  'nid',
-		  'vid',
-	);
-	
-	$values =  array(
-    'database_name'  => $node->database_name,
-    'database_user'  => $node->database_user,
-    'user_password'  => $node->user_password,
-    'gbrowse_name'  => $node->gbrowse_name,
-    'gbrowse_link' => $node->gbrowse_link,
-    'config_file' => $node->config_file,
-    'library_id'=>$node->library_id,
-    'nid' => $node->nid,
-    'vid' => $node->vid,
-  );
-  
-  //Pulling out the configuration file
-  $config_file = $node->config_file;
-    
-  if(strcmp($old_config_file, $config_file)!=0){
-  	//Removing configuration file from the directory
-  	$command = "mv " .$old_config_file ." ".$config_file;
-  	exec($command);
-	}
-
-	if($old_database_name != $node->database_name){
-    tripal_gbrowse_database_modification($node,$old_database_name);
-	}		
-
-	drupal_write_record('tripal_gbrowse_instances', $values, $match);
-
-}
-
-
-/**
-* Implementation of tripal_gbrowse_load().
-*
-*
-* @param $node
-*   The node that is to be accessed from the database
-*
-* @return $node
-*   The node with the information to be loaded into the database 
-*
-*/
-function tripal_gbrowse_load($node) {
-	
-	$result = db_fetch_object(db_query('SELECT gbrowse_id,database_name,database_user,user_password,
-	gbrowse_name,gbrowse_link,config_file FROM {tripal_gbrowse_instances} WHERE nid=%d AND vid=%d',$node->nid, $node->vid));
-	
-  $node->gbrowse = $result;
-	
-  return $node;
-}
-
-
-//-----------------------------------------------------------------------------
-//  SECTION: Configuration form
-//-----------------------------------------------------------------------------
-
-
-/**
-* Implemets hook_menu(): Adds menu items for the tripal_gbrowse module
-*
-* This form creates a specific Configuration File directory and sets a specific
-* GBrowse web address for later access 
-*
-* @return
-*   An array of menu items '$form' 
-*/
-function tripal_gbrowse_administration_form () {
- 
-  //Creating Fieldset for multiple fields in form
-  $form['configuration_features'] = array(
-    '#type' => 'fieldset',
-    '#title' => t('Module Configuration Fields'),
-  );
- 
-  //Configuration File Directory
-  $form['configuration_features']['configuration_file'] = array(
-    '#type' => 'textfield',
-    '#title' => t('Set Default Configuration File Directory'),
-    '#size' => 30,
-    '#maxlength' => 64,
-    '#description' => t('Specific Configuration File Directory'),
-    '#default_value' => variable_get('tripal_gbrowse_configuration_file_path', ''),
-  );
-  
-  //GBrowse Web Address
-  $form['configuration_features']['gbrowse_address'] = array(
-    '#type' => 'textfield',
-    '#title' => t('Set Default GBrowse Web Address'),
-    '#size' => 30,
-    '#maxlength' => 64,
-     '#description' => t('Desired GBrowse web address'),
-     '#default_value' => variable_get('tripal_gbrowse_gbrowse_address_stub', ''),
-  );
-  
-  //A box if checked creates GBrowse Instances(.conf file and database)
-	$form['configuration_features']['delete_check_box'] = array(
-		'#type' => 'checkbox',
-		'#title' => t('Delete Instance'),
-		'#description' => t('Delete GBrowse Configuration file and Database  '),
-		'#default_value'=>variable_get('tripal_gbrowse_delete_all', ''),	
-	);
-
-  $form['configuration_features']['submit'] = array(
-    '#type' => 'submit', 
-    '#weight' => 10,
-    '#value' => t('Submit')
-  );
- 
-  return $form;
-}
-
-
-/**
- * Validate User-submitted data for Register GBrowse Instances Form
- *
- * This function validates the user input for each form element in the Register GBrowse 
- * instances form that is a text field. Validations checked include:
- *    -parse_url-checks that the url can be parsed
- *
- * @param $form
- *   The form that the user submitted and whose input is being validated
- * @param $form_state
- *   An array containing the state of the form being validated including user-input
- */
-function tripal_gbrowse_administration_form_validate ($form, $form_state) {
-  
-  if ( !valid_url($form_state['values']['gbrowse_address'])) {
-    form_set_error('gbrowse_address', 'Invalid URL');
-  }
-}
-
-
-/**
-*
-* Configuration-Form
-*
-* @param $form
-*    -The submitted form containing the user entered infromation
-* @param $form_state 
-*    -Is the state of the form: i.e what button was pressed, what infromation was entered,etc.
-*    The key is the 'values'
-*/
-function tripal_gbrowse_administration_form_submit ($form, $form_state) {
-
-  if(!preg_match('/\/$/', $form_state['values']['configuration_file'])) {
-      $form_state['values']['configuration_file'] = $form_state['values']['configuration_file'] . "/";
-  }
-
-  variable_set('tripal_gbrowse_configuration_file_path',$form_state['values']['configuration_file'] );
-  drupal_set_message('Configuration File Path set to: '.variable_get('tripal_gbrowse_configuration_file_path', ''));
-    
-        
-  variable_set('tripal_gbrowse_gbrowse_address_stub',$form_state['values']['gbrowse_address'] );
-  drupal_set_message('GBrowse Default Address set to: '.variable_get('tripal_gbrowse_gbrowse_address_stub', ''));
-  
-  if($form_state['values']['delete_check_box']==1){									
-  	variable_set('tripal_gbrowse_delete_all',$form_state['values']['delete_check_box'] );
-  	drupal_set_message('Selected GBrowse instance will be deleted: '.variable_get('tripal_gbrowse_delete_all', 'NOT SET'));
-  }
-
-}
-
-
-//-----------------------------------------------------------------------------
-//  SECTION: Register-GBrowse-Instance 
-//-----------------------------------------------------------------------------
-
-
-/**
-*
-* Register & Create GBrowse instance ( called by the node form )
-*
-* This form submit takes it's fields from the form for registering a GBrowse instance. The 'sed'command
-* is used to select certain lines of a template 'conf' file and replaces them with the user specified GBrowse instance
-* and data base name. It then removes the temporary file that was created. This function utilizes the MySQL database
-* and uses the commands for MySQL to create a database for the registered GBrowse instance, appropriate warnings
-* are issued if there are problems connecting/registering/accessing the database.
-*
-* @param $form
-*    -The submitted form containing the user entered infromation
-*
-* @param $form_state 
-*    This is the state of the form: i.e what button was pressed.The key is 
-*    the name of the fields in database 
-*
-*/
-function tripal_gbrowse_create_gbrowse_instance($values) {
-    
-    global $user;    //make current user details available so access of user id is available 
-        
-  //checking for existance of configuration file, if allready created a warning is issued
-	if ( file_exists($values['config_file']) ){
-		drupal_set_message('Configuration File Already Exists', 'warning');
-	}else{ 
-	
-		$config_path = variable_get('tripal_gbrowse_configuration_file_path', '');
-		
-		if(empty($config_path)){   
-			drupal_set_message( "Invalid or Non-Existent Configuration Path (Check Configuration Menu Defaults)", 'error');
-		}
-				
-		$temp_file = '/tmp/temporary_gbrowse_'.time().'.conf';
-		
-		// Using 'sed' to select the second line of the template.config substitute <#gbrowse_name>
-		//for .$values['gbrowse_name'] 
-		$command = "sed '2 s/<#gbrowse_name#>/".$values['gbrowse_name']."/' ".$config_path."template.conf > ".$temp_file; 
-
-		exec($command);
-		
-		// Using 'sed' to select the fifth line of the template.config substitute <#database_name>
-		//for .$values['database_name']
-		 $command = "sed '5 s/<#database_name#>/".$values['database_name']."/' ".$temp_file." > ".$values['config_file'];
-
-		exec($command);
-		
-		// Check configuration file is there
-		if (file_exists($values['config_file'])) {
-			drupal_set_message('Configuration File created successfully');
-		} else {
-			drupal_set_message('Unable to create configuration file','error');
-		}
-
-		//To create a database use the mysql_query() function to execute an SQL query
-		$link = mysql_connect('localhost', $values['database_user'],$values['user_password']);
-	
-		if (!$link) {
-			drupal_set_message('Could not connect: ' . mysql_error());
-			return false;
-		}
-
-		$sql = 'CREATE DATABASE ' . $values['database_name'];
-
-		if (mysql_query($sql, $link)) {	
-			drupal_set_message( "Database created successfully\n");
-		} else {
-			drupal_set_message( 'Error creating database: ' . mysql_error() . "\n");
-			return false;
-		}
-	
-		mysql_query( "GRANT SELECT ON " .$values['database_name'].".* TO 'www-data'@'localhost'",$link);
-								
-		mysql_close($link);
-
-		$job_args=array($values['database_name'],$values['database_user'],$values['user_password'],$values['library_id'],TRUE);
-			
-		//registering a job with the tripal system, this job calls the function when executed
-		$job_id = tripal_add_job('Loading Features Into GBrowse', 'tripal_gbrowse','tripal_gbrowse_load_library_features_into_gbrowse', $job_args, $user->uid);
-
-		drupal_set_message(' The Backbone needs to be loaded into GBrowse (done by executing Tripal Jobs Loading script), 
-		Before loaded libraries or GBrowse Instance will be displayed. ');
-
-  	}
-  
-}
-
-
-//-----------------------------------------------------------------------------
-//  SECTION: Un-Register Existing GBrowse Instances
-//-----------------------------------------------------------------------------
-
-
-/**
-* Un-Register GBrowse Instance Form Submit
-*
-* This is the Form-Submit section of the Un-Register GBrowse instance function. Depending on 
-* which instance was selected, it will be removed from the database. A check box is provided
-* which, if checked is true, will delete all data/files that was associated with the selected
-* GBrowse instance.SQL commands are used in order to remove the selected instances from the 
-* SQL database.
-*
-* @param $form
-*    the submitted form containing the user entered infromation
-* @param $form_state 
-*    The state of the form: i.e if check-box was checked and what gbrowse_instance was selected to be deleted
-*    The key is the 'values'
-*
-* @return
-*    true or false, depending wheater the check box had been selected, if true, the 
-*   selected GBrowse instance will be deleted
-*/
-function tripal_gbrowse_delete_gbrowse_instance($gbrowse) {
-    
-  // Retrieve current gbrowse instance details
-  $gbrowse_instance = db_fetch_object(
-  db_query('SELECT * FROM {tripal_gbrowse_instances} WHERE gbrowse_id=%d', $gbrowse->gbrowse_id )
-  );
-     
-    //Pulling out the configuration file
-    $config_file = $gbrowse->config_file;
-      
-    //Removing configuration file from the directory
-    $command = "rm ".$config_file;
-
-    exec($command);
-    
-    if (file_exists($config_file)) {
-      drupal_set_message('Configuration File ('.$config_file.') not removed!', 'error');
-    } else {
-      drupal_set_message('Configuration File removed successfully');
-    }
-      
-    $user_name = $gbrowse->database_user;
-    
-    $user_password = $gbrowse->user_password;
-
-    $link = mysql_connect('localhost', $user_name,$user_password);
-      
-    if (!$link) {     
-      drupal_set_message('Could not connect: ' . mysql_error(), 'error');
-      return false;
-    }
-
-    $sql = 'DROP DATABASE ' . $gbrowse->database_name;
-      
-    if(mysql_query($sql, $link)){    
-      drupal_set_message( "Database removed successfully\n"); 
-    }else{
-      drupal_set_message( 'Error removing database: ' . mysql_error(), 'error');
-      return false;
-    }
-      
-    mysql_close($link);
-  
-}
-
-
-//-----------------------------------------------------------------------------
-//  SECTION: Load Library features into GBrowse Form & Form Submit
-//-----------------------------------------------------------------------------
-
-
-/**
-* Implements hook_form
-*
-* This function creates a form for the database name, user name for database operation and a 
-* password for access.The module uses these features to access information regarding the user's 
-* operations and needs.
-*
-* @return
-*   An array describing the form to be rendered
-*/
-function tripal_gbrowse_load_library_features_form() {
- 
-  $new_array=array();
-   
-  $result = tripal_core_chado_select ( 'library', array('library_id','name'), array() );
-  
-  foreach ($result as $value) {
-    $new_array[$value->library_id]=$value->name;        //options for the select list
-  }
-  
-  //Creating Fieldset for multiple fields in form
-  $form['load_features'] = array(
-    '#type' => 'fieldset'
-  );
- 
-  //Library ID
-  $form['load_features']['library_id'] = array(
-      '#type' => 'select',
-      '#title' => t('Libraries'),
-      '#options' => $new_array,
-      '#description' => t('Library of Genetic Sequences.'),
-  );
-    
-  //Sending query to the database
-  $resource = db_query('SELECT * FROM {tripal_gbrowse_instances}');
-
-    $items = array();
-  
-    while($record = db_fetch_object($resource)){
-      $items[$record->gbrowse_id]= $record->gbrowse_name;
-    }
-   
-  //GBrowse Instances
-  $form['load_features']['gbrowse_id'] = array(
-    '#type' => 'select',
-    '#title' => t('GBrowse Instances'),
-    '#options' => $items,
-    '#description' => t('Selected GBrowse Instances to be Loaded.'),
-  );
-    
-  //A checkbox to update features for the gbrowse
-  $form['load_features']['check_box'] = array(
-    '#type' => 'checkbox',
-    '#title' => t('Update Features'),
-    '#description' => t('Existing Same Name Features Updated Accordingly.'),
-  );
-
-  $form['load_features']['submit'] = array(
-   '#type' => 'submit', 
-   '#weight' => 10,
-   '#value' => t('Submit Job')
-   );
-  
-  return $form;
-}
-
-
-/**
-* Load-Features-Form
-*
-* @param $form
-*    -The submitted form containing the user entered infromation
-* @param $form_state 
-*    -Is the state of the form: i.e what button was pressed, what infromation was entered,etc.
-*    The key is the 'values'
-*/
-function tripal_gbrowse_load_library_features_form_submit($form,$form_state) {
-    
-	global $user;    //needed to make the current users details available so access of user id is available 
-				
-	$record = db_fetch_object(db_query('SELECT * FROM {tripal_gbrowse_instances} WHERE gbrowse_id=%d', $form_state['values']['gbrowse_id']));
-	
-	$name = $record->database_name;
-
-	$user_name = $record->database_user;
-
-	$password= $record->user_password;
-
-	$job_args = array($name,$user_name,$password,$form_state['values']['library_id'], FALSE);   
-								
-	//Checking state of check box, if checked delete features from GBrowse
-	if($form_state['values']['check_box']==1){
-		//registering a delete job with the tripal system, this job calls the function when executed
-			$job_id = tripal_add_job('Deleting Features From GBrowse', 'tripal_gbrowse', 
-			'tripal_gbrowse_delete_library_features_from_gbrowse', $job_args, $user->uid);
-	}
-	
-  //registering a job with the tripal system, this job calls the function when executed
-	$job_id = tripal_add_job('Loading Features Into GBrowse', 'tripal_gbrowse', 
-	'tripal_gbrowse_load_library_features_into_gbrowse', $job_args, $user->uid);
-
-}
-
-
-//-----------------------------------------------------------------------------
-//  SECTION:Load Library Features into GBrowse
-//-----------------------------------------------------------------------------
-
-
-/**
- * Load Library features into database 
- *
- * This loading function firstly creates a output GFF3 format file for verification purposes. Then, a 'Chado' table
- * is selected,depending which table the user is interested in, from this table specific infromation 
- * is taken out and placed in the GFF3 file.The Featurelocation(fmin) & featurelocation (fmax) are used  
- * to set the featureloc.feature_id = feature.feature_id, the fmin = start & fmax = end of the desired gene.
- * The testing if the phase is empty is done, if so a '.' is inserted into $phase variable. If the parent 
- * feature is indicated in feature location for the child feature will be set.The Attributes section 
- * sets the, ID, Name, Alias, Dbrexf to variables to be put into a CONF file.The strand is either a 
- * positive, negative, or zero value and is represented by +/./- accordingley.
- *
- * @param $name
- *   name of GBrowse database
- *
- * @param $user_name
- *   GBrowse MySQL user name 
- *
- * @param $password
- *   user password for GBrowse
- *
- * @param $library_id
- *   GBrowse MySQL user name 
- *
- * @param $clear_database
- *   Used to clear the database of its backbone structure
- */
-function tripal_gbrowse_load_library_features_into_gbrowse($database_name, $user_name, $password, $library_id,$clear_database){
-
-  //A test file created to verify output
-  $myFile = "/tmp/temporaryGBrowse_".time().".gff3";
-  
-  //Test opening the file, will print warning if file is not able to be opened
-  $fh = fopen($myFile, 'w') or die("WARNING: Can not open file");
-
-  print "Creating GFF3 file of features for library...\n";
- 
-  if (!preg_match('/^\d+$/', $library_id)) {
-   print "ERROR: Invalid Library ID supplied (Library ID = ".$library_id.")\n";  
-   return false;
-  }
-  
-  // Selecting all features
-  $values = array('library_id' => $library_id);
-   
-  $prime_result = tripal_core_chado_select ( 'library_feature', array('feature_id'), $values );
-
-  // Select Table:library; column:uniquename
-  $result = tripal_core_chado_select ( 'library', array('uniquename'), $values );
-
-  $source = $result[0]->uniquename ;
-  
-  // Check source: ERROR
-
-  //For each feature, type id form feature table, specific record the feature id containing $feature_id
-  foreach ($prime_result as $value) {
-
-    $feature_id = $value->feature_id;
-     
-    if (!preg_match('/^\d+$/', $feature_id)) {
-      print "ERROR: Invalid feature ID (".$feature_id.") associated with Library (Library ID = ".$library_id.")\n";
-    }
-   
-    $result = tripal_core_chado_select('feature', array('type_id'), array('feature_id'=>$feature_id));
-   
-    $type_id = $result[0]->type_id;
-     
-    if (empty($type_id)) {
-      print "ERROR: No Type associated with Feature (Feature ID = ".$feature_id.")\n";
-    }
-   
-    //Taking the cvterm name from the cvterm table given the type-id($type_id)
-    $result = tripal_core_chado_select('cvterm', array('name'), array('cvterm_id'=>$type_id));
-
-    //The extracted cvterm name
-    $type = $result[0]->name;
-    
-    if (empty($type)) {
-      print "ERROR: Type associated with Feature (".$type_id.") doesn't exist in cvterm table (Feature ID = ".$feature_id.")\n";
-    }
-    
-    //Featureloc.fmin & featureloc.fmax ( where featureloc.feature_id = feature.feature_id )
-    //fmin = start & fmax = end
-    $result = tripal_core_chado_select('featureloc', array('fmin','fmax', 'strand', 'phase', 'srcfeature_id'), array('feature_id'=>$feature_id));
-  
-    $start = $result[0]->fmin;
-    if (!preg_match('/^\d+$/', $start)) {
-      print "ERROR: Invalid Start (".$start.") of Feature (Feature ID= ".$feature_id.")\n";
-    }
-  
-    $end = $result[0]->fmax;
-    if (!preg_match('/^\d+$/', $end)) {
-      print "ERROR: Invalid End (".$end.") of Feature (Feature ID= ".$feature_id.")\n";
-    }
-    
-    $score = '.';
-
-
-    //Converting from +1/0/-1 to +/./- as there are only three possible values
-    if ($result[0]->strand < 0) {
-    
-      $strand= '-';
-    } elseif ($result[0]->strand == 0) {
-    
-      $strand = '.';
-    } elseif($result[0]->strand > 0) {
-    
-      $strand = '+';
-    } else{
-    
-      $strand = '.';
-    }
-  
-    //Testing if phase is empty, if so a '.' is inserted into $phase variable
-    $phase = $result[0]->phase;
-    if(empty($phase)){
-      $phase = '.';
-    }
-  
-    //This is the parent feature as indicated in feature location for the child feature and 
-    //the current line described the child feature
-    $srcfeature_id = $result[0]->srcfeature_id;
-
-    if (empty($srcfeature_id)) {
-      print "ERROR: No Parent associated with Feature Location (Feature ID = ".$feature_id.")\n";
-    }
-  
-    $result = tripal_core_chado_select('feature', array('name'), array('feature_id'=>$srcfeature_id));
-  
-    $seqid = $result[0]->name;
-
-    if (empty($seqid)) {
-      print "ERROR: Parent (Parent Feature ID = ".$seqid.") associated with Feature doesn't exist in feature table (Feature ID =".$feature_id."\n";
-    }
-
-    
-    //Attributes section, ID, Name, Alias, Dbrexf  
-    $result = tripal_core_chado_select('feature', array('uniquename', 'name'), array('feature_id'=>$feature_id));
-  
-    $id = $result[0]->uniquename;
-  
-    if (empty($id)) {
-      print "ERROR: Missing Unique Name for Feature (Feature ID = ".$feature_id.")\n";
-    }
-
-    $name = $result[0]->name;
-  
-    if (empty($name)) {
-      print "WARNING: Missing Name for Feature (Feature ID = ".$feature_id.")\n";
-    }
-    
-    //Synonym
-    $result = tripal_core_chado_select('feature_synonym', array('synonym_id'), array('feature_id'=>$feature_id));
-
-    $synonyms = array();
-    foreach ($result as $obj){
-  
-      $synonym_id = $obj->synonym_id;
-    
-      $sub_result = tripal_core_chado_select('synonym', array('name'), array('synonym_id'=>$synonym_id));
-
-      // check that $sub_result[0]->name isn't empty
-      if (empty($sub_result[0]->name)) {
-        print "ERROR: Synonym (".$synonym_id.") associated with feature not found in synonym table (Feature ID = ".$feature_id.")\n";
-      } else {
-        $synonyms[] = $sub_result[0]->name;
-      }
-
-    }
-    
-    // Additional Dbxref's
-    $result = tripal_core_chado_select('feature_dbxref', array('dbxref_id'), array('feature_id'=>$feature_id));
-    $dbxref = array();
-    
-    foreach ($result as $obj){
-    
-      $dbxref_id = $obj->dbxref_id;
-  
-      if (!empty($dbxref_id)) {
-        $sub1_result = tripal_core_chado_select('dbxref', array('db_id', 'accession'), array('dbxref_id'=>$dbxref_id));
-    
-        $dbxref_accession = $sub1_result[0]->accession;
-        
-        $db_id = $sub1_result[0]->db_id;
-        
-        if (!empty($db_id)) {
-          $sub_sub_result =tripal_core_chado_select('db', array('name'), array('db_id'=>$db_id));
-        
-          $db_name = $sub_sub_result[0]->name;    
-      
-          if (empty($db_name)) {
-            print "ERROR: Database (".$db_id.") associated with database reference not in db table (Database Reference ID = ".$dbxref_id.")\n";
-          } elseif (empty($dbxref_accession)) {
-            print "WARNING: Missing Accession for Database Reference (Database Reference ID = ".$dbxref_id.")\n";
-          } else {
-            $dbxref[] = $db_name . ':' . $dbxref_accession;
-          }
-        }
-      }
-    }
-
-    //Main Dbxref
-    $result = tripal_core_chado_select('feature', array('dbxref_id'), array('feature_id'=>$feature_id));
-  
-    $dbxref_id = $result[0]->dbxref_id;
-  
-    if (empty($dbxref_id)) {
-      print "WARNING: No Database Reference associated directly with Feature (Feature ID = ".$feature_id.")\n";
-    }
-
-    $result = tripal_core_chado_select('dbxref', array('accession','db_id'), array('dbxref_id'=>$dbxref_id));
-      
-    $dbxref_accession = $result[0]->accession;
-
-    //checking $dbrexf_accession for emptyness 
-    if(!empty($dbxref_accession)){
-
-      $db_id = $result[0]->db_id;
-    
-      $sub_sub_result =tripal_core_chado_select('db', array('name'), array('db_id'=>$db_id));
-
-      $db_name = $sub_sub_result[0]->name;
-  
-      $dbxref[] = $db_name . ':' . $dbxref_accession;
-
-    } else {
-      print "WARNING: Missing Accession for Database Reference (Database Reference ID = ".$dbxref_id.")\n";
-    }
-
-    //attributes array is assigned given elements based on previous initializations
-    $attributes = array();
-
-    $attributes[] = 'ID='.$id;
-
-    if (!empty($name)) { $attributes[] = 'Name='.$name; }
-
-    if (!empty($synonyms)) { $attributes[] = 'Alias='.implode(',',$synonyms); }
-
-    if (!empty($dbxref)) { $attributes[] = 'Dbxref=' .implode(',', $dbxref); }
-
-    //write to string for printing
-    $stringData = implode("\t", array($seqid,$source,$type,$start,$end,$score,$strand,$phase,
-  
-    implode(';',$attributes)))."\n";
-    
-    //Write concatinated data ($stringData) to file    
-    fwrite($fh, $stringData);
-  }
-
-  //Closing file
-  fclose($fh);
-
-
-  if($clear_database){    
-
-    //The loading script: bp_seqfeature_load.pl, allows loading of data to specific file 
-    $command= "bp_seqfeature_load.pl -c -u '" .$user_name. "' -p '" .$password. "' -d " .$database_name. " " . $myFile;
-
-  }else{
-
-    //The loading script: bp_seqfeature_load.pl, allows loading of data to specific file 
-    $command= "bp_seqfeature_load.pl -u '" .$user_name. "' -p '" .$password. "' -d " .$database_name. " " . $myFile;
-  }
-
-  //optional 'print' statement to verify that the above comman is being called and executed properly
-  print 'Executing Command:'.$command."\n";
-
-  exec($command, $out_put, $return_var);
-
-
-} 
-
-
-//-----------------------------------------------------------------------------
-//  SECTION: Delete library features from database Form & Form submit
-//-----------------------------------------------------------------------------
-
-
-/**
-*
-* This form's purpose is to delete library featues from a selected GBrowse insatance. By selecting
-* a Library of genetic sequences and a GBrowse instance, the instance will be removed as will all the 
-* associated libraries. This form allows access to a specified database and will delete any
-* selected Library features. It will return the form that contains all of the neccessary
-* information to send to the 'form_submit' function.
-*
-* @return $form
-*   An array of menu items allowing deletion of features from the library
-*/
-function tripal_gbrowse_delete_library_features_from_gbrowse_form() {
-
-  $form = array();
-  
-  $result = tripal_core_chado_select ( 'library', array('library_id','name'), array() );
-
-  foreach ($result as $value){
-    $newArray[$value->library_id]=$value->name;        //options for the select list
-  }
-    
-  //Creating Fieldset for multiple fields in form
-  $form['delete_gbrowse'] = array(
-    '#type' => 'fieldset',
-    '#title' => t(''),
-  );
-     
-   //Library ID
-   $form['delete_gbrowse']['library_id'] = array(
-    '#type' => 'select',
-    '#title' => t('Libraries'),
-    '#options' => $newArray,
-    '#description' => t('Genetic Sequences.'),
-  );
-    
-  //Sending query to the database
-  $resource = db_query('SELECT * FROM {tripal_gbrowse_instances}');
-
-  $items = array();
-  
-  while($record = db_fetch_object($resource)){  
-    $items[$record->gbrowse_id]= $record->gbrowse_name;  
-  }
-
-  $form['delete_gbrowse']['gbrowse_id'] = array(
-    '#type' => 'select',
-    '#title' => t('GBrowse Instances'),
-    '#options' => $items,
-    '#description' => t('Selected Instances to be Removed.'),
-  );
-  
-  //Delete button to remove Library
-  $form['delete_gbrowse']['submit'] = array(
-     '#type' => 'submit', 
-     '#weight' => 10,
-     '#value' => t('Delete')
-   );
-    
-  return $form;
-
-}
-
-
-/**
-* This 'form_submit' function uses MySQL commands to select the GBrowse instance from a selected database.
-* Then the selected features are deleted from the library.
-*
-*
-* @param $form
-*    The submitted form that 
-*
-* @param $form_state 
-*    The state of the form, includes the selected library and the GBrowse instance to be removed
-*    The key is the 'values'
-*/
-function tripal_gbrowse_delete_library_features_from_gbrowse_form_submit($form, $form_state) {
-  
-  global $user;    //needed to make the current users details available so access of user id is available 
-          
-  $record = db_fetch_object(db_query('SELECT * FROM {tripal_gbrowse_instances} WHERE gbrowse_id=%d', $form_state['values']['gbrowse_id']));
-    
-  $name = $record->database_name;
-  
-  $user_name = $record->database_user;
-  
-  $password= $record->user_password;
-  
-  $job_args = array($name,$user_name,$password,$form_state['values']['library_id']);   
-                  
-  //Checking state of submit button, if selected delete features from library
-  if($form_state['values']['op'] == 'Delete'){
-
-    //registering a delete job with the tripal system, this job calls the function when executed
-    $job_id = tripal_add_job('Deleting Library Features From GBrowse', 'tripal_gbrowse', 'tripal_gbrowse_delete_library_features_from_gbrowse', $job_args, $user->uid);
-        
-  }
-    
-}
-
-
-//-----------------------------------------------------------------------------
-//  SECTION: Delete Library Features from GBrowse
-//-----------------------------------------------------------------------------
-
-
-/**
-* Delete-GBrowse-Feature
-*
-* This form Removes features from library that the user has specified. The form allows the user
-* to select a desired instance. Once the library and instance are selected and deleted, the selected 
-* libraries 
-*
-*
-*
-* @param $database_name
-*   name of GBrowse database
-* @param $user_name
-*   GBrowse MySQL user name 
-* @param $password
-*   user password for GBrowse
-* @param $library_id
-*   The id of the library that is being selected from
-*
-*/
-function tripal_gbrowse_delete_library_features_from_gbrowse($database_name, $user_name, $password, $library_id){
-
-  $result = tripal_core_chado_select ( 'library', array('name'), array('library_id' => $library_id) 
-  
-  );
-
-  $library_name = $result[0]->name;
-  
-  print "Removing Features of all types related to the ".$library_name." library...\n";
-
-  $sql = 'SELECT cvterm.name FROM feature JOIN cvterm cvterm ON cvterm.cvterm_id=feature.type_id 
-  
-  JOIN library_feature library_feature ON library_feature.feature_id=feature.feature_id JOIN library 
-  
-  library ON library.library_id=library_feature.library_id WHERE library.library_id=%d GROUP BY 
-  
-  cvterm.name';
-
-  $previous_db = tripal_db_set_active('chado');
-  
-  $resource = db_query($sql, $library_id);
-  
-  tripal_db_set_active($previous_db);
-  
-  while($record = db_fetch_object($resource)){
-  
-    $type = $record->name;
-    
-    //The loading script: bp_seqfeature_delete.pl, allows removal of data to specific file 
-    $command= "bp_seqfeature_delete.pl -u '".$user_name."' -p '".$password."' -d '" .$database_name. "' -t '" .$type. ":".$library_name."'";
-    
-    print "Executing Command: ".$command."\n";
-    
-    //exec() allows for execution of a external program: given the input
-    exec($command);
-  
-  }
-
-}
-
-
-//-----------------------------------------------------------------------------
-//  SECTION: Load analyses into GBrowse Form and Form Submit
-//-----------------------------------------------------------------------------
-
-
-/**
-* Implements hook_form
-*
-* This function creates a form for the database name, user name for database operation and a 
-* password for access.The module uses these analyses to access information regarding the user's 
-* operations and needs.
-*
-* @return
-*   An array describing the form to be rendered
-*/
-function tripal_gbrowse_load_analyses_form(){
- 
-  $newArray=array();
-  
-  $result = tripal_core_chado_select ( 'analysis', array('analysis_id','name'), array() );
-  
-  foreach ($result as $value) {
-    $newArray[$value->analysis_id]=$value->name;        //options for the select list
-  }
-  
-  //Creating Fieldset for multiple fields in form
-  $form['load_analyses'] = array(
-    '#type' => 'fieldset',
-  );
- 
-  //Library ID
-  $form['load_analyses']['analysis_id'] = array(
-      '#type' => 'select',
-      '#title' => t('Analyses'),
-      '#options' => $newArray,
-      '#description' => t('Analyses.'),
-  );
-    
-  //Sending query to the database
-  $resource = db_query('SELECT * FROM {tripal_gbrowse_instances}');
-
-    $items = array();
-  
-    while($record = db_fetch_object($resource)){
-      $items[$record->gbrowse_id]= $record->gbrowse_name;
-  }
-  
-  //GBrowse Instances
-  $form['load_analyses']['gbrowse_id'] = array(
-      '#type' => 'select',
-      '#title' => t('GBrowse Instances'),
-      '#options' => $items,
-      '#description' => t('Selected GBrowse Instances to be Loaded.'),
-  );
-    
-  //A checkbox to update features for the gbrowse
-  $form['load_analyses']['check_box'] = array(
-    '#type' => 'checkbox',
-    '#title' => t('Update Analyses'),
-    '#description' => t('Existing Same Name Analyses Updated Accordingly.'),
-  );
-
-  $form['load_analyses']['submit'] = array(
-   '#type' => 'submit', 
-   '#weight' => 10,
-   '#value' => t('Submit Job')
-   );
-  
-  return $form;
-}
-
-
-/**
-* Load-Features-Form
-*
-* @param $form
-*    -The submitted form containing the user entered infromation
-*
-* @param $form_state 
-*    -Is the state of the form: i.e what button was pressed, what infromation was entered,etc.
-*    The key is the 'values'
-*/
-function tripal_gbrowse_load_analyses_form_submit($form, $form_state) {
-    
-    global $user;    //needed to make the current users details available so access of user id is available 
-          
-    $record = db_fetch_object(db_query('SELECT * FROM {tripal_gbrowse_instances} WHERE gbrowse_id=%d', $form_state['values']['gbrowse_id']));
-    
-    $name = $record->database_name;
-  
-    $user_name = $record->database_user;
-  
-    $password= $record->user_password;
- 
-    $job_args = array($name,$user_name,$password,$form_state['values']['analysis_id'], FALSE);   
-                 
-    //Checking state of check box, if checked delete features from GBrowse
-    if($form_state['values']['check_box']==1){
-        //registering a delete job with the tripal system, this job calls the function when executed
-        $job_id = tripal_add_job('Deleting Features From GBrowse', 'tripal_gbrowse', 
-        'tripal_gbrowse_delete_analysis_features_from_gbrowse', $job_args, $user->uid);
-    }
-    
-    //registering a job with the tripal system, this job calls the function when executed
-    $job_id = tripal_add_job('Loading Features Into GBrowse', 'tripal_gbrowse', 
-    'tripal_gbrowse_load_analysis_features_into_gbrowse', $job_args, $user->uid);
-
-}
-
-
-//-----------------------------------------------------------------------------
-//  SECTION:Load Analysis Features into GBrowse
-//-----------------------------------------------------------------------------
-
-
-/**
- * Load Analysis features into database 
- *
- * This loading function firstly creates a output GFF3 format file for verification purposes. Then, a 'Chado' table
- * is selected,depending which table the user is interested in, from this table specific infromation 
- * is taken out and placed in the GFF3 file.The Featurelocation(fmin) & featurelocation (fmax) are used  
- * to set the featureloc.feature_id = feature.feature_id, the fmin = start & fmax = end of the desired gene.
- * The testing if the phase is empty is done, if so a '.' is inserted into $phase variable. If the parent 
- * feature is indicated in feature location for the child feature will be set.The Attributes section 
- * sets the, ID, Name, Alias, Dbrexf to variables to be put into a CONF file.The strand is either a 
- * positive, negative, or zero value and is represented by +/./- accordingley.
- *
- * @param $name
- *   name of GBrowse database
- *
- * @param $user_name
- *   GBrowse MySQL user name
- *
- * @param $password
- *   user password for GBrowse
- *
- * @param $library_id
- *   GBrowse MySQL user name 
- *
- * @param $clear_database
- *   Used to clear the database of its backbone structure
- */
-function tripal_gbrowse_load_analysis_features_into_gbrowse($database_name, $user_name, $password, $analysis_id,$clear_database){
-
-	//print 'Analysis ID: '.$analysis_id.".\n";
-
-  //A test file created to verify output
-  $myFile = "/tmp/temporaryGBrowse_".time().".gff3";
-  
-  //Test opening the file, will print warning if file is not able to be opened
-  $fh = fopen($myFile, 'w') or die("WARNING: Can not open file");
-
-  print "Creating GFF3 file of features for Analysis...\n";
- 
-  if (!preg_match('/^\d+$/', $analysis_id)) {
-   print "ERROR: Invalid Analysis ID supplied (Analysis ID= ".$analysis_id.")\n";  
-   return false;
-  }
-  
-  // Selecting all analyses
-  $values = array('analysis_id' => $analysis_id);
-      
-  $prime_result = tripal_core_chado_select ( 'analysisfeature', array('feature_id'), $values);
-
-  // Select Table:library; column:uniquename
-  $result = tripal_core_chado_select ( 'analysis', array('name'), $values );
-
-  $source = $result[0]->name ;
-  
-  // Check source: ERROR
-  //For each feature, type id form feature table, specific record the feature id containing $feature_id
-  foreach ($prime_result as $value) {
-
-    $feature_id = $value->feature_id;
-     
-    if (!preg_match('/^\d+$/', $feature_id)) {
-      print "ERROR: Invalid feature ID (".$feature_id.") associated with Library (Library ID = ".$analysis_id.")\n";
-    }
-   
-    $result = tripal_core_chado_select('feature', array('type_id'), array('feature_id'=>$feature_id));
-   
-    $type_id = $result[0]->type_id;
-     
-    if (empty($type_id)) {
-      print "ERROR: No Type associated with Feature ( Feature ID = ".$feature_id.")\n";
-    }
-   
-    //Taking the cvterm name from the cvterm table given the type-id($type_id)
-    $result = tripal_core_chado_select('cvterm', array('name'), array('cvterm_id'=>$type_id));
-
-    //The extracted cvterm name
-    $type = $result[0]->name;
-    
-    if (empty($type)) {
-      print "ERROR: Type associated with Feature (".$type_id.") doesn't exist in cvterm table (Feature ID = ".$feature_id.")\n";
-    }
-    
-    //Featureloc.fmin & featureloc.fmax ( where featureloc.feature_id = feature.feature_id )
-    //fmin = start & fmax = end
-    $result = tripal_core_chado_select('featureloc', array('fmin','fmax', 'strand', 'phase', 'srcfeature_id'), array('feature_id'=>$feature_id));
-  
-    $start = $result[0]->fmin;
-    if (!preg_match('/^\d+$/', $start)) {
-      print "ERROR: Invalid Start (".$start.") of Feature (Feature ID= ".$feature_id.")\n";
-    }
-  
-    $end = $result[0]->fmax;
-    if (!preg_match('/^\d+$/', $end)) {
-      print "ERROR: Invalid End (".$end.") of Feature (Feature ID= ".$feature_id.")\n";
-    }
-    
-    $score = '.';
-
-    //Converting from +1/0/-1 to +/./- as there are only three possible values
-    if ($result[0]->strand < 0) {
-      $strand= '-';
-    } elseif ($result[0]->strand == 0) {
-      $strand = '.';
-    } elseif($result[0]->strand > 0) {
-      $strand = '+';
-    } else{
-      $strand = '.';
-    }
-  
-    //Testing if phase is empty, if so a '.' is inserted into $phase variable
-    $phase = $result[0]->phase;
-    if(empty($phase)){
-      $phase = '.';
-    }
-  
-    //This is the parent feature as indicated in feature location for the child feature and 
-    //the current line described the child feature
-    $srcfeature_id = $result[0]->srcfeature_id;
-
-    if (empty($srcfeature_id)) {
-      print "ERROR: No Parent associated with Feature Location (Feature ID = ".$feature_id.")\n";
-    }
-  
-    $result = tripal_core_chado_select('feature', array('name'), array('feature_id'=>$srcfeature_id));
-  
-    $seqid = $result[0]->name;
-
-    if (empty($seqid)) {
-      print "ERROR: Parent (Parent Feature ID = ".$seqid.") associated with Feature doesn't exist in feature table (Feature ID =".$feature_id."\n";
-    }
-
-    //Attributes section, ID, Name, Alias, Dbrexf  
-    $result = tripal_core_chado_select('feature', array('uniquename', 'name'), array('feature_id'=>$feature_id));
-  
-    $id = $result[0]->uniquename;
-  
-    if (empty($id)) {
-      print "ERROR: Missing Unique Name for Feature (Feature ID = ".$feature_id.")\n";
-    }
-
-    $name = $result[0]->name;
-  
-    if (empty($name)) {
-      print "WARNING: Missing Name for Feature (Feature ID = ".$feature_id.")\n";
-    }
-    
-    //Synonym
-    $result = tripal_core_chado_select('feature_synonym', array('synonym_id'), array('feature_id'=>$feature_id));
-
-    $synonyms = array();
-    foreach ($result as $obj){
-  
-      $synonym_id = $obj->synonym_id;
-    
-      $sub_result = tripal_core_chado_select('synonym', array('name'), array('synonym_id'=>$synonym_id));
-
-      // check that $sub_result[0]->name isn't empty
-      if (empty($sub_result[0]->name)) {
-        print "ERROR: Synonym (".$synonym_id.") associated with feature not found in synonym table (Feature ID = ".$feature_id.")\n";
-      } else {
-        $synonyms[] = $sub_result[0]->name;
-      }
-
-    }
-    
-    // Additional Dbxref's
-    $result = tripal_core_chado_select('feature_dbxref', array('dbxref_id'), array('feature_id'=>$feature_id));
-    $dbxref = array();
-    
-    foreach ($result as $obj){
-    
-      $dbxref_id = $obj->dbxref_id;
-  
-      if (!empty($dbxref_id)) {
-        $sub1_result = tripal_core_chado_select('dbxref', array('db_id', 'accession'), array('dbxref_id'=>$dbxref_id));
-    
-        $dbxref_accession = $sub1_result[0]->accession;
-        
-        $db_id = $sub1_result[0]->db_id;
-        
-        if (!empty($db_id)) {
-          $sub_sub_result =tripal_core_chado_select('db', array('name'), array('db_id'=>$db_id));
-        
-          $db_name = $sub_sub_result[0]->name;    
-      
-          if (empty($db_name)) {
-            print "ERROR: Database (".$db_id.") associated with database reference not in db table (Database Reference ID = ".$dbxref_id.")\n";
-          } elseif (empty($dbxref_accession)) {
-            print "WARNING: Missing Accession for Database Reference (Database Reference ID = ".$dbxref_id.")\n";
-          } else {
-            $dbxref[] = $db_name . ':' . $dbxref_accession;
-          }
-        }
-      }
-    }
-
-    //Main Dbxref
-    $result = tripal_core_chado_select('feature', array('dbxref_id'), array('feature_id'=>$feature_id));
-  
-    $dbxref_id = $result[0]->dbxref_id;
-  
-    if (empty($dbxref_id)) {
-      print "WARNING: No Database Reference associated directly with Feature (Feature ID = ".$feature_id.")\n";
-    }
-
-    $result = tripal_core_chado_select('dbxref', array('accession','db_id'), array('dbxref_id'=>$dbxref_id));
-      
-    $dbxref_accession = $result[0]->accession;
-
-    //checking $dbrexf_accession for emptyness 
-    if(!empty($dbxref_accession)){
-
-      $db_id = $result[0]->db_id;
-    
-      $sub_sub_result =tripal_core_chado_select('db', array('name'), array('db_id'=>$db_id));
-
-      $db_name = $sub_sub_result[0]->name;
-  
-      $dbxref[] = $db_name . ':' . $dbxref_accession;
-
-    } else {
-      print "WARNING: Missing Accession for Database Reference (Database Reference ID = ".$dbxref_id.")\n";
-    }
-
-    //attributes array is assigned given elements based on previous initializations
-    $attributes = array();
-
-    $attributes[] = 'ID='.$id;
-
-    if (!empty($name)) { 
-      $attributes[] = 'Name='.$name; 
-    }
-
-    if (!empty($synonyms)) { 
-      $attributes[] = 'Alias='.implode(',',$synonyms); 
-    }
-
-    if (!empty($dbxref)) { 
-      $attributes[] = 'Dbxref=' .implode(',', $dbxref); 
-    }
-
-    //write to string for printing
-    $stringData = implode("\t", array($seqid,$source,$type,$start,$end,$score,$strand,$phase,
-  
-    implode(';',$attributes)))."\n";
-    
-    //Write concatinated data ($stringData) to file    
-    fwrite($fh, $stringData);
-  }
-
-  //Closing file
-  fclose($fh);
-
-
-  if($clear_database){    
-    //The loading script: bp_seqfeature_load.pl, allows loading of data to specific file 
-    $command= "bp_seqfeature_load.pl -c -u '" .$user_name. "' -p '" .$password. "' -d " .$database_name. " " . $myFile;
-  }else{
-    //The loading script: bp_seqfeature_load.pl, allows loading of data to specific file 
-    $command= "bp_seqfeature_load.pl -u '" .$user_name. "' -p '" .$password. "' -d " .$database_name. " " . $myFile;
-  }
-
-  //optional 'print' statement to verify that the above comman is being called and executed properly
-  print 'Executing Command:'.$command."\n";
-
-  exec($command, $out_put, $return_var);
-} 
-
-
-//-----------------------------------------------------------------------------
-//  SECTION: Delete analysis features from database Form & Form submit
-//-----------------------------------------------------------------------------
-
-
-/**
-* This form's purpose is to delete analysis featues from a selected GBrowse insatance. By selecting
-* a Library of analyses and a GBrowse instance, the instance will be removed as will all the 
-* associated analysis library. This form allows access to a specified database and will delete any
-* selected Analysis features. It will return the form that contains all of the neccessary
-* information to send to the 'form_submit' function.
-*
-* @return $form
-*   An array of menu items allowing deletion of features from the library
-*/
-function tripal_gbrowse_delete_analysis_features_from_gbrowse_form() {
-
-  $form = array();
-  
-  $result = tripal_core_chado_select ( 'analysis', array('analysis_id','name'), array() );
-
-  foreach ($result as $value){
-    $newArray[$value->analysis_id]=$value->name;        //options for the select list
-  }
-    
-  //Creating Fieldset for multiple fields in form
-  $form['delete_analysis'] = array(
-    '#type' => 'fieldset',
-    '#title' => t(''),
-  );
-     
-   //Library ID
-   $form['delete_analysis']['analysis_id'] = array(
-    '#type' => 'select',
-    '#title' => t('Analysis Features'),
-    '#options' => $newArray,
-    '#description' => t('Analysis.'),
-  );
-    
-  //Sending query to the database
-  $resource = db_query('SELECT * FROM {tripal_gbrowse_instances}');
-
-  $items = array();
-  
-  while($record = db_fetch_object($resource)){
-    $items[$record->gbrowse_id]= $record->gbrowse_name;
-  }
-  
-  $form['delete_analysis']['gbrowse_id'] = array(
-    '#type' => 'select',
-    '#title' => t('GBrowse Instances'),
-    '#options' => $items,
-    '#description' => t('Selected Instances to be Removed.'),
-  );
-  
-  //Delete button to remove Library
-  $form['delete_analysis']['submit'] = array(
-     '#type' => 'submit', 
-     '#weight' => 10,
-     '#value' => t('Delete')
-   );
-    
-  return $form;
-}
-
-
-/**
-* This 'form_submit' function uses MySQL commands to select the GBrowse instance from a selected database.
-* Then the selected features are deleted from the library.
-*
-*
-* @param $form
-*    The submitted form that 
-*
-* @param $form_state 
-*    The state of the form, includes the selected library and the GBrowse instance to be removed
-*    The key is the 'values'
-*/
-function tripal_gbrowse_delete_analysis_features_from_gbrowse_form_submit($form, $form_state) {
-  
-  global $user;    //needed to make the current users details available so access of user id is available 
-          
-  $record = db_fetch_object(db_query('SELECT * FROM {tripal_gbrowse_instances} WHERE gbrowse_id=%d', $form_state['values']['gbrowse_id']));
-    
-  $name = $record->database_name;
-  
-  $user_name = $record->database_user;
-  
-  $password= $record->user_password;
-  
-  $job_args = array($name,$user_name,$password,$form_state['values']['analysis_id']);
-                  
-  //Checking state of submit button, if selected delete features from library
-  if($form_state['values']['op'] == 'Delete'){
-    //registering a delete job with the tripal system, this job calls the function when executed
-    $job_id = tripal_add_job('Deleting Analysis Features From GBrowse', 'tripal_gbrowse', 'tripal_gbrowse_delete_analysis_features_from_gbrowse', $job_args, $user->uid);
-  }
-    
-}
-
-
-//-----------------------------------------------------------------------------
-//  SECTION: Delete Analysis Features from GBrowse
-//-----------------------------------------------------------------------------
-
-
-/**
-* Delete-GBrowse-Feature
-*
-* This form Removes features from Analysis that the user has specified. The form allows the user
-* to select a desired instance. Once the analysis and instance are selected and deleted, the selected 
-* analyses will be disassociated with the specified instance. 
-*
-* @param $database_name
-*   name of GBrowse database
-*
-* @param $user_name
-*   GBrowse MySQL user name 
-*
-* @param $password
-*   user password for GBrowse
-*
-* @param $library_id
-*   The id of the library that is being selected from
-*
-*/
-function tripal_gbrowse_delete_analysis_features_from_gbrowse($database_name, $user_name, $password, $analysis_id){
-
-  $result = tripal_core_chado_select ( 'analysis', array('name'), array('analysis_id' => $analysis_id) 
-  
-  );
-  
-  $analysis_name = $result[0]->name;
-  
-  print "Removing Analysis Features of all types related to the ".$analysis_name." analysis...\n";
-
-  $sql = 'SELECT cvterm.name FROM feature JOIN cvterm cvterm ON cvterm.cvterm_id=feature.type_id 
-  
-  JOIN analysisfeature analysisfeature ON analysisfeature.feature_id=feature.feature_id JOIN analysis 
-  
-  analysis ON analysis.analysis_id=analysisfeature.analysis_id WHERE analysis.analysis_id=%d GROUP BY 
-  
-  cvterm.name';
-
-  $previous_db = tripal_db_set_active('chado');
-  $resource = db_query($sql, $analysis_id);
-  tripal_db_set_active($previous_db);
-  
-  while($record = db_fetch_object($resource)){
-  
-    $type = $record->name;
-    
-    //The loading script: bp_seqfeature_delete.pl, allows removal of data to specific file 
-    $command= "bp_seqfeature_delete.pl -u '".$user_name."' -p '".$password."' -d '" .$database_name. "' -t '" .$type. ":".$analysis_name."'";
-    
-    print "Executing Command: ".$command."\n";
-    
-    //exec() allows for execution of a external program: given the input
-    exec($command);
-  }
-
-}
-
-
-//-----------------------------------------------------------------------------
-//  SECTION: Add Tracks Form & Form submit
-//-----------------------------------------------------------------------------
-
-
-/**
-* Add-GBrowse-Tracks
-*      This Menu item is implemented to allow users to define and add tracks including their name,
-*  glyph, colour (fore and back ground), size and link. By adding tracks, the user is able to
-*  visually inspect the features of their genomic data. The Glyph library has been hardcoded 
-*  into the software and represents the most used Glyph representations. The "Glyph" option  
-*  determines the shape of each of the displayed genomic features associated with a specific  
-*  GBrowse track. It presents a configurable set of parameters specific to its type allowing 
-*  further control over the display features such as height, color (foreground & backround) etc.
-*
-*
-* @return
-*   An '$form' that is an array of menu items that allows the user to Register a GBrowse instance
-*/
-function tripal_gbrowse_add_tracks_form() {
-
-  
-  //Creating Fieldset for multiple fields in form
-  $form['add_tracks_field_set'] = array(
-    '#type' => 'fieldset',
-    '#title' => t('Content-Related Fields'),
-  );
-
-  //Sending query to the database for GBrowse Instances
-  $resource = db_query('SELECT * FROM {tripal_gbrowse_instances}');
-
-  $items = array();
-  
-  while($record = db_fetch_object($resource)){
-      
-    $items[$record->gbrowse_id]= $record->gbrowse_name;
-      
-  }
-
-  //GBrowse Instances
-  $form['add_tracks_field_set']['gbrowse_instances'] = array(
-    '#type' => 'select',
-    '#title' => t('Registered GBrowse Instances'),
-    '#options' => $items,
-    '#description' => t('Selected GBrowse Instances to be Loaded.'),
-    '#required' => TRUE,
-  );
-
-  //Feature Type
-  $sql = 'SELECT name as type, cvterm_id '
-          .'FROM cvterm '
-          .'WHERE cvterm_id IN (SELECT type_id FROM feature)';
-  $previous_db = tripal_db_set_active('chado');
-  $resource = db_query($sql);
-  tripal_db_set_active($previous_db);
-  
-  $items = array();
-  
-  while($record = db_fetch_object($resource)){
-    
-    $items[$record->type] = $record->type;
-  }
-
-  $form['add_tracks_field_set']['type_name'] = array(
-    '#type' => 'select',
-    '#title' => t('Feature Type'),
-    '#options' => $items,
-    '#description' => t('Selected GBrowse Instances to be Loaded.'),
-    '#required' => TRUE,
-  );
-
-  //Populating Select list for  Library    
-  $newArray['none'] = 'None';        //No option for select list
-  $result = tripal_core_chado_select ( 'library', array('library_id','name'), array() );
-  foreach ($result as $value) {
-    $newArray[$value->name]=$value->name;        //options for the select list
-  }
-        
-  //Library
-  $form['add_tracks_field_set']['library_id'] = array(
-    '#type' => 'select',
-    '#title' => t('Library'),
-    '#options' => $newArray,
-    '#description' => t('Selected GBrowse Instances to be Loaded.'),
-  );
-
-  //Creating Fieldset for multiple fields in form
-  $form['track_text'] = array(
-    '#type' => 'fieldset',
-    '#title' => 'Track-Specific Fields'
-  );
-
-  //Specify Track Identifier
-  $form['track_text']['identifier'] = array(
-    '#type' => 'textfield',
-    '#title' => t('Track Identifier'),
-    '#size' => 30,
-    '#maxlength' => 64,
-    '#description' => t('Specify Track Identifier (Must be Unique and Specific)'),
-    '#required' => TRUE,
-  );
-
-  //Specify Track Name
-  $form['track_text']['track_name'] = array(
-    '#type' => 'textfield',
-    '#title' => t('Track Name'),
-    '#size' => 30,
-    '#maxlength' => 64,
-    '#description' => t('Specify Track Name (Must be Unique and Specific)'),
-    '#required' => TRUE,
-  );
-  
-  //Populating Array of Glyph List
-  $item = array();
-  $item[''] = 'Default Glyph';
-  $item['generic'] = 'Generic';
-  $item['allele_tower  '] = 'Allele Tower';
-  $item['anchored_arrow'] = 'Anchored Arrow';
-  $item['arrow'] = 'Arrow';
-  $item['box'] = 'Box';
-  $item['cds'] = 'CDS';
-  $item['crossbox'] = 'Cross Box';
-  $item['diamond'] = 'Diamond';
-  $item['dna'] = 'DNA';
-  $item['dot'] = 'Dot';
-  $item['ellipse'] = 'Ellipse';
-  $item['extending_arrow'] = 'Extending Arrow';
-  $item['generic'] = 'Generic';
-  $item['graded_segments'] = 'Graded Segments';
-  $item['heterogeneous_segments  '] = 'Heterogeneous Segments';
-  $item['image'] = 'Image';
-  $item['line'] = 'Line';
-  $item['primers'] = 'Primers';
-  $item['processed_transcript'] = 'Processed Transcript';
-  $item['rndrect'] = 'Rndrect';
-  $item['ruler_arrow'] = 'Ruler Arrow';
-  $item['segments'] = 'Segments';
-  $item['span'] = 'Span';
-  $item['toomany'] = 'Too Many';
-  $item['transcript'] = 'Transcript';
-  $item['transcript2'] = 'Transcript2';
-  $item['translation'] = 'Translation';
-  $item['triangle'] = 'Triangle';
-  $item['wiggle_densit'] = 'Wiggle Densit';
-  $item['wiggle_xyplot'] = 'Wiggle XYplot';
-  $item['xyplot'] = 'XYplot';
-      
-      
-  //Glyphs
-  $form['track_text']['glyph'] = array(
-    '#type' => 'select',
-    '#title' => t('Glyph'),
-    '#options' => $item,
-    '#description' => t('Shape of Genomic Feature Track '),
-  );
-
-  //Modify The foreground colour of track
-    $form['track_text']['foreground_colour'] = array(
-    '#type' => 'textfield',
-    '#title' => t('Foreground Colour'),
-    '#size' => 30,
-    '#maxlength' => 64,
-    '#description' => t('Enter name/Hex-code for identifying foreground colour of glyph.
-                        List of available colours here:'.l("GBrowse Colour Palette.pdf",
-                        "http://gmod.org/mediawiki/images/a/ae/Gbrowse_Color_Palette.pdf")),
-  );
-
-
-  //Modify The Backround colour of track
-  $form['track_text']['backround_colour'] = array(
-    '#type' => 'textfield',
-    '#title' => t('Background Colour'),
-    '#size' => 30,
-    '#maxlength' => 20,
-    '#description' => t('Enter name/Hex-code for identifying background colour of glyph.
-                        List of available colours here:'.l("GBrowse Colour Palette.pdf",
-                        "http://gmod.org/mediawiki/images/a/ae/Gbrowse_Color_Palette.pdf")),
-  );
-
-
-  //Modify The Height of track
-  $form['track_text']['track_height'] = array(
-    '#type' => 'textfield',
-    '#title' => t('Height'),
-    '#size' => 30,
-    '#maxlength' => 20,
-    '#description' => t('Modify Track Height'),
-  );
-
-  //Specify Link
-  $form['track_text']['link'] = array(
-    '#type' => 'textfield',
-    '#title' => t('Link'),
-    '#size' => 30,
-    '#maxlength' => 64,
-    '#description' => t('Specify to Further details (HTML address)'),
-  );
-
-  //Register job submit button
-  $form['create_instance']['submit'] = array(
-     '#type' => 'submit',
-     '#value' => t('Add Track')
-  );
-  
-  return $form;
-
-}
-
-
-/**
- * Validate User-submitted data for Register GBrowse Instances 
- *
- * This function validates the user input for each form element in the Register GBrowse 
- * instances form that is a text field. Validations checked include:
- *   - database_name: contains only word characters not including punctuation 
- *       or white-space ([A-Z][a-z][0-1]_)
- *
- * @param $form
- *   The form that the user submitted and whose input is being validated
- *
- * @param $form_state
- *   An array containing the state of the form being validated including user-input
- */
-function tripal_gbrowse_add_tracks_form_validate ($form, $form_state) {
-  
-  if (!empty($form_state['values']['foreground_colour'])) {
-    // foreground colour is present and a valid colour
-    if ( !preg_match('/^[\w#]+$/', $form_state['values']['foreground_colour'])) {
-      
-      form_set_error('foreground_colour',
-      'The Foreground Colour should be either the name of a colour listed in the linked to pdf or a valid hex colour');
-    }
-  }
-  
-  if (!empty($form_state['values']['backround_colour'])) {
-    if(!preg_match('/^[\w#]+$/', $form_state['values']['backround_colour'])){
-      form_set_error('backround_colour','The Background Colour should be either the name of a colour listed in the linked to pdf or a valid hex colour');
-    }
-  }
-  
-  if (!empty($form_state['values']['track_height'])){
-    if(!preg_match('/^\d*$/', $form_state['values']['track_height'])){
-      form_set_error('track_height','The Track Height must be a positive integer');
-    }
-  }
-  
-  if(!preg_match('/^\w+$/', $form_state['values']['identifier'])){
-
-    form_set_error('identifier','The Identifier must be composed of the following characters only: [A-Z][a-z][0-9] and _');
-  
-  }
-  
-  if (!empty($form_state['values']['link'])){
-    if(!preg_match('/^http:/', $form_state['values']['link'])){
-      form_set_error('link','The Link must be a conventional web site name, beginging with  http: ');
-    }
-  }
-
-} 
-
-
-/**
-*Add-GBrowse-Tracks Form_Submit
-*
-* @param $form
-*    The form for the information that the user has entered
-*
-* @param $form_state 
-*    This is the state of the form: i.e what button was pressed.The key is 
-*    the name of the fields in database 
-*
-* @return
-*   An '$form' that is an array of menu items that allows the user to Register a GBrowse instance
-*/
-function tripal_gbrowse_add_tracks_form_submit($form, $form_state) {
-
-  
-
-  $string = "\n[".$form_state['values']['identifier']."]\n"
-    ."key = ".$form_state['values']['track_name']."\n";
-    
-  if($form_state['values']['library_id'] == 'none'){    
-    $string .= "feature =  ".$form_state['values']['type_name']."\n";
-  } else {
-    $string .= "feature =  ".$form_state['values']['type_name'].":" .$form_state['values']['library_id']."\n";
-  }
-  
-  if (!empty($form_state['values']['glyph'])) {
-    $string .= "glyph = ".$form_state['values']['glyph']."\n";
-  }
-  
-  if (!empty($form_state['values']['track_height'])) {
-    $string .= "height = ".$form_state['values']['track_height']."\n";
-  }
-  
-  if (!empty($form_state['values']['foreground_colour'])) {
-    $string .= "bgcolor = ".$form_state['values']['foreground_colour']."\n";
-  }
-  
-  if (!empty($form_state['values']['backround_colour'])) {
-    $string .= "fgcolor = ".$form_state['values']['backround_colour']."\n";
-  }
-  
-  if (!empty($form_state['values']['link'])) {
-    $string .= "link = ".$form_state['values']['link']."\n";
-  }
-  
-  $string .= "\n";
-       
-  $record = db_fetch_object(db_query('SELECT * FROM {tripal_gbrowse_instances} WHERE gbrowse_id=%d', $form_state['values']['gbrowse_instances']));
-  
-  $config_file = $record->config_file;
-  
-  $command = "echo '".$string."' >> ".$config_file;
-  
-  exec($command);
-
-}
-
-
-//-----------------------------------------------------------------------------
-//  SECTION: Delete Tracks Form & Form submit
-//-----------------------------------------------------------------------------
-
-
-/**
-*Delete-GBrowse-Tracks
-*    
-*    This Form allows selection for a specific GBrowse Instance to be removed in a multi-submit form outline.
-*    Once the GBrowse instance is selected,the corresponding track list that corresponds to 
-*    the selected GBrowse instance is deleted. This can be done one track at a time. As
-*    there is no limit to the number of tracks that can be added to a particular GBrowse instance and
-*    thus all the tracks that have bee added can be deleted, one track at a time. The track that is to 
-*    be deleted is to be selected from the list. When selected and the delete button is pushed, 
-*    the track that was selected is removed from the 'configuration' file.
-*
-* @param $form_state
-*    The state of the form as it is setting the default value of $form_state is NULL
-*
-* @return
-*   An '$form' that is an array of menu items that allows the user to Register a GBrowse instance
-*/
-function tripal_gbrowse_delete_tracks_form(&$form_state=NULL) {
-
-  //Creating Fieldset for multiple fields in form
-  $form['delete_tracks_field_set'] = array(
-    '#type' => ($form_state['storage']['gbrowse_id']) ? 'hidden' : 'fieldset',
-    '#title' => t('GBrowse Specific Fields'),
-  );
-  
-  //Sending query to the database for GBrowse Instances
-  $resource = db_query('SELECT * FROM {tripal_gbrowse_instances}');
-
-  $items = array();
-  
-  while($record = db_fetch_object($resource)){
-      
-    $items[$record->gbrowse_id]= $record->gbrowse_name;
-    
-  }
-
-  //GBrowse Instance Select List
-  $form['delete_tracks_field_set']['gbrowse_instances'] = array(
-    '#type' => 'select',
-    '#title' => t('Registered GBrowse Instances'),
-    '#options' => $items,
-    '#description' => t('Selected GBrowse Instances to be Loaded.'),
-    '#default_value' => $form_state['values']['gbrowse_instances'],
-  );
-  
-  //Set Instance Submit button
-  $form['delete_tracks_field_set']['submit_instance'] = array(
-    '#type' => 'submit',
-    '#value' => t('Set Instance')
-  );
-
-  //Creating Fieldset for multiple fields in form
-  $form['delete_tracks'] = array(
-    '#type' => ($form_state['storage']['gbrowse_id']) ? 'fieldset' : 'hidden',
-    '#title' => t('Track Specific Fields'),
-  );
-  
-  
-  $gbrowse_id = $form_state['storage']['gbrowse_id'];
-  
-  if ($gbrowse_id){
-  
-    $items = track_name_options($gbrowse_id);
-  
-  }else {
-    
-    $items = array();
-  
-  }
-  
-  //Track Name Select List
-  $form['delete_tracks']['track_line_number'] = array(
-    '#type' => 'select',
-    '#title' => t('Track Name'),
-    '#options' => $items,
-    '#description' => t('Name of Track to Remove '),
-    '#default_value' => $form_state['values']['gbrowse_id'],
-  );
-
-  //Remove Track button
-  $form['delete_tracks']['remove_track'] = array(
-    '#type' => 'submit',
-    '#value' => t('Remove Track')
-  );
-
-  return $form;
-
-}
-
-
-/**
-*Delete-GBrowse-Tracks
-*
-*@param $form
-*    The form that is completed in the above section
-*
-*  @param $form_state
-*    The state of the form, as it is completed by the user and will contain all of the user's
-*    selected infromation that is to be removed from the configuration file.    
-*
-*/
-function tripal_gbrowse_delete_tracks_form_submit($form, &$form_state) {
-
-  $form_state['storage']['gbrowse_id'] = $form_state['values']['gbrowse_instances'];
-  
-  //Checking that the "Remove Track" button was selected      
-  if($form_state['clicked_button']['#value']=='Remove Track'){
-        
-    //selecting GBrowse-ID from the database
-    $resource= db_fetch_object(db_query('SELECT * FROM {tripal_gbrowse_instances} WHERE gbrowse_id=%d', $form_state['storage']['gbrowse_id']));
-    
-    //putting contents of the configuration file into an variable
-    $config_file = (string) $resource->config_file;
-          
-    $read_file_handle = fopen($config_file,'r') or drupal_set_message("WARNING: Can not open file:" .$config_file, 'error');
-
-    $track_number = $form_state['values']['track_line_number'];
-  
-    $line_num = 0;
-  
-    //create temp file 
-    $new_conf_file = '/tmp/temp_config_file.temp';
-          
-    //making '.temp' file in the /tmp directory
-    $command = 'touch /tmp/temp_config_file.temp';
-          
-    exec($command);
-          
-    //Checking that the newly created file is writable    
-    if (is_writable($new_conf_file)) {
-          
-      //opening file for writing to
-      $write_file_handle = fopen($new_conf_file, 'w') or drupal_set_message("WARNING: Can not open file:" .$new_conf_file, 'error');
-          
-     }else{
-           
-       drupal_set_message("WARNING: Attempting to create a temporary file -insufficient permissions: ".$new_conf_file, 'error');                   
-     }    
-
-    while(!feof($read_file_handle)){
-  
-      $file_line = fgets($read_file_handle);
-            
-      $line_num++;
-      
-      if($line_num == $track_number){
-                          
-        $remove_track = TRUE;
-                  
-       }
-       
-       if(preg_match('/^\s*$/',$file_line)){
-                            
-         $remove_track=FALSE;
-                  
-       }
-       
-       if($remove_track==FALSE){
-                  
-         fwrite($write_file_handle, $file_line);              
-                  
-       }
-                                    
-    }
-          
-    $command = 'cp '.$new_conf_file.'  '.$config_file  ; 
-          
-    exec($command);
-          
-    $command = 'rm '.$new_conf_file ;
-          
-    exec($command);
-        
-  }
-      
-}
-
-
-/**
-*  Populate Track-Name List
-*
-* This section  takes a GBrowse ID so the coresponding configuration file can be accessed. Once it has been
-* obtained from the database, by the db_query() command. The configuration file is is searched for lines
-* that start with "[ ]". This corresponds to the framework of the conf file, as the Track Names are
-* enclosed within "[ ]". The file is then scanned from the spots that contain the "[ ]".  
-*
-*
-*  @param gbrowse_id
-*        The Selected GBrowse instance's identification
-*
-* @return
-*    $items() and array with the tracks that are in the selected GBrowse instance.
-*/
-function track_name_options($gbrowse_id) {
-
-  $items = array();
-
-  // Use GBrowse ID to get configuration filename  
-  $record = db_fetch_object(db_query('SELECT * FROM {tripal_gbrowse_instances} WHERE gbrowse_id=%d', $gbrowse_id));
-
-  //putting contents of the configuration file into an variable
-  $config_file = (string) $record->config_file;
-
-  $config_array = array();
-  
-  //command to select the lines that begin with '[' and have characters within the '[ ]'
-  $command = 'grep -n "^\[.*\]" ' .$config_file;
-    
-  //execution of the command
-  exec($command , $config_array);
-  
-  $config_array_size = count($config_array);
-        
-  //while the end-of-file has not been reached
-  for($i = 0 ; $i < $config_array_size; $i++){
-    
-    $file_line = $config_array[$i];      
-          
-        if ($is_track_definition){
-        
-            if(preg_match('/^(\d+):\[(.+)\]$/', $file_line, $matches)){
-  
-              $items[$matches[1]] = $matches[2];
-              
-            }
-        
-    }
-        
-        if(preg_match('/\[TRACK DEFAULTS\]/', $file_line)){
-            
-            $is_track_definition = TRUE;
-        }
-        
-  }
-  
-  return $items;
-}
-
-
-//-----------------------------------------------------------------------------
-//  END OF SOFTWARE
-//-----------------------------------------------------------------------------
-
-
-
-
-
-
-
-
-
-
-
-
-

+ 0 - 606
extensions/tripal_gbrowse/tripal_gbrowse.views.inc

@@ -1,606 +0,0 @@
-<?php
-
-
-/**
-* Developed by: Chad N.A Krilow at The University of Saskatchewan
-* Contact:cnk046@mail.usask.ca
-*/
-
-
-/**
- * Implements hook_views_data(): Describe tripal tables & fields to views
- *
- * @return array
- *   A data array which follows the structure outlined in the
- *   views2 documentation for this hook. Essentially, it's an array of table
- *   definitions keyed by tripal table name. Each table definition 
- *   includes basic details about the table, fields in that table and
- *   relationships between that table and others (joins)
- */ 
-function tripal_gbrowse_views_data() {
-  
-  //array to be filled with views data
-  $data = array();
-
-  // Basic table definition
-  $data['tripal_gbrowse_instances']['table']['group'] = 'Tripal GBrowse';
-  $data['tripal_gbrowse_instances']['table']['base'] = array(
-    'field' => 'gbrowse_id',
-    'title' => 'Tripal GBrowse',
-    'help' => 'A GMOD GBrowse instance registered with Tripal',                                                                                                                                                                          
-  );
-
-  // Join the node table to chado stock
-  $data['node']['table']['join']['tripal_gbrowse_instances'] = array(
-  	'left_field' => 'nid',
-  	'field' => 'nid',
-  );
-
-  // Field: database_name(varchar 255)
-  $data['tripal_gbrowse_instances']['database_name'] = array(
-    'title' => 'Database Name',
-    'help' => 'The specified name of the Database',
-    'field' => array(
-       'handler' => 'views_handler_field',
-       'click sortable' => TRUE,
-     ),
-     'sort' => array(
-       'handler' => 'views_handler_sort',
-     ),
-     'filter' => array(
-       'handler' => 'views_handler_filter_string',
-     ),
-     'argument' => array(
-       'handler' => 'views_handler_argument_string',
-     ),
-  );
-  
-    // Field: database_user(varchar 255)
-  $data['tripal_gbrowse_instances']['database_user'] = array(
-    'title' => 'Database User',
-    'help' => 'The Registered User of the Database',
-    'field' => array(
-       'handler' => 'views_handler_field',
-       'click sortable' => TRUE,
-     ),
-     'sort' => array(
-       'handler' => 'views_handler_sort',
-     ),
-     'filter' => array(
-       'handler' => 'views_handler_filter_string',
-     ),
-     'argument' => array(
-       'handler' => 'views_handler_argument_string',
-     ),
-  );
-  
-  // Field: user_password(varchar 255)
-  $data['tripal_gbrowse_instances']['user_password'] = array(
-    'title' => 'User Password',
-    'help' => 'The user password',
-    'field' => array(
-       'handler' => 'views_handler_field',
-       'click sortable' => TRUE,
-     ),
-     'sort' => array(
-       'handler' => 'views_handler_sort',
-     ),
-     'filter' => array(
-       'handler' => 'views_handler_filter_string',
-     ),
-     'argument' => array(
-       'handler' => 'views_handler_argument_string',
-     ),
-  );
-  
-  // Field: gbrowse_name(varchar 255)
-  $data['tripal_gbrowse_instances']['gbrowse_name'] = array(
-    'title' => 'GBrowse Instance Name',
-    'help' => 'The Name of the Specified GBrowse Instance',
-    'field' => array(
-       'handler' => 'views_handler_field',
-       'click sortable' => TRUE,
-     ),
-     'sort' => array(
-       'handler' => 'views_handler_sort',
-     ),
-     'filter' => array(
-       'handler' => 'views_handler_filter_string',
-     ),
-     'argument' => array(
-       'handler' => 'views_handler_argument_string',
-     ),
-  );
-  
-  // Field: gbrowse_link(varchar 255)
-  $data['tripal_gbrowse_instances']['gbrowse_link'] = array(
-    'title' => 'GBrowse Instance Link',
-    'help' => 'The Link to the GBrowse Instance',
-    'field' => array(
-       'handler' => 'views_handler_field',
-       'click sortable' => TRUE,
-     ),
-     'sort' => array(
-       'handler' => 'views_handler_sort',
-     ),
-     'filter' => array(
-       'handler' => 'views_handler_filter_string',
-     ),
-     'argument' => array(
-       'handler' => 'views_handler_argument_string',
-     ),
-  );
-    
-  // Field: config_file(varchar 255)
-  $data['tripal_gbrowse_instances']['config_file'] = array(
-    'title' => 'Configuration File',
-    'help' => 'The Configuration File Associated with the GBrowse Instance',
-    'field' => array(
-       'handler' => 'views_handler_field',
-       'click sortable' => TRUE,
-     ),
-     'sort' => array(
-       'handler' => 'views_handler_sort',
-     ),
-     'filter' => array(
-       'handler' => 'views_handler_filter_string',
-     ),
-     'argument' => array(
-       'handler' => 'views_handler_argument_string',
-     ),
-  );
-  
-  return $data;
-  
-}
-
-
-/**
- * Implements hook_views_default_views(): Describe tripal tables & fields to views
- *
- * This function represents the "Default View" that the user will see when on the drupal site.
- *
- */
-function tripal_gbrowse_views_default_views() {
-  
-  $views = array();
-  
-  $view = new view;
-
-  $view->name = 'all_tripal_gbrowse_instances';
-  $view->description = '';
-  $view->tag = '';
-  $view->view_php = '';
-  $view->base_table = 'tripal_gbrowse_instances';
-  $view->is_cacheable = FALSE;
-  $view->api_version = 2;
-  $view->disabled = FALSE; /* Edit this to true to make a default view disabled initially */
-  $handler = $view->new_display('default', 'Defaults', 'default');
-  
-  $handler->override_option('fields', array(
-  'gbrowse_name' => array(
-    'label' => 'Instance Name',
-    'alter' => array(
-      'alter_text' => 0,
-      'text' => '',
-      'make_link' => 0,
-      'path' => '',
-      'link_class' => '',
-      'alt' => '',
-      'prefix' => '',
-      'suffix' => '',
-      'target' => '',
-      'help' => '',
-      'trim' => 0,
-      'max_length' => '',
-      'word_boundary' => 1,
-      'ellipsis' => 1,
-      'html' => 0,
-      'strip_tags' => 0,
-    ),
-    'empty' => '',
-    'hide_empty' => 0,
-    'empty_zero' => 0,
-    'exclude' => 0,
-    'id' => 'gbrowse_name',
-    'table' => 'tripal_gbrowse_instances',
-    'field' => 'gbrowse_name',
-    'relationship' => 'none',
-    'override' => array(
-      'button' => 'Override',
-    ),
-  ),
-  'database_name' => array(
-    'label' => 'Database Name',
-    'alter' => array(
-      'alter_text' => 0,
-      'text' => '',
-      'make_link' => 0,
-      'path' => '',
-      'link_class' => '',
-      'alt' => '',
-      'prefix' => '',
-      'suffix' => '',
-      'target' => '',
-      'help' => '',
-      'trim' => 0,
-      'max_length' => '',
-      'word_boundary' => 1,
-      'ellipsis' => 1,
-      'html' => 0,
-      'strip_tags' => 0,
-    ),
-    'empty' => '',
-    'hide_empty' => 0,
-    'empty_zero' => 0,
-    'exclude' => 0,
-    'id' => 'database_name',
-    'table' => 'tripal_gbrowse_instances',
-    'field' => 'database_name',
-    'relationship' => 'none',
-  ),
-  'gbrowse_link' => array(
-    'label' => 'GBrowse Instance Link',
-    'alter' => array(
-      'alter_text' => 0,
-      'text' => '',
-      'make_link' => 0,
-      'path' => '',
-      'link_class' => '',
-      'alt' => '',
-      'prefix' => '',
-      'suffix' => '',
-      'target' => '',
-      'help' => '',
-      'trim' => 0,
-      'max_length' => '',
-      'word_boundary' => 1,
-      'ellipsis' => 1,
-      'html' => 0,
-      'strip_tags' => 0,
-    ),
-    'empty' => '',
-    'hide_empty' => 0,
-    'empty_zero' => 0,
-    'exclude' => 0,
-    'id' => 'gbrowse_link',
-    'table' => 'tripal_gbrowse_instances',
-    'field' => 'gbrowse_link',
-    'relationship' => 'none',
-  ),
-));
-
-$handler->override_option('filters', array(
-  'database_name' => array(
-    'operator' => '=',
-    'value' => '',
-    'group' => '0',
-    'exposed' => TRUE,
-    'expose' => array(
-      'use_operator' => 0,
-      'operator' => 'database_name_op',
-      'identifier' => 'database_name',
-      'label' => 'GBrowse: Database Name',
-      'optional' => 1,
-      'remember' => 0,
-    ),
-    'case' => 1,
-    'id' => 'database_name',
-    'table' => 'tripal_gbrowse_instances',
-    'field' => 'database_name',
-    'relationship' => 'none',
-    'override' => array(
-      'button' => 'Override',
-    ),
-  ),
-  'gbrowse_name' => array(
-    'operator' => '=',
-    'value' => '',
-    'group' => '0',
-    'exposed' => TRUE,
-    'expose' => array(
-      'use_operator' => 0,
-      'operator' => 'gbrowse_name_op',
-      'identifier' => 'gbrowse_name',
-      'label' => 'GBrowse: Instance Name',
-      'optional' => 1,
-      'remember' => 0,
-    ),
-    'case' => 1,
-    'id' => 'gbrowse_name',
-    'table' => 'tripal_gbrowse_instances',
-    'field' => 'gbrowse_name',
-    'override' => array(
-      'button' => 'Override',
-    ),
-    'relationship' => 'none',
-  ),
-  'database_user' => array(
-    'operator' => '=',
-    'value' => '',
-    'group' => '0',
-    'exposed' => TRUE,
-    'expose' => array(
-      'use_operator' => 0,
-      'operator' => 'database_user_op',
-      'identifier' => 'database_user',
-      'label' => 'GBrowse: Database User',
-      'optional' => 1,
-      'remember' => 0,
-    ),
-    'case' => 1,
-    'id' => 'database_user',
-    'table' => 'tripal_gbrowse_instances',
-    'field' => 'database_user',
-    'override' => array(
-      'button' => 'Override',
-    ),
-    'relationship' => 'none',
-  ),
-));
-
-  $handler->override_option('access', array(
-    'type' => 'perm',
-    'perm' => 'access tripal_gbrowse content',
-  ));
-
-  $handler->override_option('cache', array(
-    'type' => 'none',
-  ));
-  
-$handler->override_option('empty', 'No GBrowse instances match these criteria.');
-
-$handler->override_option('empty_format', '1');
-
-$handler->override_option('use_pager', '1');
-
-$handler->override_option('style_plugin', 'table');
-
-  $handler->override_option('style_options', array(
-    'grouping' => '',
-    'override' => 1,
-    'sticky' => 0,
-    'order' => 'asc',
-    'columns' => array(
-      'gbrowse_name' => 'gbrowse_name',
-      'database_name' => 'database_name',
-      'gbrowse_link' => 'gbrowse_link',
-    ),
-    'info' => array(
-      'gbrowse_name' => array(
-        'sortable' => 1,
-        'separator' => '',
-      ),
-      'database_name' => array(
-        'sortable' => 1,
-        'separator' => '',
-      ),
-      'gbrowse_link' => array(
-        'sortable' => 1,
-        'separator' => '',
-      ),
-    ),
-    'default' => 'gbrowse_name',
-  ));
-
-$handler = $view->new_display('page', 'Page', 'page_1');
-
-  $handler->override_option('fields', array(
-    'title' => array(
-      'label' => 'GBrowse Instance Name',
-      'alter' => array(
-        'alter_text' => 0,
-        'text' => '',
-        'make_link' => 0,
-        'path' => '',
-        'link_class' => '',
-        'alt' => '',
-        'prefix' => '',
-        'suffix' => '',
-      	'target' => '',
-				'help' => '',
-      	'trim' => 0,
-      	'max_length' => '',
-      	'word_boundary' => 1,
-      	'ellipsis' => 1,
-      	'html' => 0,
-      	'strip_tags' => 0,
-    	),
-			'empty' => '',
-			'hide_empty' => 0,
-			'empty_zero' => 0,
-			'link_to_node' => 1,
-			'exclude' => 0,
-			'id' => 'title',
-			'table' => 'node',
-			'field' => 'title',
-			'override' => array(
-				'button' => 'Use default',
-			),
-			'relationship' => 'none',
-		),
-		'database_name' => array(
-			'label' => 'Database Name',
-			'alter' => array(
-				'alter_text' => 0,
-				'text' => '',
-				'make_link' => 0,
-				'path' => '',
-				'link_class' => '',
-				'alt' => '',
-				'prefix' => '',
-				'suffix' => '',
-				'target' => '',
-				'help' => '',
-				'trim' => 0,
-				'max_length' => '',
-				'word_boundary' => 1,
-				'ellipsis' => 1,
-				'html' => 0,
-				'strip_tags' => 0,
-			),
-			'empty' => '',
-			'hide_empty' => 0,
-			'empty_zero' => 0,
-			'exclude' => 0,
-			'id' => 'database_name',
-			'table' => 'tripal_gbrowse_instances',
-			'field' => 'database_name',
-			'relationship' => 'none',
-		),
-		'gbrowse_link' => array(
-			'label' => 'GBrowse Instance Link',
-			'alter' => array(
-				'alter_text' => 0,
-				'text' => '',
-				'make_link' => 1,
-				'path' => '[gbrowse_link]',
-				'link_class' => '',
-				'alt' => '',
-				'prefix' => '',
-				'suffix' => '',
-				'target' => '',
-				'help' => '',
-				'trim' => 0,
-				'max_length' => '',
-				'word_boundary' => 1,
-				'ellipsis' => 1,
-				'html' => 0,
-				'strip_tags' => 0,
-			),
-			'empty' => '',
-			'hide_empty' => 1,
-			'empty_zero' => 0,
-			'exclude' => 0,
-			'id' => 'gbrowse_link',
-			'table' => 'tripal_gbrowse_instances',
-			'field' => 'gbrowse_link',
-			'relationship' => 'none',
-			'override' => array(
-				'button' => 'Use default',
-			),
-		),
-		'changed' => array(
-			'label' => 'Updated date',
-			'alter' => array(
-				'alter_text' => 0,
-				'text' => '',
-				'make_link' => 0,
-				'path' => '',
-				'link_class' => '',
-				'alt' => '',
-				'prefix' => '',
-				'suffix' => '',
-				'target' => '',
-				'help' => '',
-				'trim' => 0,
-				'max_length' => '',
-				'word_boundary' => 1,
-				'ellipsis' => 1,
-				'html' => 0,
-				'strip_tags' => 0,
-			),
-			'empty' => '',
-			'hide_empty' => 0,
-			'empty_zero' => 0,
-			'date_format' => 'custom',
-			'custom_date_format' => 'D, d M Y ',
-			'exclude' => 0,
-			'id' => 'changed',
-			'table' => 'node',
-			'field' => 'changed',
-			'override' => array(
-				'button' => 'Use default',
-			),
-			'relationship' => 'none',
-		),
-		'created' => array(
-			'label' => 'Post date',
-			'alter' => array(
-				'alter_text' => 0,
-				'text' => '',
-				'make_link' => 0,
-				'path' => '',
-				'link_class' => '',
-				'alt' => '',
-				'prefix' => '',
-				'suffix' => '',
-				'target' => '',
-				'help' => '',
-				'trim' => 0,
-				'max_length' => '',
-				'word_boundary' => 1,
-				'ellipsis' => 1,
-				'html' => 0,
-				'strip_tags' => 0,
-			),
-			'empty' => '',
-			'hide_empty' => 0,
-			'empty_zero' => 0,
-			'date_format' => 'custom',
-			'custom_date_format' => 'D, d M Y ',
-			'exclude' => 0,
-			'id' => 'created',
-			'table' => 'node',
-			'field' => 'created',
-			'override' => array(
-				'button' => 'Use default',
-			),
-			'relationship' => 'none',
-		),
-		'edit_node' => array(
-			'label' => 'Edit link',
-			'alter' => array(
-				'alter_text' => 0,
-				'text' => '',
-				'make_link' => 1,
-				'path' => '[gbrowse_link]',
-				'link_class' => '',
-				'alt' => '',
-				'prefix' => '',
-				'suffix' => '',
-				'target' => '',
-				'help' => '',
-				'trim' => 0,
-				'max_length' => '',
-				'word_boundary' => 1,
-				'ellipsis' => 1,
-				'html' => 0,
-				'strip_tags' => 0,
-			),
-			'empty' => '',
-			'hide_empty' => 1,
-			'empty_zero' => 0,
-			'text' => '',
-			'exclude' => 0,
-			'id' => 'edit_node',
-			'table' => 'node',
-			'field' => 'edit_node',
-			'override' => array(
-				'button' => 'Use default',
-			),
-			'relationship' => 'none',
-		),
-	));
-	$handler->override_option('path', 'gbrowse_instances');
-	$handler->override_option('menu', array(
-		'type' => 'normal',
-		'title' => 'GBrowse Instances',
-		'description' => '',
-		'weight' => '0',
-		'name' => 'primary-links',
-	));
-	$handler->override_option('tab_options', array(
-		'type' => 'none',
-		'title' => '',
-		'description' => '',
-		'weight' => 0,
-		'name' => 'navigation',
-	));
-    
-    
-  $views[$view->name] = $view;  
-  
-  return $views;
-
-}

+ 47 - 7
tripal_analysis/tripal_analysis.admin.inc

@@ -1,11 +1,8 @@
 <?php
-//
-// Copyright 2009 Clemson University
-//
 
 /**
  * @file
- * @todo Add file header description
+ * Contains functions displaying administrative pages and forms
  */
 
 /**
@@ -73,8 +70,8 @@ function tripal_analysis_module_description_page() {
             </ul>
             </p>';
 
-   $text .= '<h3>Page Customizations</h3>';
-   $text .= '<p>There are several ways to customize the look-and-feel for the way Chado data is presented through Tripal.
+  $text .= '<h3>Page Customizations</h3>';
+  $text .= '<p>There are several ways to customize the look-and-feel for the way Chado data is presented through Tripal.
              Below is a description of several methods.  These methods may be used in conjunction with one another to
              provide fine-grained control.
              <ul>
@@ -136,12 +133,16 @@ function tripal_analysis_module_description_page() {
   return $text;
 }
 
-/*******************************************************************************
+/**
  * Administration page callbacks for the Tripal Analysis module
+ *
  * We have defined a hook_get_settings() function. When a sub-module
  * is enabled, we'll look for this function to provide a form for the
  * administrative setting.
  *
+ * @return
+ *  A form API array describing an administrative form
+ *
  * @ingroup tripal_analysis
  */
 function tripal_analysis_admin() {
@@ -209,6 +210,13 @@ function tripal_analysis_admin() {
 }
 
 /**
+ * Displays the Set Drupal Taxonomy for Analysis Features From
+ *
+ * @param $form
+ *  The administrative form as it is currently
+ *
+ * @return
+ *  A form API array describing an administrative form
  *
  * @ingroup tripal_analysis
  */
@@ -254,7 +262,15 @@ function get_tripal_analysis_admin_form_taxonomy_set(&$form) {
       '#weight'      => 3
   );
 }
+
 /**
+ * The "Reindex Analysis Nodes" form
+ *
+ * @param $form
+ *  The administrative form as it is currently
+ *
+ * @return
+ *  A form API array describing an administrative form
  *
  * @ingroup tripal_analysis
  */
@@ -298,7 +314,15 @@ function get_tripal_analysis_admin_form_reindex_set(&$form) {
       '#weight' => 3,
   );
 }
+
 /**
+ * The "Clean-up orphaned analysis & nodes" Form
+ *
+ * @param $form
+ *  The administrative form as it is currently
+ *
+ * @return
+ *  A form API array describing an administrative form
  *
  * @ingroup tripal_analysis
  */
@@ -322,7 +346,15 @@ function get_tripal_analysis_admin_form_cleanup_set(&$form) {
       '#weight' => 2,
   );
 }
+
 /**
+ * The "sync Analysis in chado with drupal" form
+ *
+ * @param $form
+ *  The administrative form as it is currently
+ *
+ * @return
+ *  A form API array describing an administrative form
  *
  * @ingroup tripal_analysis
  */
@@ -400,7 +432,15 @@ function get_tripal_analysis_admin_form_sync_set(&$form) {
     );
   }
 }
+
 /**
+ * Validate the administrative form
+ * @todo Stephen: Why is validate used rather then submit?
+ *
+ * @param $form
+ *   The form API array of the form to be validated
+ * @form_state
+ *   The user submitted values
  *
  * @ingroup tripal_analysis
  */

+ 111 - 110
tripal_analysis/tripal_analysis.api.inc

@@ -2,17 +2,119 @@
 
 /**
  * @file
- * @todo Add file header description
- */
-
-/**
+ * API functions relating to Analysis'
+ *
  * @defgroup tripal_analysis_api Analysis Module API
  * @ingroup tripal_analysis
  * @ingroup tripal_api
  */
-/****************************************************************************
+
+/**
+ * Retrieve properties of a given type for a given analysis
+ *
+ * @param $analysis_id
+ *    The analysis_id of the properties you would like to retrieve
+ * @param $property
+ *    The cvterm name of the properties to retrieve
+ *
+ * @return
+ *    An analysis chado variable with the specified properties expanded
+ *
+ * @ingroup tripal_analysis_api
+ */
+function tripal_analysis_get_property($analysis_id, $property) {
+  return tripal_core_get_property('analysis', $analysis_id, $property, 'tripal');
+}
+
+/**
+ * Insert a given property
+ *
+ * @param $analysis_id
+ *   The analysis_id of the property to insert
+ * @param $property
+ *   The cvterm name of the property to insert
+ * @param $value
+ *   The value of the property to insert
+ * @param $update_if_present
+ *   A boolean indicated whether to update the record if it's already present
+ *
+ * @return
+ *   True of success, False otherwise
+ *
+ * @ingroup tripal_analysis_api
+ */
+function tripal_analysis_insert_property($analysis_id, $property, $value, $update_if_present = 0) {
+    return tripal_core_insert_property('analysis', $analysis_id, $property, 'tripal', $value, $update_if_present);
+}
+
+/**
+ * Update a given property
+ *
+ * @param $analysis_id
+ *   The analysis_id of the property to update
+ * @param $property
+ *   The cvterm name of the property to update
+ * @param $value
+ *   The value of the property to update
+ * @param $insert_if_missing
+ *   A boolean indicated whether to insert the record if it's absent
+ *
+ * Note: The property will be identified using the unique combination of the $analysis_id and $property
+ * and then it will be updated with the supplied value
+ *
+ * @return
+ *   True of success, False otherwise
+ *
+ * @ingroup tripal_analysis_api
+ */
+function tripal_analysis_update_property($analysis_id, $property, $value, $insert_if_missing = 0) {
+  return tripal_core_update_property('analysis', $analysis_id, $property, 'tripal', $value, $insert_if_missing);
+}
+
+/**
+ * Delete a given property
+ *
+ * @param $analysis_id
+ *   The analysis_id of the property to delete
+ * @param $property
+ *   The cvterm name of the property to delete
+ *
+ * Note: The property will be identified using the unique combination of the $analysis_id and $property
+ * and then it will be deleted
+ *
+ * @return
+ *   True of success, False otherwise
+ *
+ * @ingroup tripal_analysis_api
+ */
+function tripal_analysis_delete_property($analysis_id, $property) {
+  return tripal_core_delete_property('analysis', $analysis_id, $property, 'tripal');
+}
+
+/**
+ * Retreives the node of a sync'ed analysis
+ *
+ * @param $analysis_id
+ *   The analysis_id of the property to delete
+ *
+ * @return
+ *   node of analysis on success, null otherwise
+ *
+ * @ingroup tripal_analysis_api
+ */
+function tripal_analysis_get_node($analysis_id) {
+  $sql = "SELECT *
+           FROM chado_analysis CA
+              INNER JOIN node N on CA.nid = N.nid
+           WHERE analysis_id = %d";
+  $node = db_fetch_object(db_query($sql, $analysis_id));
+  return $node;
+}
+
+/**
  * @section Chado Table Descriptions
- ****************************************************************************/
+ */
+
 /**
  * Implements hook_chado_analysis_schema()
  * Purpose: To add descriptions and foreign keys to default table description
@@ -39,7 +141,7 @@ function tripal_analysis_chado_analysis_schema() {
   return $description;
 }
 
- /****************************************************************************
+/**
  * Implements hook_chado_analysisfeature_schema()
  * Purpose: To add descriptions and foreign keys to default table description
  * Note: This array will be merged with the array from all other implementations
@@ -69,7 +171,7 @@ function tripal_analysis_chado_analysisfeature_schema() {
   return $description;
 }
 
- /****************************************************************************
+/**
  * Implements hook_chado_analysisfeatureprop_schema()
  * Purpose: To add descriptions and foreign keys to default table description
  * Note: This array will be merged with the array from all other implementations
@@ -99,7 +201,7 @@ function tripal_analysis_chado_analysisfeatureprop_schema() {
 }
 
 
- /****************************************************************************
+/**
   * Implements hook_chado_analysisprop_schema()
   * Purpose: To add descriptions and foreign keys to default table description
   * Note: This array will be merged with the array from all other implementations
@@ -128,104 +230,3 @@ function tripal_analysis_chado_analysisprop_schema() {
 
   return $description;
 }
-
-/**
- * Retrieve properties of a given type for a given analysis
- *
- * @param $analysis_id
- *    The analysis_id of the properties you would like to retrieve
- * @param $property
- *    The cvterm name of the properties to retrieve
- *
- * @return
- *    An analysis chado variable with the specified properties expanded
- *
- * @ingroup tripal_analysis_api
- */
-function tripal_analysis_get_property($analysis_id, $property) {
-   return tripal_core_get_property('analysis', $analysis_id, $property, 'tripal');
-}
-
-/**
- * Insert a given property
- *
- * @param $analysis_id
- *   The analysis_id of the property to insert
- * @param $property
- *   The cvterm name of the property to insert
- * @param $value
- *   The value of the property to insert
- * @param $update_if_present
- *   A boolean indicated whether to update the record if it's already present
- *
- * @return
- *   True of success, False otherwise
- *
- * @ingroup tripal_analysis_api
- */
-function tripal_analysis_insert_property($analysis_id, $property, $value, $update_if_present = 0) {
-    return tripal_core_insert_property('analysis', $analysis_id, $property, 'tripal', $value, $update_if_present);
-}
-
-/**
- * Update a given property
- *
- * @param $analysis_id
- *   The analysis_id of the property to update
- * @param $property
- *   The cvterm name of the property to update
- * @param $value
- *   The value of the property to update
- * @param $insert_if_missing
- *   A boolean indicated whether to insert the record if it's absent
- *
- * Note: The property will be identified using the unique combination of the $analysis_id and $property
- * and then it will be updated with the supplied value
- *
- * @return
- *   True of success, False otherwise
- *
- * @ingroup tripal_analysis_api
- */
-function tripal_analysis_update_property($analysis_id, $property, $value, $insert_if_missing = 0) {
-   return tripal_core_update_property('analysis', $analysis_id, $property, 'tripal', $value, $insert_if_missing);
-}
-
-/**
- * Delete a given property
- *
- * @param $analysis_id
- *   The analysis_id of the property to delete
- * @param $property
- *   The cvterm name of the property to delete
- *
- * Note: The property will be identified using the unique combination of the $analysis_id and $property
- * and then it will be deleted
- *
- * @return
- *   True of success, False otherwise
- *
- * @ingroup tripal_analysis_api
- */
-function tripal_analysis_delete_property($analysis_id, $property) {
-   return tripal_core_delete_property('analysis', $analysis_id, $property, 'tripal');
-}
-/**
- * Retreives the node of a sync'ed analysis
- *
- * @param $analysis_id
- *   The analysis_id of the property to delete
- *
- * @return
- *   node of analysis on success, null otherwise
- *
- * @ingroup tripal_analysis_api
- */
-function tripal_analysis_get_node($analysis_id) {
-   $sql = "SELECT *
-           FROM chado_analysis CA
-              INNER JOIN node N on CA.nid = N.nid
-           WHERE analysis_id = %d";
-   $node = db_fetch_object(db_query($sql, $analysis_id));
-   return $node;
-}

+ 70 - 65
tripal_analysis/tripal_analysis.install

@@ -1,10 +1,10 @@
 <?php
 /**
  * @file
- * @todo Add file header description
+ * Implements hooks from the Schema API
  */
 
-/*******************************************************************************
+/**
  * Implementation of hook_install().
  */
 function tripal_analysis_install() {
@@ -20,7 +20,7 @@ function tripal_analysis_install() {
   // table is used to store Blast xml and Interpro html/goterms
   $previous_db = tripal_db_set_active('chado');
   if (!db_table_exists('analysisfeatureprop')) {
-     $sql = "CREATE TABLE {analysisfeatureprop} (".
+    $sql = "CREATE TABLE {analysisfeatureprop} (".
             "  analysisfeatureprop_id SERIAL PRIMARY KEY, ".
             "  analysisfeature_id INTEGER NOT NULL REFERENCES analysisfeature(analysisfeature_id) ON DELETE CASCADE DEFERRABLE INITIALLY DEFERRED, ".
             "  type_id INTEGER NOT NULL REFERENCES cvterm(cvterm_id) ON DELETE CASCADE DEFERRABLE INITIALLY DEFERRED, ".
@@ -28,17 +28,17 @@ function tripal_analysis_install() {
             "  rank INTEGER NOT NULL, ".
             "  CONSTRAINT analysisfeature_id_type_id_rank UNIQUE(analysisfeature_id, type_id, rank)".
             ")";
-     db_query($sql);
+    db_query($sql);
   }
   tripal_db_set_active($previous_db);
 
-   tripal_cv_add_cvterm(array('name' => 'analysis_type', 'def' => 'The type of analysis was performed. This value is automatically set by each Tripal Analysis module and should be equal to the module name (e.g. tripal_analysis_blast, tripal_analysis_go).'), 'tripal', 0, 1, 'tripal');
+  tripal_cv_add_cvterm(array('name' => 'analysis_type', 'def' => 'The type of analysis was performed. This value is automatically set by each Tripal Analysis module and should be equal to the module name (e.g. tripal_analysis_blast, tripal_analysis_go).'), 'tripal', 0, 1, 'tripal');
   tripal_cv_add_cvterm(array('name' => 'analysis_date', 'def' => 'The date that an analysis was performed.'), 'tripal', 0, 1, 'tripal');
   tripal_cv_add_cvterm(array('name' => 'analysis_short_name', 'def' => 'A computer legible (no spaces ' .
       'or special characters) abbreviation for the analysis.'), 'tripal', 0, 1 , 'tripal');
 }
 
-/*******************************************************************************
+/**
  * Implementation of hook_uninstall().
  */
 function tripal_analysis_uninstall() {
@@ -54,90 +54,95 @@ function tripal_analysis_uninstall() {
   }
 }
 
-/*******************************************************************************
- * Implementation of hook_schema() creates two tables. chado_analysis table
- * stores nodes that are also saved in the analysis table of chado database.
- * tripal_analysis table stores the sub-module names, such as
- * tripal_analysis_blast, that are registered with this module.
+/**
+ * Implementation of hook_schema() creates two tables.
+ *
+ * - chado_analysis table
+ *     stores nodes that are also saved in the analysis table of chado database.
+ * - tripal_analysis table
+ *     stores the sub-module names, such as tripal_analysis_blast, that are registered
+ *     with this module.
  */
 function tripal_analysis_schema() {
   // chado_analysis table
   $schema['chado_analysis'] = array(
-      'fields' => array(
-         'vid' => array(
-            'type' => 'int',
-            'unsigned' => TRUE,
-            'not null' => TRUE,
-            'default' => 0
-  ),
-         'nid' => array(
-            'type' => 'int',
-            'unsigned' => TRUE,
-            'not null' => TRUE,
-            'default' => 0
-  ),
-         'analysis_id' => array(
-            'type' => 'int',
-            'not null' => TRUE,
-            'default' => 0
-  )
-  ),
-      'indexes' => array(
-         'analysis_id' => array('analysis_id')
-  ),
-      'unique keys' => array(
-         'nid_vid' => array('nid', 'vid'),
-         'vid' => array('vid')
-  ),
-      'primary key' => array('nid'),
+    'fields' => array(
+      'vid' => array(
+        'type' => 'int',
+        'unsigned' => TRUE,
+        'not null' => TRUE,
+        'default' => 0
+      ),
+      'nid' => array(
+        'type' => 'int',
+        'unsigned' => TRUE,
+        'not null' => TRUE,
+        'default' => 0
+      ),
+      'analysis_id' => array(
+        'type' => 'int',
+        'not null' => TRUE,
+        'default' => 0
+      )
+    ),
+    'indexes' => array(
+      'analysis_id' => array('analysis_id')
+    ),
+    'unique keys' => array(
+      'nid_vid' => array('nid', 'vid'),
+      'vid' => array('vid')
+    ),
+    'primary key' => array('nid'),
   );
 
   // tripal_analysis table
   $schema['tripal_analysis'] = array(
-      'description' => t('Table to store analysis sub-modules'),
-      'fields' => array(
-         'modulename' => array(
-            'type' => 'text',
-            'size' => 'small',
-            'not null' => TRUE,
-            'description' => t('The module name. Tripal Analysis will use the '.
-                               'module name to call module_setting_form()')
-  )
-  ),
-      'unique keys' => array(
-         'modulename' => array('modulename')
-  )
+    'description' => t('Table to store analysis sub-modules'),
+    'fields' => array(
+      'modulename' => array(
+        'type' => 'text',
+        'size' => 'small',
+        'not null' => TRUE,
+        'description' => t('The module name. Tripal Analysis will use the '.
+                            'module name to call module_setting_form()')
+      )
+    ),
+    'unique keys' => array(
+      'modulename' => array('modulename')
+    )
   );
+
   return $schema;
 }
 
-/*******************************************************************************
+/**
  * Implementation of hook_requirements(). Make sure 'Tripal Core' is enabled
  * before installation
+ * @todo: Check if this is needed
  */
 function tripal_analysis_requirements($phase) {
-   $requirements = array();
-   if ($phase == 'install') {
-      if (!function_exists('tripal_create_moddir')) {
-         $requirements ['tripal_analysis'] = array(
+  $requirements = array();
+  if ($phase == 'install') {
+    if (!function_exists('tripal_create_moddir')) {
+      $requirements ['tripal_analysis'] = array(
             'title' => "tripal_analysis",
             'value' => "error. Some required modules are just being installed. Please try again.",
             'severity' => REQUIREMENT_ERROR,
-         );
+      );
       }
-   }
-   return $requirements;
+  }
+  return $requirements;
 }
 
-/*******************************************************************************
+/**
  * Provide update script for adding new cvterms
  */
 function tripal_analysis_update_6001() {
    // we have some new cvterms to add
-   tripal_cv_add_cvterm(array('name' => 'based_on_analysis', 'def' => 'The analysis that this analysis was based on. For example, blast/kegg/interpro analyses are based on a unigene analysis. The unigene analysis_id should be stored in analysisprop as the rank using this cvterm. The name of said unigene analysis can be inserted as the value in analysisprop.'), 'tripal', 0, 1, 'tripal');
-   tripal_cv_add_cvterm(array('name' => 'additional_files', 'def' => 'Additional files for this analysis. Each file should be separated by a semi-colon and have this format: <file description>, <file path>;'), 'tripal', 0, 1, 'tripal');
-   $ret = array(
+  tripal_cv_add_cvterm(array('name' => 'based_on_analysis', 'def' => 'The analysis that this analysis was based on. For example, blast/kegg/interpro analyses are based on a unigene analysis. The unigene analysis_id should be stored in analysisprop as the rank using this cvterm. The name of said unigene analysis can be inserted as the value in analysisprop.'), 'tripal', 0, 1, 'tripal');
+  tripal_cv_add_cvterm(array('name' => 'additional_files', 'def' => 'Additional files for this analysis. Each file should be separated by a semi-colon and have this format: <file description>, <file path>;'), 'tripal', 0, 1, 'tripal');
+  $ret = array(
       '#finished' => 1,
-   );
-   return $ret;
+  );
+  return $ret;
 }

+ 130 - 105
tripal_analysis/tripal_analysis.module

@@ -3,9 +3,7 @@
 /**
  * @file
  * Contains all the main hook implementations for the tripal_analysis module
- */
-
-/**
+ *
  * @defgroup tripal_analysis Analysis Module
  * @{
  * Provides functions for managing chado analysis' including creating details pages for each one
@@ -16,39 +14,45 @@
 require('tripal_analysis.api.inc');
 require('tripal_analysis_privacy.inc');
 
-
 /**
+ * Register tripal_analysis sub-modules
  *
+ * @param $modulename
+ *  The name of the module to be registered as a tripal analysis submodule
  *
  * @ingroup tripal_analysis
  */
 function tripal_analysis_register_child($modulename) {
-   $sql = "INSERT INTO {tripal_analysis} (modulename) VALUES ('%s')";
-   db_query($sql, $modulename);
+  $sql = "INSERT INTO {tripal_analysis} (modulename) VALUES ('%s')";
+  db_query($sql, $modulename);
 }
+
 /**
+ * Un-register a tripal analysis sub-module
  *
+ * @param $modulename
+ *  The name of the module to un-register
  *
  * @ingroup tripal_analysis
  */
 function tripal_analysis_unregister_child($modulename) {
-   if (db_table_exists('tripal_analysis')) {
+  if (db_table_exists('tripal_analysis')) {
       $sql = "DELETE FROM {tripal_analysis} WHERE modulename = '%s'";
       db_query($sql, $modulename);
-   }
+  }
 }
 
 /**
+ * Add tripal javascript to page headers
  *
  * @ingroup tripal_analysis
  */
 function tripal_analysis_init() {
-   drupal_add_js(drupal_get_path('theme', 'tripal') . '/js/tripal_analysis.js');
+  drupal_add_js(drupal_get_path('theme', 'tripal') . '/js/tripal_analysis.js');
 }
 
 /**
- * tripal_analysis_menu()
- * HOOK: Implementation of hook_menu()
+ * Implementation of hook_menu().
  * Entry points and paths of the module
  *
  * @ingroup tripal_analysis
@@ -57,14 +61,14 @@ function tripal_analysis_menu() {
   // Display available analyses
   $items['analyses'] = array(
       'menu_name' => ('primary-links'), //Enable the 'Analysis' primary link
-      'title' => t('Analyses'),
+      'title' => 'Analyses',
       'page callback' => 'tripal_analysis_show_analyses',
       'access arguments' => array('access chado_analysis content'),
       'type' => MENU_NORMAL_ITEM
   );
   //Sync analysis
   $items['chado_sync_analyses'] = array(
-     'title' => t('Sync Data'),
+     'title' => 'Sync Data',
      'page callback' => 'tripal_analysis_sync_analyses',
      'access arguments' => array('administer site configuration'),
      'type' => MENU_CALLBACK
@@ -112,8 +116,8 @@ function tripal_analysis_show_analyses() {
 }
 
 /**
- *  Provide information to drupal about the node types that we're creating
- *  in this module
+ * Provide information to drupal about the node types that we're creating
+ * in this module
  *
  * @ingroup tripal_analysis
  */
@@ -131,6 +135,7 @@ function tripal_analysis_node_info() {
   );
   return $nodes;
 }
+
 /**
  *  When a new chado_analysis node is created we also need to add information
  *  to our chado_analysis table.  This function is called on insert of a new
@@ -174,8 +179,8 @@ function chado_analysis_insert($node) {
           'timeexecuted' => $timestamp
       );
       if (tripal_core_chado_insert('analysis', $values)) {
-         $analysis = tripal_core_chado_select('analysis', array('*'), $values);
-         $analysis_id = $analysis[0]->analysis_id;
+        $analysis = tripal_core_chado_select('analysis', array('*'), $values);
+        $analysis_id = $analysis[0]->analysis_id;
       }
   }
 
@@ -215,10 +220,15 @@ function chado_analysis_insert($node) {
 
    // add the analysis to the node object for
    // use by other analysis modules that may be using this function
-   $node->analysis = $analysis;
-   $node->analysis_id = $analysis_id; // we need to set this for children
+    $node->analysis = $analysis;
+    $node->analysis_id = $analysis_id; // we need to set this for children
 }
+
 /**
+ * Removes analysis from the chado database
+ *
+ * @param $node
+ *   The node object specifying which chado record to delete
  *
  * @ingroup tripal_analysis
  */
@@ -254,6 +264,9 @@ function chado_analysis_delete($node) {
 /**
  * Update analyses
  *
+ * @param $node
+ *   The updated node object
+ *
  * @ingroup tripal_analysis
  */
 function chado_analysis_update($node) {
@@ -272,8 +285,8 @@ function chado_analysis_update($node) {
     // get the analysis_id for this node:
     $sql = "SELECT analysis_id ".
              "FROM {chado_analysis} ".
-             "WHERE vid = %d";
-    $analysis_id = db_fetch_object(db_query($sql, $node->vid))->analysis_id;
+             "WHERE nid = %d";
+    $analysis_id = db_fetch_object(db_query($sql, $node->nid))->analysis_id;
 
     $sql = "UPDATE {analysis} ".
              "SET name = '%s', ".
@@ -327,53 +340,53 @@ function chado_analysis_update($node) {
  */
 function chado_analysis_form($node) {
 
-   $analysis = $node->analysis;
-
-   // add in the description column. It is a text field and may not be included
-   // if the text is too big.
-   $analysis = tripal_core_expand_chado_vars($analysis, 'field', 'analysis.description');
-
-   // get form defaults
-   $analysis_id = $node->analysis_id;
-   if (!$analysis_id) {
-      $analysis_id = $analysis->analysis_id;
-   }
-   $analysisname = $node->analysisname;
-   if (!$analysisname) {
-      $analysisname = $analysis->name;
-   }
-   $program = $node->program;
-   if (!$program) {
-      $program = $analysis->program;
-   }
-   $programversion = $node->programversion;
-   if (!$programversion) {
-      $programversion = $analysis->programversion;
-   }
-   $algorithm = $node->algorithm;
-   if (!$algorithm) {
-      $algorithm = $analysis->algorithm;
-   }
-   $sourcename = $node->sourcename;
-   if (!$sourcename) {
-      $sourcename = $analysis->sourcename;
-   }
-   $sourceversion = $node->sourceversion;
-   if (!$sourceversion) {
-      $sourceversion = $analysis->sourceversion;
-   }
-   $sourceuri = $node->sourceuri;
-   if (!$sourceuri) {
-      $sourceuri = $analysis->sourceuri;
-   }
-   $timeexecuted = $node->timeexecuted;
-   if (!$timeexecuted) {
-      $timeexecuted = $analysis->timeexecuted;
-   }
-   $description = $node->description;
-   if (!$description) {
-      $description = $analysis->description;
-   }
+  $analysis = $node->analysis;
+
+  // add in the description column. It is a text field and may not be included
+  // if the text is too big.
+  $analysis = tripal_core_expand_chado_vars($analysis, 'field', 'analysis.description');
+
+  // get form defaults
+  $analysis_id = $node->analysis_id;
+  if (!$analysis_id) {
+    $analysis_id = $analysis->analysis_id;
+  }
+    $analysisname = $node->analysisname;
+  if (!$analysisname) {
+    $analysisname = $analysis->name;
+  }
+    $program = $node->program;
+  if (!$program) {
+    $program = $analysis->program;
+  }
+    $programversion = $node->programversion;
+  if (!$programversion) {
+    $programversion = $analysis->programversion;
+  }
+    $algorithm = $node->algorithm;
+  if (!$algorithm) {
+    $algorithm = $analysis->algorithm;
+  }
+    $sourcename = $node->sourcename;
+  if (!$sourcename) {
+    $sourcename = $analysis->sourcename;
+  }
+    $sourceversion = $node->sourceversion;
+  if (!$sourceversion) {
+    $sourceversion = $analysis->sourceversion;
+  }
+    $sourceuri = $node->sourceuri;
+  if (!$sourceuri) {
+    $sourceuri = $analysis->sourceuri;
+  }
+    $timeexecuted = $node->timeexecuted;
+  if (!$timeexecuted) {
+    $timeexecuted = $analysis->timeexecuted;
+  }
+    $description = $node->description;
+  if (!$description) {
+    $description = $analysis->description;
+  }
   $form = array();
   $form['title']= array(
       '#type' => 'hidden',
@@ -482,23 +495,23 @@ function chado_analysis_form($node) {
   return $form;
 }
 
-/**
- *  When a node is requested by the user this function is called to allow us
- *  to add auxiliary data to the node object.
- *
- * @ingroup tripal_analysis
- */
+ /**
+  *  When a node is requested by the user this function is called to allow us
+  *  to add auxiliary data to the node object.
+  *
+  * @ingroup tripal_analysis
+  */
 function chado_analysis_load($node) {
 
    // get the feature details from chado
-   $analysis_id = chado_get_id_for_node('analysis', $node);
+  $analysis_id = chado_get_id_for_node('analysis', $node);
 
-   $values = array('analysis_id' => $analysis_id);
-   $analysis = tripal_core_generate_chado_var('analysis', $values);
+  $values = array('analysis_id' => $analysis_id);
+  $analysis = tripal_core_generate_chado_var('analysis', $values);
 
-   $additions = new stdClass();
-   $additions->analysis = $analysis;
-   return $additions;
+  $additions = new stdClass();
+  $additions->analysis = $analysis;
+  return $additions;
 }
 
 /**
@@ -601,10 +614,10 @@ function tripal_analysis_sync_analyses($analysis_id = NULL, $job_id = NULL) {
          // This is a kegg analysis
         }
         elseif ($analysis_type->value == 'tripal_analysis_kegg' ) {
-           $new_node->type = 'chado_analysis_kegg';
+          $new_node->type = 'chado_analysis_kegg';
         }
         else {
-           $new_node->type = 'chado_analysis';
+          $new_node->type = 'chado_analysis';
         }
       // If it doesn't exist, this analysis is generic
       }
@@ -649,36 +662,36 @@ function tripal_analysis_sync_analyses($analysis_id = NULL, $job_id = NULL) {
         node_save($node);
 
         if ($node->nid) {
-          $page_content .= "Added $new_node->title<br>";
+          $page_content .= "Added $new_node->title<br />";
         }
       }
     }
     else {
-      $page_content .= "Skipped $new_node->title<br>";
+      $page_content .= "Skipped $new_node->title<br />";
     }
   }
   return $page_content;
 }
 
 /**
+ * Validates the user input before creating an analysis node
  *
  * @ingroup tripal_analysis
  */
 function chado_analysis_validate($node, &$form) {
    // use the analysis parent to validate the node
-   tripal_analysis_validate($node, $form);
+  tripal_analysis_validate($node, $form);
 }
+
 /**
+ * This validation is being used for three activities:
+ *   CASE A: Update a node that exists in both drupal and chado
+ *   CASE B: Synchronizing a node from chado to drupal
+ *   CASE C: Inserting a new node that exists in niether drupal nor chado
  *
- *@ingroup tripal_analysis
+ * @ingroup tripal_analysis
  */
 function tripal_analysis_validate($node, &$form) {
-##dprint_r($node);
-
-    // This validation is being used for three activities:
-    // CASE A: Update a node that exists in both drupal and chado
-    // CASE B: Synchronizing a node from chado to drupal
-    // CASE C: Inserting a new node that exists in niether drupal nor chado
 
     // Only nodes being updated will have an nid already
     if ($node->nid) {
@@ -715,13 +728,14 @@ function tripal_analysis_validate($node, &$form) {
             );
             $analysis = tripal_core_chado_select('analysis', array('analysis_id'), $values);
             if (sizeof($analysis) > 0) {
-               form_set_error('program', 'Cannot add the analysis with this program,
+              form_set_error('program', 'Cannot add the analysis with this program,
                   program version and source name. An analysis with these values already exists.');
-               return;
+              return;
             }
         }
     }
 }
+
 /**
  * Display help and module information
  * @param path which path of the site we're displaying help
@@ -742,6 +756,7 @@ function tripal_analysis_help($path, $arg) {
   }
   return $output;
 }
+
 /**
  *  The following function proves access control for users trying to
  *  perform actions on data managed by this module
@@ -767,16 +782,16 @@ function chado_analysis_access($op, $node, $account) {
   }
   if ($op == 'view') {
     if (!user_access('access chado_analysis content', $account)) {
-         return FALSE;
+      return FALSE;
       }
   }
-   return NULL;
+    return NULL;
 }
 
 /**
  *  Set the permission types that the chado module uses.  Essentially we
  *  want permissionis that protect creation, editing and deleting of chado
- #  data objects
+ *  data objects
  *
  * @ingroup tripal_analysis
  */
@@ -846,20 +861,24 @@ function get_chado_analyses() {
     return $analyses;
   }
 }
+
 /**
+ * Theme the List Analysis page
  *
+ * @param $analyses
+ *   An array of analyses to list
  *
  * @ingroup tripal_analysis
  */
 function theme_tripal_analysis_analysis_page($analyses) {
 
-  $output = "<br>Analyses are listed in the descending order of their execution time.<br><a id=\"tripal_expandableBox_toggle_button\" onClick=\"toggleExpandableBoxes()\">[-] Collapse All</a>";
+  $output = "<br />Analyses are listed in the descending order of their execution time.<br /><a id=\"tripal_expandableBox_toggle_button\" onClick=\"toggleExpandableBoxes()\">[-] Collapse All</a>";
 
-   foreach ($analyses as $analysis) {
+  foreach ($analyses as $analysis) {
     // Prepare information for html output
     $ana_node_url = url("node/$analysis->node_id");
-     if ($analysis->sourceversion) {
-         $ver = "($analysis->sourceversion)";
+    if ($analysis->sourceversion) {
+      $ver = "($analysis->sourceversion)";
       }
       $date =  preg_replace("/^(\d+-\d+-\d+) .*/", "$1", $analysis->timeexecuted);
 
@@ -902,7 +921,12 @@ function theme_tripal_analysis_analysis_page($analyses) {
 }
 
 /**
+ * Remove orphaned drupal nodes or chado analysis
  *
+ * @param $dummy
+ *   Not Used -kept for backwards compatibility
+ * @param $job_id
+ *   The id of the tripal job executing this function
  *
  * @ingroup tripal_analysis
  */
@@ -1057,7 +1081,8 @@ function tripal_analysis_taxonify_features ($analysis_id = NULL, $job_id = NULL)
     $i++;
   }
 }
-*/
+ */
+
 /**
  * Implements hook_views_api()
  * Purpose: Essentially this hook tells drupal that there is views support for
@@ -1067,7 +1092,7 @@ function tripal_analysis_taxonify_features ($analysis_id = NULL, $job_id = NULL)
  * @ingroup tripal_analysis
  */
 function tripal_analysis_views_api() {
-   return array(
-      'api' => 2.0,
-   );
+    return array(
+    'api' => 2.0,
+  );
 }

+ 7 - 7
tripal_analysis/tripal_analysis.views.inc

@@ -33,12 +33,12 @@ function tripal_analysis_views_data()  {
   $data = array();
 
   if (module_exists('tripal_views')) {
-		// Base Table: Analysis
-		$tablename = 'analysis';
-		if (!tripal_views_is_integrated($tablename, 10)) {
-			$table_integration_array = tripal_views_get_integration_array_for_chado_table($tablename, TRUE);
-			tripal_views_integration_add_entry($table_integration_array);
-		}
+    // Base Table: Analysis
+    $tablename = 'analysis';
+    if (!tripal_views_is_integrated($tablename, 10)) {
+      $table_integration_array = tripal_views_get_integration_array_for_chado_table($tablename, TRUE);
+      tripal_views_integration_add_entry($table_integration_array);
+    }
 
 
     $tables = array(
@@ -112,7 +112,7 @@ function tripal_analysis_views_data_alter(&$data) {
 }
 
 /**
- *
+ * Implements hook_views_default_views().
  *
  * @ingroup tripal_analysis_views
  */

+ 0 - 567
tripal_analysis/tripal_analysis.views.inc.orig

@@ -1,567 +0,0 @@
-<?php
-
-/**
- *  @file
- *  This file contains the basic functions for views integration of
- *  chado/tripal analysis tables. Supplementary functions can be found in
- *  ./views/
- *
- *  Documentation on views integration can be found at
- *  http://views2.logrus.com/doc/html/index.html.
- */
-
-/**
- * @defgroup tripal_analysis_views Analysis Views Integration
- * @ingroup views
- * @ingroup tripal_analysis
- */
-
-<<<<<<< HEAD
-=======
-require('views/analysis.views.inc');
-require('views/chado_analysis.views.inc');
-require('views/misc_tables.views.inc');
->>>>>>> 6.x-0.4-dev
-/**
- * Implements hook_views_data()
- *
- * Purpose: Describe chado/tripal tables & fields to views
- *
- * @return: a data array which follows the structure outlined in the
- *   views2 documentation for this hook. Essentially, it's an array of table
- *   definitions keyed by chado/tripal table name. Each table definition
- *   includes basic details about the table, fields in that table and
- *   relationships between that table and others (joins)
- *
- * @ingroup tripal_analysis_views
- */
-function tripal_analysis_views_data()  {
-  $data = array();
-
-  if (module_exists('tripal_views')) {
-		// Base Table: Analysis
-		$tablename = 'analysis';
-		if (!tripal_views_is_integrated($tablename, 10)) {
-			$table_integration_array = tripal_views_get_integration_array_for_chado_table($tablename, TRUE);
-			tripal_views_integration_add_entry($table_integration_array);
-		}
-
-
-    $tables = array(
-      'analysisfeature',
-      'analysisprop'
-    );
-    foreach ($tables as $tablename) {
-      if (!tripal_views_is_integrated($tablename, 10)) {
-        $table_integration_array = tripal_views_get_integration_array_for_chado_table($tablename, FALSE);
-        tripal_views_integration_add_entry($table_integration_array);
-      }
-    }
-
-  }
-
-  return $data;
-}
-
-/**
- * Implements hook_views_handlers()
- *
- * Purpose: Register all custom handlers with views
- *   where a handler describes either "the type of field",
- *   "how a field should be filtered", "how a field should be sorted"
- *
- * @return
- *   An array of handler definitions
- *
- * @ingroup tripal_analysis_views
- */
-function tripal_analysis_views_views_handlers() {
-  return array(
-    'info' => array(
-      'path' => drupal_get_path('module', 'tripal_analysis') . '/views/handlers',
-    ),
-    'handlers' => array(
-      'views_handler_field_computed_analysis_nid' => array(
-        'parent' => 'views_handler_field_numeric',
-      ),
-      'views_handler_field_readable_date' => array(
-        'parent' => 'views_handler_field',
-      ),
-    ),
-  );
-}
-
-/**
- * Implementation of hook_views_data_alter().
- */
-function tripal_analysis_views_data_alter(&$data) {
-
-  if (!(is_array($db_url) and array_key_exists('chado', $db_url)) ) {
-
-    // Add featuer relationship to node
-    $data['node']['analysis_chado_nid'] = array(
-      'group' => 'Analysis',
-      'title' => 'Analysis Node',
-      'help' => 'Links Chado analysis Fields/Data to the Nodes in the current View.',
-      'real field' => 'nid',
-      'relationship' => array(
-        'handler' => 'views_handler_relationship',
-        'title' => t('Node => Chado'),
-        'label' => t('Node => Chado'),
-        'real field' => 'nid',
-        'base' => 'chado_analysis',
-        'base field' => 'nid'
-      ),
-    );
-  }
-
-}
-
-/**
- *
- *
- * @ingroup tripal_analysis_views
- */
-function tripal_analysis_views_default_views() {
-  $views = array();
-
-  // Main default view
-  // List all cvterms based on cv
-  $view = new view;
-  $view->name = 'all_analysis';
-  $view->description = 'A listing of all analysis\'';
-  $view->tag = 'chado';
-  $view->view_php = '';
-  $view->base_table = 'analysis';
-  $view->is_cacheable = FALSE;
-  $view->api_version = 2;
-  $view->disabled = FALSE; /* Edit this to true to make a default view disabled initially */
-  $handler = $view->new_display('default', 'Defaults', 'default');
-  $handler->override_option('fields', array(
-    'name' => array(
-      'label' => 'Name',
-      'alter' => array(
-        'alter_text' => 0,
-        'text' => '',
-        'make_link' => 0,
-        'path' => '',
-        'link_class' => '',
-        'alt' => '',
-        'prefix' => '',
-        'suffix' => '',
-        'target' => '',
-        'help' => '',
-        'trim' => 0,
-        'max_length' => '',
-        'word_boundary' => 1,
-        'ellipsis' => 1,
-        'html' => 0,
-        'strip_tags' => 0,
-      ),
-      'empty' => '',
-      'hide_empty' => 0,
-      'empty_zero' => 0,
-      'link_to_node' => 1,
-      'exclude' => 0,
-      'id' => 'name',
-      'table' => 'analysis',
-      'field' => 'name',
-      'relationship' => 'none',
-    ),
-    'algorithm' => array(
-      'label' => 'Algorithm',
-      'alter' => array(
-        'alter_text' => 0,
-        'text' => '',
-        'make_link' => 0,
-        'path' => '',
-        'link_class' => '',
-        'alt' => '',
-        'prefix' => '',
-        'suffix' => '',
-        'target' => '',
-        'help' => '',
-        'trim' => 0,
-        'max_length' => '',
-        'word_boundary' => 1,
-        'ellipsis' => 1,
-        'html' => 0,
-        'strip_tags' => 0,
-      ),
-      'empty' => '',
-      'hide_empty' => 0,
-      'empty_zero' => 0,
-      'exclude' => 0,
-      'id' => 'algorithm',
-      'table' => 'analysis',
-      'field' => 'algorithm',
-      'relationship' => 'none',
-    ),
-    'program' => array(
-      'label' => 'Program',
-      'alter' => array(
-        'alter_text' => 0,
-        'text' => '',
-        'make_link' => 0,
-        'path' => '',
-        'link_class' => '',
-        'alt' => '',
-        'prefix' => '',
-        'suffix' => '',
-        'target' => '',
-        'help' => '',
-        'trim' => 0,
-        'max_length' => '',
-        'word_boundary' => 1,
-        'ellipsis' => 1,
-        'html' => 0,
-        'strip_tags' => 0,
-      ),
-      'empty' => '',
-      'hide_empty' => 0,
-      'empty_zero' => 0,
-      'exclude' => 0,
-      'id' => 'program',
-      'table' => 'analysis',
-      'field' => 'program',
-      'relationship' => 'none',
-    ),
-    'programversion' => array(
-      'label' => 'Program Version',
-      'alter' => array(
-        'alter_text' => 0,
-        'text' => '',
-        'make_link' => 0,
-        'path' => '',
-        'link_class' => '',
-        'alt' => '',
-        'prefix' => '',
-        'suffix' => '',
-        'target' => '',
-        'help' => '',
-        'trim' => 0,
-        'max_length' => '',
-        'word_boundary' => 1,
-        'ellipsis' => 1,
-        'html' => 0,
-        'strip_tags' => 0,
-      ),
-      'empty' => '',
-      'hide_empty' => 0,
-      'empty_zero' => 0,
-      'exclude' => 0,
-      'id' => 'programversion',
-      'table' => 'analysis',
-      'field' => 'programversion',
-      'relationship' => 'none',
-    ),
-    'description' => array(
-      'label' => 'Description',
-      'alter' => array(
-        'alter_text' => 0,
-        'text' => '',
-        'make_link' => 0,
-        'path' => '',
-        'link_class' => '',
-        'alt' => '',
-        'prefix' => '',
-        'suffix' => '',
-        'target' => '',
-        'help' => '',
-        'trim' => 0,
-        'max_length' => '',
-        'word_boundary' => 1,
-        'ellipsis' => 1,
-        'html' => 0,
-        'strip_tags' => 0,
-      ),
-      'empty' => '',
-      'hide_empty' => 0,
-      'empty_zero' => 0,
-      'exclude' => 0,
-      'id' => 'description',
-      'table' => 'analysis',
-      'field' => 'description',
-      'relationship' => 'none',
-    ),
-    'sourcename' => array(
-      'label' => 'Source Name',
-      'alter' => array(
-        'alter_text' => 0,
-        'text' => '',
-        'make_link' => 0,
-        'path' => '',
-        'link_class' => '',
-        'alt' => '',
-        'prefix' => '',
-        'suffix' => '',
-        'target' => '',
-        'help' => '',
-        'trim' => 0,
-        'max_length' => '',
-        'word_boundary' => 1,
-        'ellipsis' => 1,
-        'html' => 0,
-        'strip_tags' => 0,
-      ),
-      'empty' => '',
-      'hide_empty' => 0,
-      'empty_zero' => 0,
-      'exclude' => 0,
-      'id' => 'sourcename',
-      'table' => 'analysis',
-      'field' => 'sourcename',
-      'relationship' => 'none',
-    ),
-    'sourceuri' => array(
-      'label' => 'Source URL',
-      'alter' => array(
-        'alter_text' => 0,
-        'text' => '',
-        'make_link' => 0,
-        'path' => '',
-        'link_class' => '',
-        'alt' => '',
-        'prefix' => '',
-        'suffix' => '',
-        'target' => '',
-        'help' => '',
-        'trim' => 0,
-        'max_length' => '',
-        'word_boundary' => 1,
-        'ellipsis' => 1,
-        'html' => 0,
-        'strip_tags' => 0,
-      ),
-      'empty' => '',
-      'hide_empty' => 0,
-      'empty_zero' => 0,
-      'exclude' => 0,
-      'id' => 'sourceuri',
-      'table' => 'analysis',
-      'field' => 'sourceuri',
-      'relationship' => 'none',
-    ),
-    'sourceversion' => array(
-      'label' => 'Source Version',
-      'alter' => array(
-        'alter_text' => 0,
-        'text' => '',
-        'make_link' => 0,
-        'path' => '',
-        'link_class' => '',
-        'alt' => '',
-        'prefix' => '',
-        'suffix' => '',
-        'target' => '',
-        'help' => '',
-        'trim' => 0,
-        'max_length' => '',
-        'word_boundary' => 1,
-        'ellipsis' => 1,
-        'html' => 0,
-        'strip_tags' => 0,
-      ),
-      'empty' => '',
-      'hide_empty' => 0,
-      'empty_zero' => 0,
-      'exclude' => 0,
-      'id' => 'sourceversion',
-      'table' => 'analysis',
-      'field' => 'sourceversion',
-      'relationship' => 'none',
-    ),
-    'num_features' => array(
-      'label' => 'Number of Features',
-      'alter' => array(
-        'alter_text' => 0,
-        'text' => '',
-        'make_link' => 0,
-        'path' => '',
-        'link_class' => '',
-        'alt' => '',
-        'prefix' => '',
-        'suffix' => '',
-        'target' => '',
-        'help' => '',
-        'trim' => 0,
-        'max_length' => '',
-        'word_boundary' => 1,
-        'ellipsis' => 1,
-        'html' => 0,
-        'strip_tags' => 0,
-      ),
-      'empty' => '',
-      'hide_empty' => 0,
-      'empty_zero' => 0,
-      'exclude' => 0,
-      'id' => 'num_features',
-      'table' => 'analysis',
-      'field' => 'num_features',
-      'relationship' => 'none',
-    ),
-    'timeexecuted' => array(
-      'label' => 'Time Executed',
-      'alter' => array(
-        'alter_text' => 0,
-        'text' => '',
-        'make_link' => 0,
-        'path' => '',
-        'link_class' => '',
-        'alt' => '',
-        'prefix' => '',
-        'suffix' => '',
-        'target' => '',
-        'help' => '',
-        'trim' => 0,
-        'max_length' => '',
-        'word_boundary' => 1,
-        'ellipsis' => 1,
-        'html' => 0,
-        'strip_tags' => 0,
-      ),
-      'empty' => '',
-      'hide_empty' => 0,
-      'empty_zero' => 0,
-      'date_format' => 'large',
-      'custom_date_format' => '',
-      'exclude' => 0,
-      'id' => 'timeexecuted',
-      'table' => 'analysis',
-      'field' => 'timeexecuted',
-      'relationship' => 'none',
-    ),
-  ));
-  $handler->override_option('filters', array(
-    'program' => array(
-      'operator' => '=',
-      'value' => 'All',
-      'group' => '0',
-      'exposed' => TRUE,
-      'expose' => array(
-        'use_operator' => 0,
-        'operator' => 'program_op',
-        'identifier' => 'program',
-        'label' => 'Program',
-        'optional' => 1,
-        'remember' => 0,
-      ),
-      'case' => 0,
-      'id' => 'program',
-      'table' => 'analysis',
-      'field' => 'program',
-      'relationship' => 'none',
-    ),
-    'sourcename' => array(
-      'operator' => 'contains',
-      'value' => '',
-      'group' => '0',
-      'exposed' => TRUE,
-      'expose' => array(
-        'use_operator' => 0,
-        'operator' => 'sourcename_op',
-        'identifier' => 'sourcename',
-        'label' => 'Source Name Contains',
-        'optional' => 1,
-        'remember' => 0,
-      ),
-      'case' => 0,
-      'id' => 'sourcename',
-      'table' => 'analysis',
-      'field' => 'sourcename',
-      'relationship' => 'none',
-    ),
-  ));
-  $handler->override_option('access', array(
-    'type' => 'perm',
-    'perm' => 'access chado_analysis content',
-  ));
-  $handler->override_option('cache', array(
-    'type' => 'none',
-  ));
-  $handler->override_option('title', 'Analysis');
-  $handler->override_option('empty', 'No analysis match the supplied criteria.');
-  $handler->override_option('empty_format', '1');
-  $handler->override_option('items_per_page', 50);
-  $handler->override_option('use_pager', '1');
-  $handler->override_option('style_plugin', 'table');
-  $handler->override_option('style_options', array(
-    'grouping' => '',
-    'override' => 1,
-    'sticky' => 0,
-    'order' => 'asc',
-    'columns' => array(
-      'algorithm' => 'algorithm',
-      'description' => 'description',
-      'name' => 'name',
-      'num_features' => 'num_features',
-      'program' => 'program',
-      'programversion' => 'programversion',
-      'sourcename' => 'sourcename',
-      'sourceuri' => 'sourceuri',
-      'sourceversion' => 'sourceversion',
-      'timeexecuted' => 'timeexecuted',
-    ),
-    'info' => array(
-      'algorithm' => array(
-        'sortable' => 1,
-        'separator' => '',
-      ),
-      'description' => array(
-        'sortable' => 1,
-        'separator' => '',
-      ),
-      'name' => array(
-        'sortable' => 1,
-        'separator' => '',
-      ),
-      'num_features' => array(
-        'separator' => '',
-      ),
-      'program' => array(
-        'sortable' => 1,
-        'separator' => '',
-      ),
-      'programversion' => array(
-        'sortable' => 1,
-        'separator' => '',
-      ),
-      'sourcename' => array(
-        'sortable' => 1,
-        'separator' => '',
-      ),
-      'sourceuri' => array(
-        'sortable' => 1,
-        'separator' => '',
-      ),
-      'sourceversion' => array(
-        'sortable' => 1,
-        'separator' => '',
-      ),
-      'timeexecuted' => array(
-        'sortable' => 1,
-        'separator' => '',
-      ),
-    ),
-    'default' => 'timeexecuted',
-  ));
-  $handler = $view->new_display('page', 'Page', 'page_1');
-  $handler->override_option('path', 'analyses');
-  $handler->override_option('menu', array(
-    'type' => 'normal',
-    'title' => 'Analyses',
-    'description' => '',
-    'weight' => '0',
-    'name' => 'primary-links',
-  ));
-  $handler->override_option('tab_options', array(
-    'type' => 'none',
-    'title' => '',
-    'description' => '',
-    'weight' => 0,
-    'name' => 'navigation',
-  ));
-  $views[$view->name] = $view;
-
-  return $views;
-}

+ 13 - 4
tripal_analysis/tripal_analysis_privacy.inc

@@ -1,11 +1,14 @@
 <?php
 /**
  * @file
- * @todo Add file header description
+ * Perform permission check (required node_privacy_byrole module)
  */
 
-/*
- *  Perform permission check by analysis_id only if 'node_privacy_byrole' module is enabled
+/**
+ * Perform permission check by analysis_id only if 'node_privacy_byrole' module is enabled
+ *
+ * @param $analysis_id
+ *   Which analysis to check if the user has permission to view
  */
 function tripal_analysis_check_permission($analysis_id) {
   if (module_exists('node_privacy_byrole')) {
@@ -34,8 +37,14 @@ function tripal_analysis_check_permission($analysis_id) {
   }
 }
 
-/*
+/**
  * Set permissions for features associated with an analysis
+ * @todo Stephen: ensure the $nid param is defined correctly
+ *
+ * @param $analysis_id
+ *   Features associated with this analysis will have their permissions set
+ * @param $nid
+ *   The node ID of the analysis
  */
 function tripal_analysis_set_feature_permission($analysis_id, $nid) {
 

+ 165 - 2131
tripal_bulk_loader/tripal_bulk_loader.admin.inc

@@ -2,7 +2,7 @@
 
 /**
  * @file
- * Handles Create/Edit/Delete Template Admin Forms
+ * Bulk Loader Administration (Miscellaneous)
  */
 
 /**
@@ -11,24 +11,54 @@
 function tripal_bulk_loader_admin_template() {
   $output = '';
 
-  $output .= '<br><h3>Quick Links:</h3>';
-  $output .= l('Create a new bulk loader template', 'admin/tripal/tripal_bulk_loader_template/create') . "<br>";
-  $output .= l('Edit a bulk loader template', 'admin/tripal/tripal_bulk_loader_template/edit') . "<br>";
-  $output .= l('Delete a bulk loader template', 'admin/tripal/tripal_bulk_loader_template/delete') . "<br>";
-  $output .= l('Export a bulk loader template', 'admin/tripal/tripal_bulk_loader_template/export') . "<br>";
-  $output .= l('Import a bulk loader template', 'admin/tripal/tripal_bulk_loader_template/import') . "<br>";
-  $output .= '<br>';
+  $output .= '<br /><h3>Quick Links:</h3>';
+  $output .= '<ul>'
+    . '<li>'
+      . t('<a href="@link">Configure settings</a>',
+        array('@link' => url('admin/tripal/tripal_bulk_loader_template/configure')))
+      . '</li>'
+    . '<li>'
+      . t('List <a href="@link">Bulk Loader Jobs</a>',
+      array('@link' => url('admin/tripal/tripal_bulk_loader_template/jobs')))
+      . '</li>'
+    . '<li>'
+      . t('List <a href="@link">Manage Templates</a>',
+      array('@link' => url('admin/tripal/tripal_bulk_loader_template/manage_templates')))
+      . '</li>'
+      . '<ul>'
+      . '<li>'
+        . t('<a href="@create">Create</a> a new template',
+        array('@create' => url('admin/tripal/tripal_bulk_loader_template/manage_templates/create')))
+        . '</li>'
+      . '<li>'
+        . t('<a href="@edit">Edit</a> an existing template',
+        array('@edit' => url('admin/tripal/tripal_bulk_loader_template/manage_templates/edit')))
+        . '</li>'
+      . '<li>'
+        . t('<a href="@delete">Delete</a> an existing template',
+        array('@delete' => url('admin/tripal/tripal_bulk_loader_template/manage_templates/delete')))
+        . '</li>'
+      . '<li>'
+        . t('<a href="@import">Import</a> a new template',
+        array('@import' => url('admin/tripal/tripal_bulk_loader_template/manage_templates/import')))
+        . '</li>'
+      . '<li>'
+        . t('<a href="@export">Export</a> an existing template',
+        array('@export' => url('admin/tripal/tripal_bulk_loader_template/manage_templates/export')))
+        . '</li>'
+      . '</ul>'
+    . '</ul>';
 
   $output .= '<h3>Module Description:</h3>';
   $output .= '<p>This module provides the ability to create loading templates for any tab-delimited '
     . 'data file allowing it to be loaded into chado. The Loading Templates are a direct mapping '
     . 'between the columns in your file and the columns in chado tables. As such to use this tool '
     . 'you need to be very familar with the chado schema -See '
-    . l('Chado -Getting Started', 'http://gmod.org/wiki/Chado_-_Getting_Started')
+    . l(t('Chado -Getting Started'), 'http://gmod.org/wiki/Chado_-_Getting_Started')
     . '. The ability to add constants and specify foreign key contraints is also provided '
     . 'in order for the loader to fill chado columns which may be required but are not specified '
     . 'in your input file.</p>';
-  $output .= '<br>';
+  $output .= '<br />';
 
   $output .= '<h3>Setup Instructions</h3>';
   $output .= '<p>After intallation of the bulk loader module, the following tasks should be performed:</p>';
@@ -44,2172 +74,176 @@ function tripal_bulk_loader_admin_template() {
 }
 
 /**
- * A Configuration form for this module
+ * Provides a description page and quick links for template management
  */
-function tripal_bulk_loader_configuration_form($form_state = NULL) {
-  $form = array();
-
-  $form['speed'] = array(
-    '#type' => 'fieldset',
-    '#title' => t('Possible Speed Improvements'),
-  );
-
-  $form['speed']['prepare'] = array(
-    '#type' => 'checkbox',
-    '#title' => t('Use Prepared Statements'),
-    '#description' => t('SQL Prepared Statements allow for SQL queries which will be run '
-      .'many times to be parsed, rewritten and planned only once rather then every time '
-      .'the query is run. In the case of the bulk loader, this ensures that planning only '
-      .'occurs once for each "record" in your bulk loading template.'),
-    '#default_value' => variable_get('tripal_bulk_loader_prepare', TRUE),
-  );
+function tripal_bulk_loader_admin_manage_templates() {
+  $output = '';
 
-  $form['submit1'] = array(
-    '#type' => 'submit',
-    '#value' => t('Save')
-  );
+  $output .= '<br /><h3>Quick Links:</h3>';
+  $output .= '<ul>'
+    . '<li>'
+      . t('<a href="@create">Create</a> a new template',
+      array('@create' => url('admin/tripal/tripal_bulk_loader_template/manage_templates/create')))
+      . '</li>'
+    . '<li>'
+      . t('<a href="@edit">Edit</a> an existing template',
+      array('@edit' => url('admin/tripal/tripal_bulk_loader_template/manage_templates/edit')))
+      . '</li>'
+    . '<li>'
+      . t('<a href="@delete">Delete</a> an existing template',
+      array('@delete' => url('admin/tripal/tripal_bulk_loader_template/manage_templates/delete')))
+      . '</li>'
+    . '<li>'
+      . t('<a href="@import">Import</a> a new template',
+      array('@import' => url('admin/tripal/tripal_bulk_loader_template/manage_templates/import')))
+      . '</li>'
+    . '<li>'
+      . t('<a href="@export">Export</a> an existing template',
+      array('@export' => url('admin/tripal/tripal_bulk_loader_template/manage_templates/export')))
+      . '</li>'
+    . '</ul>';
+
+  $output .= '<p>' . t('Templates, as the term is used for this module, refer to plans
+  describing how the columns in the data file supplied to a bulk loading job map to tables
+  and fields in chado. Templates are created independently of bulk loading jobs so that
+  they can be re-used. Thus you only need one template to load any number of files of the
+  same format.') . '</p>';
 
-  return $form;
-}
 
-/**
- * A Configuration form for this module (Submit)
- */
-function tripal_bulk_loader_configuration_form_submit($form, $form_state) {
 
-  variable_set('tripal_bulk_loader_prepare', $form_state['values']['prepare']);
+  return $output;
 }
 
-//////////////////////////////////////////////////////////////////////////////////////
-// Modify Template
-//////////////////////////////////////////////////////////////////////////////////////
-
-
 /**
- * The main form reached at admin/tripal/tripal_bulk_loader/create and /edit
+ * Provides a listing of bulk loader jobs and links for administration
  */
-function tripal_bulk_loader_modify_template_base_form($form_state = NULL, $mode) {
-  $form = array();
-
-   // get template id from path and rebuild form
-   if ($_GET['template_id']) {
-    if (preg_match('/^\d+$/', $_GET['template_id'])) {
-      $form_state['storage']['template_id'] = $_GET['template_id'];
-    }
-
-    $sql = "SELECT * FROM {tripal_bulk_loader_template} WHERE template_id=%d";
-    $result = db_fetch_object(db_query($sql, $form_state['storage']['template_id']));
-    $form_state['storage']['template'] = unserialize($result->template_array);
-    $form_state['storage']['template_name'] = $result->name;
-
-    $form_state['storage']['record2priority'] = array();
-    foreach ($form_state['storage']['template'] as $priority => $record_array) {
-      if (!is_array($record_array)) {
-      continue; }
-      $form_state['storage']['record2priority'][$record_array['record_id']] = $priority;
-    }
-  }
-
-  $form['mode'] = array(
-    '#type' => 'hidden',
-    '#value' => $mode,
-  );
-
-  if ($form_state['storage']['template_id']) {
-    $form['template_name'] = array(
-        '#type' => 'item',
-        '#title' => 'Template',
-        '#value' => $form_state['storage']['template_name'],
-        '#weight' => 1,
-    );
-  }
-  else {
-    if (preg_match('/create/', $mode)) {
-     $form['new_template_name'] = array(
-        '#type' => 'textfield',
-        '#title' => 'Template Name',
-        '#weight' => 1,
-      );
-    }
-    elseif (preg_match('/edit/', $mode)) {
-      $sql = "SELECT * FROM {tripal_bulk_loader_template}";
-      $resource = db_query($sql);
-      $templates = array();
-      $templates[''] = 'Select a Template';
-      while ($r = db_fetch_object($resource)) {
-        $templates[$r->template_id] = $r->name;
-      }
-
-      $form['template_id'] = array(
-        '#title'         => t('Template'),
-        '#description'   => t('Please select the template you would like to edit.'),
-        '#type'          => 'select',
-        '#options'       => $templates,
-        '#default_value' => $form_state['storage']['template_id'],
-        '#weight'        => 0,
-        '#required'      => TRUE,
-        '#weight' => 1,
-      );
-    }
-  }
-
-  $form['records'] = array(
-    '#type' => ($form_state['storage']['template_id'])? 'fieldset' : 'hidden',
-    '#title' => t('Current Records'),
-    '#collapsible' => TRUE,
-    '#weight' => 2,
-  );
-
-  $form['records']['description'] = array(
-    '#type' => 'item',
-    '#value' => 'Records will be inserted into the chado database in the order listed below. To '
-      .'change this order: <ul><li>Drag the rows into the correct order OR</li><li>Enter '
-      .'the numbers 1 and up in the Order textboxes to indicate the correct order.</li></ul>',
-  );
-
-  $form['records']['records-data'] = array(
-    '#tree' => TRUE,
-  );
-
-  $form['records']['no_records'] = array(
-    '#type' => 'hidden',
-    '#value' => TRUE,
-  );
-
-  $form['records']['submit-new_record'] = array(
-    '#type' => 'submit',
-    '#value' => 'New Record/Field',
-  );
-
-  $form['records']['submit-reorder'] = array(
-    '#type' => 'submit',
-    '#value' => 'Save Order',
-  );
-
-  $form['fields'] = array(
-    '#type' => ($form_state['storage']['template_id'])? 'fieldset' : 'hidden',
-    '#title' => t('Current Fields'),
-    '#collapsible' => TRUE,
-    '#weight' => 3,
-  );
-
-  $form['fields']['fields-data'] = array(
-    '#tree' => TRUE,
-  );
-
-  if ($form_state['storage']['template']) {
-
-    // List Current Fields -------------------------------------------------------------
-    $i=1;
-    foreach ($form_state['storage']['template'] as $priority => $table_array) {
-      if (!is_array($table_array)) {
-      continue; }
-
-        $form['records']['no_records']['#value'] = FALSE;
-
-        $form['records']['records-data'][$priority] = array(
-          'title' => array(
-            '#type' => 'markup',
-            '#value' => $table_array['record_id'],
-          ),
-          'chado_table' => array(
-            '#type' => 'markup',
-            '#value' => $table_array['table'],
-          ),
-          'mode' => array(
-            '#type' => 'item',
-            '#value' => ($table_array['mode']) ? $table_array['mode'] : 'insert_unique',
-          ),
-          'new_priority' => array(
-            '#type' => 'select',
-            '#options' => range(1, sizeof($form_state['storage']['template'])),
-            '#default_value' => $priority,
-          ),
-          'old_priority' => array(
-            '#type' => 'hidden',
-            '#value' => $priority,
-          ),
-          'id'  => array(
-            '#type' => 'hidden',
-            '#value' => $priority,
-          ),
-          'submit-edit_record' => array(
-            '#type' => 'submit',
-            '#name' => (string)$priority,
-            '#value' => 'Edit Record',
-          ),
-          'submit-add_field' => array(
-            '#type' => 'submit',
-            '#name' => (string)$priority,
-            '#value' => 'Add Field',
-          ),
-          'submit-duplicate_record' => array(
-            '#type' => 'submit',
-            '#name' => (string)$priority,
-            '#value' => 'Duplicate Record'
-          ),
-        );
-
-        foreach ($table_array['fields'] as $field_index => $field) {
-
-          $form['fields']['fields-data'][$i] = array(
-            'record_id' => array(
-              '#type' => 'item',
-              '#value' => $table_array['record_id'],
-            ),
-            'priority_hidden' => array(
-              '#type' => 'hidden',
-              '#value' => $priority,
-            ),
-            'field_name' => array(
-              '#type' => 'item',
-              '#value' => $field['title'],
-            ),
-            'chado_table_name' => array(
-              '#type' => 'item',
-              '#value' => $table_array['table'],
-            ),
-            'chado_table_hidden' => array(
-              '#type' => 'hidden',
-              '#value' => $table_array['table'],
-            ),
-            'chado_field_name' => array(
-              '#type' => 'item',
-              '#value' => $field['field'],
-            ),
-            'sheet_name' => array(
-              '#type' => 'item',
-              '#value' => $field['spreadsheet sheet'],
-            ),
-            'column_num' => array(
-              '#type' => 'item',
-              '#value' => $field['spreadsheet column'],
-            ),
-            'constant_value' => array(
-              '#type' => 'item',
-              '#value' => $field['constant value'],
-            ),
-            'field_index' => array(
-              '#type' => 'hidden',
-              '#value' => $field_index
-            ),
-            'foreign_record_id' => array(
-              '#type' => 'item',
-              '#value' => $field['foreign key'],
-            ),
-            'edit_submit' => array(
-              '#type' => 'submit',
-              '#name' => (string)$i,
-              '#value' => "Edit Field",
-            ),
-            'delete_submit' => array(
-              '#type' => 'submit',
-              '#name' => (string)$i,
-              '#value' => "Delete Field",
-            ),
-          );
-
-          $i++;
-        }
-    }
-    $form['fields']['total_fields'] = array(
-      '#type' => 'item',
-      '#value' => $i,
-    );
-
-  }
-
-  if ($form['records']['no_records']['#value']) {
-    $form['records']['description'] = array(
-      '#type' => 'item',
-      '#value' => 'There are currently no records.',
-    );
-    unset($form['records']['submit-reorder']);
-
-    $form['fields']['description'] = array(
-      '#type' => 'item',
-      '#value' => 'There are currently no fields.',
+function tripal_bulk_loader_admin_jobs() {
+  $output = '';
+  $num_jobs_per_page = 50;
+
+  $output .= '<p>' . t('Jobs are not automatically submitted to the tripal jobs management
+  system when they are first created. Any jobs listed below with a status of "Initialized"
+  will not have a Job ID until you go to the bulk loader page and submit the job.') . '</p>';
+
+  $header = array(
+    array('data' => 'Job ID', 'field' => 'job_id', 'sort' => 'DESC'),
+    array('data' => 'Name', 'field' => 'loader_name'),
+    array('data' =>  'Template', 'field' => 'template_name'),
+    array('data' =>  'Status', 'field' => 'job_status'),
+    '');
+  $rows = array();
+  $resource = pager_query("SELECT n.*, t.name as template_name
+    FROM {tripal_bulk_loader} n
+    LEFT JOIN {tripal_bulk_loader_template} t ON cast(n.template_id as integer)=t.template_id"
+    . tablesort_sql($header),
+    $num_jobs_per_page);
+  while ($n = db_fetch_object($resource)) {
+    $rows[] = array(
+      l($n->job_id, 'admin/tripal/tripal_jobs/view/' . $n->job_id),
+      l($n->loader_name, 'node/' . $n->nid),
+      l($n->template_name, 'admin/tripal/tripal_bulk_loader_template/manage_templates/edit', array('query' => 'template_id=' . $n->template_id)),
+      $n->job_status,
+      l('View', 'node/' . $n->nid) . ' | ' .  l('Edit', 'node/' . $n->nid . '/edit')
     );
-
-  }
-
-  $mode_title = (preg_match('/create/', $mode)) ? 'Create Template' : 'Edit Template';
-  $value = ($form_state['storage']['template_id'])? 'Save Template' : $mode_title;
-  $form['submit'] = array(
-    '#type' => 'submit',
-    '#value' => $value,
-    '#weight' => 4,
-  );
-  return $form;
-}
-
-/**
- * Submit for tripal_bulk_loader_modify_template_base_form
- */
-function tripal_bulk_loader_modify_template_base_form_submit($form, &$form_state) {
-
-  $form_state['rebuild'] = TRUE;
-  if ($form_state['storage']['template_id']) {
-    $sql = "SELECT * FROM {tripal_bulk_loader_template} WHERE template_id=%d";
-    $result = db_fetch_object(db_query($sql, $form_state['storage']['template_id']));
-    $form_state['storage']['template'] = unserialize($result->template_array);
-  }
-
-  $op = $form_state['values'][ $form_state['clicked_button']['#name'] ];
-  switch ($op) {
-    // Initialize after template is chosen ----------------------------------------
-    case 'Edit Template':
-      $form_state['storage']['template_id'] = $form_state['values']['template_id'];
-
-      $sql = "SELECT * FROM {tripal_bulk_loader_template} WHERE template_id=%d";
-      $result = db_fetch_object(db_query($sql, $form_state['storage']['template_id']));
-      $form_state['storage']['template'] = unserialize($result->template_array);
-      $form_state['storage']['template_name'] = $result->name;
-
-      $form_state['storage']['record2priority'] = array();
-      foreach ($form_state['storage']['template'] as $priority => $record_array) {
-        if (!is_array($record_array)) {
-         continue;
-         }
-        $form_state['storage']['record2priority'][$record_array['record_id']] = $priority;
-      }
-    break;
-
-    case 'Create Template':
-      $record = array(
-        'name' => $form_state['values']['new_template_name'],
-        'template_array' => array(),
-      );
-      drupal_write_record('tripal_bulk_loader_template', $record);
-      $form_state['storage']['template_id'] = $record['template_id'];
-      $form_state['storage']['template_name'] = $record['name'];
-      $form_state['storage']['template'] = array();
-    break;
-
-    // Save Reordered Records -----------------------------------------------------
-    case 'Save Order':
-      $new_template = $form_state['storage']['template'];
-      // unset old elements
-       $form_state['storage']['record2priority'] = array();
-      foreach ($new_template as $priority => $record_array) {
-        if (preg_match('/\d+/', $priority)) {
-           unset($new_template[$priority]);
-         }
-      }
-      //set elements in new order
-      foreach ($form_state['values']['records-data'] as $item) {
-        $new_template[$item['new_priority']] = $form_state['storage']['template'][$item['old_priority']];
-        $record_name = $new_template[$item['new_priority']]['record_id'];
-        $form_state['storage']['record2priority'][$record_name] = $item['new_priority'];
-      }
-      ksort($new_template);
-      $form_state['storage']['template'] = $new_template;
-    break;
-
-    case 'New Record/Field':
-      $query = array(
-        'template_id' => $form_state['storage']['template_id'],
-        'record_id' => 'NEW',
-      );
-      drupal_goto('admin/tripal/tripal_bulk_loader_template/add_field', $query);
-    break;
-
-    case 'Edit Record':
-      $query = array(
-        'template_id' => $form_state['storage']['template_id'],
-        'record_id' => $form_state['clicked_button']['#name'],
-      );
-      drupal_goto('admin/tripal/tripal_bulk_loader_template/edit_record', $query);
-    break;
-
-    case 'Add Field':
-      $query = array(
-        'template_id' => $form_state['storage']['template_id'],
-        'record_id' => $form_state['clicked_button']['#name'],
-      );
-      drupal_goto('admin/tripal/tripal_bulk_loader_template/add_field', $query);
-    break;
-
-    case 'Duplicate Record':
-      // original record (one to be duplicated)
-      $orig_priority = $form_state['clicked_button']['#name'];
-      $record = $form_state['storage']['template'][ $orig_priority ];
-
-      // new record
-      $new_priority = sizeof($form_state['storage']['template']) + 1;
-      $record['record_id'] = $record['record_id'] . '_' . date('YzHi');
-      $form_state['storage']['template'][ $new_priority ] = $record;
-    break;
-
-    case 'Edit Field':
-      $field_data_index = $form_state['clicked_button']['#name'];
-      $query = array(
-        'template_id' => $form_state['storage']['template_id'],
-        'record_id' => $form_state['values']['fields-data'][$field_data_index]['priority_hidden'],
-        'field_index' => $form_state['values']['fields-data'][$field_data_index]['field_index'],
-      );
-      drupal_goto('admin/tripal/tripal_bulk_loader_template/edit_field', $query);
-    break;
-
-    case 'Delete Field':
-      $field_data = $form_state['values']['fields-data'][$form_state['clicked_button']['#name']];
-      $priority = $field_data['priority_hidden'];
-      $field_key = $field_data['field_index'];
-      unset($form_state['storage']['template'][$priority]['fields'][$field_key]);
-      if (!$form_state['storage']['template'][$priority]['fields']) {
-        unset($form_state['storage']['record2priority'][$form_state['storage']['template'][$priority]['record_id']]);
-        unset($form_state['storage']['template'][$priority]);
-      }
-      drupal_set_message('Deleted Field from Template.');
-    break;
-  } //end of switch
-
-  // Save Template
-  $record = array(
-    'template_id' => $form_state['storage']['template_id'],
-    'template_array' => serialize($form_state['storage']['template'])
-  );
-  drupal_write_record('tripal_bulk_loader_template', $record, array('template_id'));
-  drupal_set_message('Template Saved.');
-
-}
-
-//////////////////////////////////////////////////////////////////////////////////////
-// Delete Template
-//////////////////////////////////////////////////////////////////////////////////////
-
-/**
- * Delete Template Form
- * This form allows admin to delete already existing templates
- */
-function tripal_bulk_loader_delete_template_base_form() {
-  $form = array();
-
-  $sql = "SELECT * FROM {tripal_bulk_loader_template}";
-  $resource = db_query($sql);
-  $templates = array();
-  $templates[''] = 'Select a Template';
-  while ($r = db_fetch_object($resource)) {
-    $templates[$r->template_id] = $r->name;
   }
-  $form['template_name'] = array(
-      '#title'         => t('Template'),
-      '#description'   => t('Please select the template you would like to delete.'),
-      '#type'          => 'select',
-      '#options'       => $templates,
-      '#weight'        => 0,
-      '#required'      => TRUE,
-  );
+  $output .= theme_table($header, $rows);
 
-  $form['submit'] = array(
-    '#type' => 'submit',
-    '#value' => 'Delete Template',
-  );
+  $output .= theme('pager');
 
-  return $form;
+  return $output;
 }
 
 /**
- * Delete Template Form Submit
- *
- * @param $form
- *   The form that was submitted
- * @param $form_state
- *   The values and storage that were submitted
+ * @section
+ * Configuration Form
  */
-function tripal_bulk_loader_delete_template_base_form_submit($form, &$form_state) {
-  $sql = "DELETE FROM {tripal_bulk_loader_template} WHERE template_id=%d";
-  db_query($sql, $form_state['values']['template_name']);
-}
-
-//////////////////////////////////////////////////////////////////////////////////////
-// Import/Export Template
-//////////////////////////////////////////////////////////////////////////////////////
 
 /**
- * Import/Export Template Form
- *
- * On export, simply selects the serialized array from the db for a given template
- * and presents it to the user. On import, a serialized template array and a name is
- * supplied and a template record is created.
- *
- * @todo Make array presented to the user more readable. (ie: unserialize and print to the screen)
- *
- * @param $form_state
- *   The values and storage for the form
- * @param $mode
- *   Either 'import' or 'export' to indicate which function is being performed
- * @return
- *   A form array to be rendered by drupal_get_form
+ * A Configuration form for this module
  */
-function tripal_bulk_loader_import_export_template_form($form_state = NULL, $mode) {
+function tripal_bulk_loader_configuration_form($form_state = NULL) {
   $form = array();
 
-  $form['mode'] = array(
-    '#type' => 'hidden',
-    '#value' => $mode,
-  );
-
-  if (preg_match('/import/', $mode)) {
-   $form['new_template_name'] = array(
-      '#type' => 'textfield',
-      '#title' => 'Template Name',
-      '#weight' => 1,
-    );
-  }
-  elseif (preg_match('/export/', $mode)) {
-    $sql = "SELECT * FROM {tripal_bulk_loader_template}";
-    $resource = db_query($sql);
-    $templates = array();
-    $templates[''] = 'Select a Template';
-    while ($r = db_fetch_object($resource)) {
-      $templates[$r->template_id] = $r->name;
-    }
-
-    $form['template_id'] = array(
-      '#title'         => t('Template'),
-      '#description'   => t('Please select the template you would like to edit.'),
-      '#type'          => 'select',
-      '#options'       => $templates,
-      '#default_value' => $form_state['storage']['template_id'],
-      '#weight'        => 0,
-      '#required'      => TRUE,
-      '#weight' => 1,
-    );
-  }
-
-  $form['template_array'] = array(
-    '#type' => 'textarea',
-    '#title' => 'Template Array',
-    '#default_value' => $form_state['storage']['template_array'],
-    '#weight' => 2,
-  );
-
-  $form['submit'] = array(
-    '#type' => 'submit',
-    '#value' => 'Submit',
-    '#weight' => 10,
-  );
-
-  return $form;
-}
-
-/**
- * Import/Export Template Form Submit
- *
- * @param $form
- *   The form that was submitted
- * @param $form_state
- *   The values and storage that were submitted
- */
-function tripal_bulk_loader_import_export_template_form_submit($form, &$form_state) {
-  switch ($form_state['values']['mode']) {
-    case 'export':
-      $record = db_fetch_object(db_query("SELECT * FROM {tripal_bulk_loader_template} WHERE template_id=%d", $form_state['values']['template_id']));
-      $form_state['storage']['template_array'] = $record->template_array;
-      $form_state['storage']['template_id'] = $form_state['values']['template_id'];
-    break;
-    case 'import':
-      $record = array(
-        'name' => $form_state['values']['new_template_name'],
-        'template_array' => $form_state['values']['template_array'],
-      );
-      drupal_write_record('tripal_bulk_loader_template', $record);
-      if ($record->template_id) {
-        drupal_set_message('Successfully imported Tripal Bulk Loader Template.');
-      }
-    break;
-  }
-}
-
-//////////////////////////////////////////////////////////////////////////////////////
-// Edit Record Form
-//////////////////////////////////////////////////////////////////////////////////////
-
-/**
- * Edit Record Form
- *
- * This form is meant to be called from a bulk loader form. The following should be set
- * in the query section of the path:
- *  - template_id=\d+: the template which the edited record is part of
- *  - record_id=\d+: the priority or key in the template array of the record to be edited
- *
- * @param $form_state
- *   Contains the values and storage for the form
- * @return
- *   A form array to be rendered by drupal_get_form
- */
-function tripal_bulk_loader_edit_template_record_form(&$form_state = NULL) {
-   $form['#cache'] = TRUE; // Make sure the form is cached.
-
-   // get template id from path
-   $template_id = ($_GET['template_id'] !== NULL) ? $_GET['template_id'] : $form_state['values']['template_id'];
-
-   // if there is no template supplied don't return rest of form
-   if (!$template_id) {
-     return $form;
-   }
-
-  // Pre-process values/defaults ---------------------------
-
-   // If this is the first load of the form (no form state) we need to initialize some variables
-   if (!$form_state['storage']['template']) {
-    $sql = "SELECT * FROM {tripal_bulk_loader_template} WHERE template_id=%d";
-    $template = db_fetch_object(db_query($sql, $template_id));
-    $form_state['storage']['template_array'] = unserialize($template->template_array);
-    $form_state['storage']['template'] = $template;
-
-    $form_state['storage']['record2priority'] = array();
-    foreach ($form_state['storage']['template_array'] as $priority => $record_array) {
-      if (!is_array($record_array)) {
-         continue;
-       }
-      $form_state['storage']['record2priority'][$record_array['record_id']] = $priority;
-    }
-
-    $form_state['storage']['referring URL'] = $_SERVER["HTTP_REFERER"];
-  }
-  else {
-    $template = $form_state['storage']['template'];
-  }
-
-   // get the record_id from the path
-   if ($_GET['record_id'] !== NULL) {
-     $form_state['values']['field_group'] = $_GET['record_id'];
-     $form_state['storage']['original_priority'] = $_GET['record_id'];
-  }
-
-
-  // Tables and default table
-  $tables = tripal_core_get_chado_tables();
-  if ($form_state['values']['chado_table']) {
-    $table = $form_state['values']['chado_table'];
-  }
-  else {
-    $table = $form_state['storage']['template_array'][$form_state['storage']['original_priority']]['table'];
-  }
-
-  //dpm($form_state, 'form state');
-
-   // Form Proper -------------------------------------------
-  $form['template_name'] = array(
-    '#type' => 'item',
-    '#title' => 'Template',
-    '#value' => $template->name,
-  );
-
-  $form['template_id'] = array(
-    '#type' => 'hidden',
-    '#value' => $template_id,
-  );
-
-  $form['edit_record'] = array(
+  $form['speed'] = array(
     '#type' => 'fieldset',
+    '#title' => t('Possible Speed Improvements'),
   );
 
-  // check template array for records then add one more
-  if (!$form_state['storage']['record2priority']) {
-    $groups = array();
-  }
-  else {
-    $groups = array_flip($form_state['storage']['record2priority']);
-  }
-  $priority_default = $form_state['values']['field_group'];
-  $form['edit_record']['field_group']  = array(
-    '#type' => 'select',
-    '#title' => 'Record',
-    '#description' => 'By Changing the record here, you can move all the fields from the current record into the selected record.',
-    '#options' => $groups,
-    '#default_value' => $priority_default,
-    '#required' => TRUE,
+  $form['speed']['prepare'] = array(
+    '#type' => 'checkbox',
+    '#title' => t('Use Prepared Statements'),
+    '#description' => t('SQL Prepared Statements allow for SQL queries which will be run '
+      .'many times to be parsed, rewritten and planned only once rather then every time '
+      .'the query is run. In the case of the bulk loader, this ensures that planning only '
+      .'occurs once for each "record" in your bulk loading template.'),
+    '#default_value' => variable_get('tripal_bulk_loader_prepare', TRUE),
   );
 
-  $form['edit_record']['record_name'] = array(
-    '#type' => 'textfield',
-    '#title' => 'Unique Record Name',
-    '#default_value' => $groups[$priority_default],
+  $form['speed']['disable_triggers'] = array(
+    '#type' => 'checkbox',
+    '#title' => t('Delay Constraint Checking during loading job.'),
+    '#description' => t('This delays the constraint checking until the end of the
+    loading proccess.'),
+    '#default_value' => variable_get('tripal_bulk_loader_disable_triggers', TRUE),
   );
 
-  $form['edit_record']['chado_table'] = array(
-    '#type' => 'select',
-    '#title' => t('Chado Table'),
-    '#description' => 'This changes the chado table for all fields in this record.',
-    '#options' => $tables,
-    '#default_value' => $table,
+  $form['speed']['no_validate'] = array(
+    '#type' => 'checkbox',
+    '#title' => t('Skip Validation at the Tripal Core API level'),
+    '#description' => t('If an error is encountered, the Tripal core API will try
+      to provide informative error messages. With this turned off, you will not benifit
+      from these more informative error messages; however, your job will load faster
+      since it doesn\'t have to do the additional checking before inserting.'),
+    '#default_value' => variable_get('tripal_bulk_loader_skip_validation', FALSE),
   );
 
-  $form['edit_record']['mode'] = array(
+  $form['speed']['transactions'] = array(
     '#type' => 'radios',
-    '#title' => 'Action to take when Loading Record',
+    '#title' => t('Transaction Rollback when an error is encountered'),
     '#options' => array(
-      'select' => 'SELECT: Don\'t insert this record: it\'s used to define a foreign key in another record',
-      'insert' => 'INSERT: Insert the record',
-      'optional' => 'OPTIONAL: Record will only be inserted if all required data is filled in',
-      'insert_once' => 'INSERT ONCE: Record will be inserted once for the entire spreadsheet',
-      'insert_unique' => 'INSERT UNIQUE: Only insert record if there isn\'t a record with the same values',
+      'all' => t('Rollback the last constant set.'
+        .'<div class="description"If you added more then one constant set then the
+        successfully loaded constant sets will not be rolled back. However, once an error
+        is encountered no further constant sets will be loaded either.</div>'),
+      'row' => t('Only Rollback the last line of the input file.'
+        .'<div class="description">This option may allow you to restart the job after
+        fixing the error (manual intervention needed).</div>'),
+      'none' => t('Do not use transactions<div class="description">This is not recommended.</div>')
     ),
-    '#default_value' => 'insert_unique'
+    '#default_value' => variable_get('tripal_bulk_loader_transactions',   'row')
   );
 
-  $form['edit_record']['submit-edit_record'] = array(
-      '#type' => 'submit',
-      '#value' => 'Edit Record'
+  $form['speed']['lock'] = array(
+    '#type' => 'radios',
+    '#title' => t('Lock Type'),
+    '#description' => t('The type of lock used by the bulk loading jobs. The lock is '
+      .'acquired at the beginning of the job and kept till the end. A lock of the type '
+      .'selected will be acquired for every table being inserted into.'),
+    '#options' => array(
+      'ROW EXCLUSIVE' => t('ROW EXCLUSIVE: The default lock type for insert queries.'),
+      'EXCLUSIVE' => t('EXCLUSIVE: Only Select Queries can access the table.'),
+      'ACCESS EXCLUSIVE' => t('ACCESS EXCLUSIVE: No other queries can access the table.'),
+    ),
+    '#default_value' => variable_get('tripal_bulk_loader_lock', 'ROW EXCLUSIVE'),
   );
 
-  $form['edit_record']['submit-cancel'] = array(
-      '#type' => 'submit',
-      '#value' => 'Cancel'
+  $form['submit1'] = array(
+    '#type' => 'submit',
+    '#value' => t('Save')
   );
 
   return $form;
 }
 
-
-/**
- * Edit Record Form Submit
- *
- * @param $form
- *   The form that was submitted
- * @param $form_state
- *   Contains the values and storage for the form
- */
-function tripal_bulk_loader_edit_template_record_form_submit($form, &$form_state) {
-  //dpm($form_state, 'form state -start submit');
-
-  if (!$form_state['ahah_submission']) {
-    if ($form_state['values']['op'] ==  'Edit Record') {
-
-      $template = $form_state['storage']['template_array'];
-
-      // Edit Record
-      $record = $template[ $form_state['storage']['original_priority'] ];
-      $record['record_id'] = $form_state['values']['record_name'];
-      $record['mode'] = $form_state['values']['mode'];
-      $record['table'] = $form_state['values']['chado_table'];
-
-      if ($form_state['storage']['original_priority'] != $form_state['values']['field_group']) {
-        $record['fields'] = array_merge($record['fields'], $template[ $form_state['values']['field_group'] ]['fields']);
-        $template[ $form_state['values']['field_group'] ] = $record;
-        unset($template[ $form_state['storage']['original_priority'] ]);
-      }
-      else {
-        $template[ $form_state['storage']['original_priority'] ] = $record;
-      }
-
-      // Save Template
-      $form_state['storage']['template']->template_array = serialize($template);
-      $success = drupal_write_record('tripal_bulk_loader_template', $form_state['storage']['template'], array('template_id'));
-
-      if ($success) {
-        drupal_set_message('Successfully Updated Template Record');
-        drupal_set_message('Template Saved.');
-
-        $path = explode('?', $form_state['storage']['referring URL']);
-        parse_str($path[1], $query);
-        $query['template_id'] = $form_state['storage']['template']->template_id;
-        drupal_goto($path[0], $query);
-      }
-      else {
-        drupal_set_message('Unable to Save Template!', 'error');
-        watchdog('T_bulk_loader',
-          'Unable to save bulk loader template: %template',
-          array('%template' => print_r($form_state['storage']['template'], TRUE)),
-          WATCHDOG_ERROR
-        );
-      }
-    }
-    elseif ($form_state['values']['op'] ==  'Cancel') {
-        $path = explode('?', $form_state['storage']['referring URL']);
-        parse_str($path[1], $query);
-        $query['template_id'] = $form_state['storage']['template']->template_id;
-        //dpm('Redirecting to: '.$path[0].'?'.print_r($query,TRUE).' where the referring URL:'.$form_state['storage']['referring URL']);
-        drupal_goto($path[0], $query);
-    }
-  }
-
-}
-
-//////////////////////////////////////////////////////////////////////////////////////
-// Add/Edit Field Forms
-//////////////////////////////////////////////////////////////////////////////////////
-
 /**
- * Add Field Form
- *
- * This form is meant to be called from a bulk loader form. Blank Defaults are in place but you
- * can use the following in the query of the path to set defaults for a given template:
- *  - template_id=\d+: the template to add the field to
- *  - record_id=\d+: the priority or key in the template array of the record to add the field to
- *
- * @param $form_state
- *   Contains the values and storage for the form
- * @return
- *   A form array to be rendered by drupal_get_form
+ * A Configuration form for this module (Submit)
  */
-function tripal_bulk_loader_add_template_field_form(&$form_state = NULL) {
-  $form = array();
-   $form['#cache'] = TRUE; // Make sure the form is cached.
-
-   // get template id from path
-   $template_id = ($_GET['template_id']) ? $_GET['template_id'] : $form_state['values']['template_id'];
-
-   // if there is no template supplied don't return rest of form
-   if (!$template_id) {
-     return $form;
-   }
-
-  // Pre-set Variables needed for form proper------------------------------------------
-
-   // If this is the first load of the form (no form state) we need to initialize some variables
-   if (!$form_state['storage']['template']) {
-    $sql = "SELECT * FROM {tripal_bulk_loader_template} WHERE template_id=%d";
-    $template = db_fetch_object(db_query($sql, $template_id));
-    $form_state['storage']['template_array'] = unserialize($template->template_array);
-    $form_state['storage']['template'] = $template;
-
-    $form_state['storage']['record2priority'] = array();
-    foreach ($form_state['storage']['template_array'] as $priority => $record_array) {
-      if (!is_array($record_array)) {
-        continue;
-      }
-      $form_state['storage']['record2priority'][$record_array['record_id']] = $priority;
-    }
-
-    $form_state['storage']['referring URL'] = $_SERVER["HTTP_REFERER"];
-  }
-  else {
-    $template = $form_state['storage']['template'];
-  }
-
-  $field_type = ($form_state['values']['field_type'])? $form_state['values']['field_type'] : 'table field';
-
-  // Tables and default table
-  $tables = tripal_core_get_chado_tables();
-  if ($form_state['values']) {
-    if (!preg_match('/^' . current($tables) . '$/', $form_state['values']['chado_table'])) {
-      $table = $form_state['values']['chado_table'];
-    }
-    elseif ($form_state['values']['record_name']) {
-      $record_name = $form_state['values']['record_name'];
-      $priority = $form_state['storage']['record2priority'][$record_name];
-      $table = $form_state['storage']['template_array'][$priority]['table'];
-    }
-    else {
-      $priority = $form_state['values']['field_group'];
-      $table = $form_state['storage']['template_array'][$priority]['table'];
-    }
-  }
-  if (!$table) {
-    $table = reset($tables);
-  }
-
-   // get the record_id from the path
-   if ($_GET['record_id'] !== NULL) {
-     $form_state['values']['field_group'] = $_GET['record_id'];
-    if (preg_match('/\d+/', $_GET['record_id'])) {
-      $priority = $form_state['values']['field_group'];
-      $table = $form_state['storage']['template_array'][$priority]['table'];
-    }
-  }
-
-  // Fields and foreign key mappings
-  $chado_fields = array();
-  $fk_options = array();
-  $fk_options['NULL'] = 'None';
-  $table_description = module_invoke_all('chado_' . $table . '_schema');
-  //dpm($table_description, 'table description for |'.$table.'|');
-  if ($field_type == 'foreign key') {
-    $foreign_field2table = array();
-    foreach ($table_description['foreign keys'] as $key_table => $key_array) {
-      foreach ($key_array['columns'] as $left_field => $right_field) {
-        $chado_fields[$left_field] = $left_field;
-        $foreign_field2table[$left_field] = $key_table;
-      }
-    }
-    reset($chado_fields);
-
-    // set default field
-    if (empty($chado_fields)) {
-      $field = NULL;
-    }
-    elseif ($chado_fields[$form_state['values']['chado_field']]) {
-      $field = $form_state['values']['chado_field'];
-    }
-    else {
-      $field = current($chado_fields);
-    }
-
-    // Foreign key options
-    $foreign_table = $foreign_field2table[$field];
-    if ($foreign_table) {
-      foreach ($form_state['storage']['record2priority'] as $record_name => $priority ) {
-        if (preg_match('/^' . $foreign_table . '$/', $form_state['storage']['template_array'][$priority]['table'])) {
-          $fk_options[$record_name] = $record_name;
-        }
-      }
-    }
-  }
-  else {
-    foreach ($table_description['fields'] as $field_name => $field_array) {
-        $chado_fields[$field_name] = $field_name;
-    }
-  }
-
-  $variables = array(
-    'form_state' => $form_state,
-    'tables' => $tables,
-    'default table' => $table,
-    'fields' => $chado_fields,
-    'default_field' => $field,
-    'priority' => $priority,
-    'record_name' => $record_name,
-    'table description' => $table_description,
-    'foreign key options' => $fk_options,
-    'foreign field=>table' => $foreign_field2table,
-    'foreign table' => $foreign_table,
-  );
-  //dpm($variables, 'variables');
-
-  // Start of Form Proper--------------------------------------------------------------
-  //dpm($form_state, 'Form State');
-
-  $form['template_name'] = array(
-    '#type' => 'item',
-    '#title' => 'Template',
-    '#value' => $template->name,
-  );
-
-  $form['template_id'] = array(
-    '#type' => 'hidden',
-    '#value' => $template_id,
-  );
-
-  $form['add_fields'] = array(
-    '#type' => 'fieldset',
-    '#prefix' => '<div id="tripal_bulk_loader_template-add_field">',
-    '#suffix' => '</div>',
-  );
-
-  $form['add_fields']['field_type'] = array(
-    '#type' => 'radios',
-    '#title' => t('Type of Field'),
-    '#options' => array(
-      'table field' => t('Spreadsheet: Fields which maps to a Spreadsheet Column'),
-      'constant' => t('Constant: Field which remains Constant throughout the Spreadsheet'),
-      'foreign key' => t('Foreign Key: Fields which map to a record in another table'),
-    ),
-    '#required' => TRUE,
-    '#default_value' => $field_type,
-    '#ahah' => array(
-      'path' => 'admin/tripal/tripal_bulk_loader_template/add_field_ahah',
-      'wrapper' => 'tripal_bulk_loader_template-add_field',
-      'effect' => 'fade'
-    ),
-  );
-
-  // check template array for records then add one more
-  if (!$form_state['storage']['record2priority']) {
-    $groups = array();
-  }
-  else {
-    $groups = array_flip($form_state['storage']['record2priority']);
-  }
-  $groups['NONE'] = 'Select a Record';
-  $groups['NEW'] = 'New Record';
-  $form['add_fields']['field_group']  = array(
-    '#type' => 'select',
-    '#title' => 'Record',
-    '#description' => 'This is used to group a set of fields together allowing '
-      .'multiple records to be inserted into the same table per line of the spreadsheet',
-    '#options' => $groups,
-    '#default_value' => (preg_match('/\w+.*/', $form_state['values']['field_group'])) ? $form_state['values']['field_group'] : 'NONE',
-    '#ahah' => array(
-      'path' => 'admin/tripal/tripal_bulk_loader_template/add_field_ahah',
-      'wrapper' => 'tripal_bulk_loader_template-add_field',
-      'effect' => 'fade'
-    ),
-    '#required' => TRUE,
-  );
-
-  $form['add_fields']['record_name'] = array(
-    '#type' => (preg_match('/NEW/', $form_state['values']['field_group'])) ? 'textfield' : 'hidden',
-    '#title' => 'Unique Record Name',
-    '#prefix' => '<div id="tripal_bulk_loader_template-add_record">',
-    '#suffix' => '</div>',
-    '#default_value' => $form_state['values']['record_name'],
-  );
-
-  $form['add_fields']['field_title'] = array(
-    '#type' => 'textfield',
-    '#title' => t('Human-readable Title for Field'),
-    '#default_value' => $form_state['values']['field_title'],
-  );
-
-  // Spreadsheet column
-  $form['add_fields']['columns'] = array(
-    '#type' => 'fieldset',
-    '#title' => t('Spreadsheet Column'),
-    '#collapsible' => TRUE,
-    '#collapsed' => ($field_type == 'table field')? FALSE : TRUE,
-  );
-
-  $form['add_fields']['columns']['sheet_name'] = array(
-    '#type' => 'textfield',
-    '#title' => t('Worksheet'),
-    '#description' => t('Specify the name of the worksheet.'),
-    '#size' => 5,
-    '#default_value' => ($form_state['values']['sheet_name'])? $form_state['values']['sheet_name'] : 'Sheet1',
-  );
-
-  $form['add_fields']['columns']['column_number'] = array(
-    '#type' => 'textfield',
-    '#title' => t('Column'),
-    '#description' => t('Specify the column in the spreadsheet that this field maps to where the first column is 1.'),
-    '#size' => 5,
-    '#default_value' => $form_state['values']['column_number'],
-  );
-
-  $form['add_fields']['columns']['column_exposed'] = array(
-    '#type' => 'checkbox',
-    '#title' => t('Allow Column to be set for each Bulk Loading Job'),
-    '#description' => t('Adds a textbox field to the Bulk Loader Page to allow users to set this value.'),
-    '#default_value' => ($form_state['values']['column_exposed']) ? $form_state['values']['column_exposed'] : $template_field['exposed'],
-  );
+function tripal_bulk_loader_configuration_form_submit($form, $form_state) {
 
-  $form['add_fields']['columns']['column_exposed_desc'] = array(
-    '#type' => 'textfield',
-    '#title' => t('Description for exposed field on bulk loading job'),
-    '#description' => t('This description should tell the user what column should be entered here.'),
-    '#default_value' => ($form_state['values']['column_exposed_desc']) ? $form_state['values']['column_exposed_desc'] : $template_field['exposed_description'],
-  );
-
-  // Global Value
-  $form['add_fields']['constant'] = array(
-    '#type' => 'fieldset',
-    '#title' => t('Constant'),
-    '#collapsible' => TRUE,
-    '#collapsed' => ($field_type == 'constant')? FALSE : TRUE,
-  );
-
-  $form['add_fields']['constant']['constant_value'] = array(
-    '#type' => 'textfield',
-    '#title' => t('Constant Value'),
-    '#description' => t('Specify the value you wish this field to have regardless of spreadsheet data.'),
-    '#default_value' => $form_state['values']['constant_value']
-  );
-
-  $form['add_fields']['constant']['constant_exposed'] = array(
-    '#type' => 'checkbox',
-    '#title' => t('Allow Constant to be set for each Bulk Loading Job'),
-    '#description' => t('Adds a textbox field to the Create Bulk Loader Form to allow users to set this value.')
-  );
-
-  $form['add_fields']['constant']['constant_validate'] = array(
-    '#type' => 'checkbox',
-    '#title' => t('Ensure value is in table'),
-    '#description' => t('Checks the database when a bulk loading job is created to ensure the value entered already exists in the database.'),
-  );
-
-  // Foreign Key
-  $form['add_fields']['foreign_key'] = array(
-    '#type' => 'fieldset',
-    '#title' => 'Foreign Key',
-    '#collapsible' => TRUE,
-    '#collapsed' => ($field_type == 'foreign key')? FALSE : TRUE,
-  );
-
-  $form['add_fields']['foreign_key']['foreign_record'] = array(
-    '#type' => 'select',
-    '#title' => 'Record to refer to',
-    '#descripion' => 'Select the record that this foreign key shouold refer to. The record needs to already exist and be of the correct table.',
-    '#options' => $fk_options,
-  );
-
-  // Chado Field
-  $form['add_fields']['chado'] = array(
-    '#type' => 'fieldset',
-    '#title' => t('Chado Field/Column Details'),
-    '#description' => t('Specify the Table/Field in chado that this field maps to.'),
-  );
-
-  $form['add_fields']['chado']['chado_table'] = array(
-    '#type' => 'select',
-    '#title' => t('Chado Table'),
-    '#options' => $tables,
-    '#default_value' => $table,
-    '#ahah' => array(
-      'path' => 'admin/tripal/tripal_bulk_loader_template/add_field_ahah',
-      'wrapper' => 'tripal_bulk_loader_template-add_field',
-      'effect' => 'fade'
-      ),
-  );
-
-  $form['add_fields']['chado']['chado_field'] = array(
-    '#type' => 'select',
-    '#title' => t('Chado Field/Column'),
-    '#options' => $chado_fields,
-    '#default_value' => $form_state['values']['chado_field'],
-    '#ahah' => array(
-      'path' => 'admin/tripal/tripal_bulk_loader_template/add_field_ahah',
-      'wrapper' => 'tripal_bulk_loader_template-add_field',
-      'effect' => 'fade'
-    ),
-  );
-
-  $form['add_fields']['additional'] = array(
-    '#type' => 'fieldset',
-    '#title' => 'Additional Options',
-  );
-
-  $form['add_fields']['additional']['required'] = array(
-    '#type' => 'checkbox',
-    '#title' => 'Make this file required',
-  );
-
-  $form['add_fields']['additional']['regex_transform'] = array(
-    '#type' => 'fieldset',
-    '#title' => 'Transform Spreadsheet Value Rules',
-    '#collapsible' => TRUE,
-    '#collapsed' => (!$form_state['storage']['regex']['pattern']) ? TRUE : FALSE,
-  );
-
-  $form['add_fields']['additional']['regex_transform']['regex_description'] = array(
-    '#type' => 'item',
-    '#value' => 'A transformation rule allows you to transform the original value '
-      .'(usually from a user submitted spreadsheet) into the form you would like it stored '
-      .'in the chado database. Each rule consists of a match pattern (a php regular expression '
-      .'which determines which replacement patterns are applied and captures regions of the '
-      .'original value) and a replacement pattern (a string which may contain capture references '
-      .'that describes what the new value should be). Each rule is applied to the result of the '
-      .'previous rule.'
-  );
-
-  $form['add_fields']['additional']['regex_transform']['regex-data'] = array(
-    '#tree' => TRUE,
-  );
-  if (!$form_state['storage']['regex']['pattern']) {
-    $form_state['storage']['regex']['pattern'] = array();
-  }
-  foreach ($form_state['storage']['regex']['pattern'] as $index => $pattern) {
-    $data_element = array(
-      'pattern' => array(
-        '#type' => 'item',
-        '#value' => $pattern,
-      ),
-      'replace' => array(
-        '#type' => 'item',
-        '#value' => $form_state['storage']['regex']['replace'][$index],
-      ),
-      'old_index' => array(
-        '#type' => 'hidden',
-        '#value' => $index,
-      ),
-      'new_index' => array(
-        '#type' => 'select',
-        '#options' => range(0, sizeof($form_state['storage']['regex']['pattern'])-1),
-        '#default_value' => $index,
-      ),
-      'id' => array(
-        '#type' => 'hidden',
-        '#value' => $index,
-      ),
-      'submit-delete' => array(
-        '#type' => 'submit',
-        '#value' => 'Delete Transformation',
-        '#name' => $index,
-      ),
-    );
-    $form['add_fields']['additional']['regex_transform']['regex-data'][$index] = $data_element;
-  }
-
-  $form['add_fields']['additional']['regex_transform']['submit-reorder_regex'] = array(
-    '#type' => ($form_state['storage']['regex']['pattern']) ? 'submit' : 'hidden',
-    '#value' => 'Save Transformation Rule Order'
-  );
-
-  $form['add_fields']['additional']['regex_transform']['new_regex'] = array(
-    '#type' => 'fieldset',
-    '#title' => 'Add a new Transformation Rule',
-  );
-
-  $form['add_fields']['additional']['regex_transform']['new_regex']['pattern'] = array(
-    '#type' => 'textfield',
-    '#title' => 'Match Pattern',
-    '#description' => 'You can use standard php regular expressions in this field to specify a '
-      .'pattern. Only if this pattern matches the value in the spreadsheet does the replacement '
-      .'pattern get applied to the value. To capture a section of your value for use in the '
-      .'replacement patten surround with round brackets. For example, <i>GI:(\d+)</i> will match '
-      .' NCBI gi numbers and will capture the numerical digits for use in the replacement pattern. '
-      .' To match and capture any value use <i>.*</i>',
-  );
-
-  $form['add_fields']['additional']['regex_transform']['new_regex']['replace'] = array(
-    '#type' => 'textfield',
-    '#title' => 'Replacement Pattern',
-    '#description' => 'This pattern should contain the text you want to replace the match pattern '
-    .'mentioned above. It can include references of the form \n where n is the number of the '
-    .'capture in the match pattern. For example, \1 will be replaced with the text matched in your '
-    .'first set of round brackets.',
-  );
-
-  if ($field_type == 'table field') {
-    $tab = '&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp';
-    $form['add_fields']['additional']['regex_transform']['new_regex']['replace']['#description'] .= '<p>'
-      .'The following references are also available for spreadsheet fields: <b><#column:<i>number</i>#></b>. '
-      .'This allows you to substitute other spreadsheet values into the current field. For example, '
-      .'if you had the following line:<br>'
-      . $tab . 'SNP' . $tab . '15-Jan-2011' . $tab . '1' . $tab . '54' . $tab . 'Contig34355'
-      .'<br> and your current field is for column #1 and you\'re inserting into the chado field '
-      .'feature.uniquename then you might want to add in the data to ensure your uniquename is '
-      .'unique. The Match Pattern is (.*) to select all the first column and the Replacement '
-      .'Pattern could be \1_<#column:2#> which would insert SNP_15-Jan-2011 into the database.</p>';
-  }
-
-  $form['add_fields']['additional']['regex_transform']['new_regex']['submit-add_transform'] = array(
-    '#type' => 'submit',
-    '#value' => 'Add Transformation',
-  );
-
-  $form['add_fields']['additional']['regex_transform']['test_regex'] = array(
-    '#type' => 'fieldset',
-    '#title' => 'Test Transformation Rules',
-  );
-
-  $form['add_fields']['additional']['regex_transform']['test_regex']['test_string'] = array(
-    '#type' => 'textfield',
-    '#title' => 'Test Value',
-    '#description' => 'This should be a value that you expect the above transformation rules '
-      .'to be applied to.',
-    '#default_value' => $form_state['storage']['test_regex_test'],
-  );
-
-  $form['add_fields']['additional']['regex_transform']['test_regex']['test_result'] = array(
-    '#type' => 'textfield',
-    '#title' => 'Test Result',
-    '#description' => 'This is the value that would be saved to the database after the above transformation '
-      .'riles were applied to the Test Value.',
-    '#default_value' => $form_state['storage']['test_regex_result'],
-  );
-
-  $form['add_fields']['additional']['regex_transform']['test_regex']['submit-test'] = array(
-    '#type' => 'submit',
-    '#value' => 'Test Transformation Rules'
-  );
-
-  $form['add_fields']['submit-add_field'] = array(
-      '#type' => 'submit',
-      '#value' => 'Add Field'
-  );
-
-  $form['add_fields']['submit-cancel'] = array(
-      '#type' => 'submit',
-      '#value' => 'Cancel'
-  );
-
-  return $form;
-}
-
-/**
- * Add Field Submit
- *
- * @param $form
- *   The form that was submitted
- * @param $form_state
- *   The values and storage for the form
- */
-function tripal_bulk_loader_add_template_field_form_submit($form, &$form_state) {
-
-  $op = $form_state['values'][ $form_state['clicked_button']['#name'] ];
-
-  if (!$form_state['ahah_submission']) {
-    if ($op ==  'Add Field') {
-
-      $template = $form_state['storage']['template_array'];
-
-       // If new record
-      if (preg_match('/NEW/', $form_state['values']['field_group'])) {
-        $record_name = $form_state['values']['record_name'];
-        $priority = sizeof($form_state['storage']['template_array']) + 1;
-        $record2priority[$record_name] = $priority;
-        $template[$priority]['table'] = $form_state['values']['chado_table'];
-        $template[$priority]['record_id'] = $record_name;
-
-      }
-      else {
-        $priority = $form_state['values']['field_group'];
-        $record_name = $record2priority[$priority];
-      }
-
-      // Add field to template array
-      if ($form_state['values']['field_type'] == 'table field') {
-        $field = array(
-          'type' => 'table field',
-          'title' => $form_state['values']['field_title'],
-          'field' => $form_state['values']['chado_field'],
-          'required' => $form_state['values']['required'],
-          //'allowed values' => empty by default,
-          'spreadsheet sheet' => $form_state['values']['sheet_name'],
-          'spreadsheet column' => $form_state['values']['column_number'],
-          'exposed' => $form_state['values']['column_exposed'],
-          'exposed_description' => $form_state['values']['column_exposed_desc'],
-        );
-      }
-      elseif ($form_state['values']['field_type'] == 'constant') {
-        $field = array(
-          'type' => 'constant',
-          'title' => $form_state['values']['field_title'],
-          'field' => $form_state['values']['chado_field'],
-          'required' => $form_state['values']['required'],
-          //'allowed values' => empty by default,
-          'constant value' => $form_state['values']['constant_value'],
-          'exposed' => $form_state['values']['constant_exposed'],
-          'exposed_validate' => $form_state['values']['constant_validate'],
-        );
-      }
-      elseif ($form_state['values']['field_type'] == 'foreign key') {
-        $field = array(
-          'type' => 'foreign key',
-          'title' => $form_state['values']['field_title'],
-          'field' => $form_state['values']['chado_field'],
-          'foreign key' => $form_state['values']['foreign_record'],
-          'required' => $form_state['values']['required'],
-        );
-      }
-
-      // Deal with any additional options
-      if ($form_state['storage']['regex']) {
-        $field['regex'] = $form_state['storage']['regex'];
-      }
-
-      // Save Template
-      $template[$priority]['fields'][] = $field;
-      $form_state['storage']['template']->template_array = serialize($template);
-      $success = drupal_write_record('tripal_bulk_loader_template', $form_state['storage']['template'], array('template_id'));
-
-      if ($success) {
-        drupal_set_message('Successfully Added Field to Template');
-        drupal_set_message('Template Saved.');
-
-        $path = explode('?', $form_state['storage']['referring URL']);
-        parse_str($path[1], $query);
-        $query['template_id'] = $form_state['storage']['template']->template_id;
-        drupal_goto($path[0], $query);
-      }
-      else {
-        drupal_set_message('Unable to Save Template!', 'error');
-        watchdog('T_bulk_loader',
-          'Unable to save bulk loader template: %template',
-          array('%template' => print_r($form_state['storage']['template'], TRUE)),
-          WATCHDOG_ERROR
-        );
-      }
-    }
-    elseif ($op ==  'Cancel') {
-        $path = explode('?', $form_state['storage']['referring URL']);
-        parse_str($path[1], $query);
-        $query['template_id'] = $form_state['storage']['template']->template_id;
-        drupal_goto($path[0], $query);
-    }
-    elseif ($op == 'Add Transformation') {
-
-      // Add transformation rule to original field
-      $form_state['storage']['regex']['pattern'][] = '/' . $form_state['values']['pattern'] . '/';
-      $form_state['storage']['regex']['replace'][] = $form_state['values']['replace'];
-      drupal_set_message('Successfully Added Transformation Rule');
-
-    }
-    elseif ($op == 'Save Transformation Rule Order') {
-
-      // Generate new regex array
-      $new_regex = array();
-      $old_regex = $form_state['storage']['regex'];
-      foreach ($form_state['values']['regex-data'] as $key => $element) {
-        $new_regex['pattern'][ $element['new_index'] ] = $old_regex['pattern'][ $element['old_index'] ];
-        $new_regex['replace'][ $element['new_index'] ] = $old_regex['replace'][ $element['old_index'] ];
-      }
-
-      // sort new regex arrays
-      asort($new_regex['pattern']);
-      asort($new_regex['replace']);
-
-      $form_state['storage']['regex'] = $new_regex;
-    }
-    elseif ($op == 'Delete Transformation') {
-
-      // Unset regex rule
-      $index = $form_state['clicked_button']['#name'];
-      unset($form_state['storage']['regex']['pattern'][$index]);
-      unset($form_state['storage']['regex']['replace'][$index]);
-
-    }
-    elseif ($op == 'Test Transformation Rules') {
-
-      $patterns = $form_state['storage']['regex']['pattern'];
-      $replaces = $form_state['storage']['regex']['replace'];
-      $test_string = $form_state['values']['test_string'];
-      $form_state['storage']['test_regex_result'] = preg_replace($patterns, $replaces, $test_string);
-      $form_state['storage']['test_regex_test'] = $test_string;
-    }
-  }
-
-}
-
-/**
- * Edit Field Form
- *
- * This form is meant to be called from a bulk loader form. The following should be set
- * in the query section of the path:
- *  - template_id=\d+: the template which the edited field is part of
- *  - record_id=\d+: the priority or key in the template array of the record the field
- *      is currently part of
- *  - field_index=\d+: the key of the field in the fields array of the previously
- *      specified record
- *
- * @param $form_state
- *   Contains the values and storage for the form
- * @return
- *   A form array to be rendered by drupal_get_form
- */
-function tripal_bulk_loader_edit_template_field_form(&$form_state = NULL) {
-  $form = array();
-   $form['#cache'] = TRUE; // Make sure the form is cached.
-
-   // get template id from path
-   $template_id = ($_GET['template_id']) ? $_GET['template_id'] : $form_state['values']['template_id'];
-
-   // if there is no template supplied don't return rest of form
-   if (!$template_id) {
-     return $form;
-   }
-
-  // Pre-set Variables needed for form proper------------------------------------------
-
-   // If this is the first load of the form (no form state) we need to initialize some variables
-   if (!$form_state['storage']['template']) {
-    $sql = "SELECT * FROM {tripal_bulk_loader_template} WHERE template_id=%d";
-    $template = db_fetch_object(db_query($sql, $template_id));
-    $form_state['storage']['template_array'] = unserialize($template->template_array);
-    $form_state['storage']['template'] = $template;
-
-    $form_state['storage']['record2priority'] = array();
-    foreach ($form_state['storage']['template_array'] as $priority => $record_array) {
-      if (!is_array($record_array)) {
-         continue;
-       }
-      $form_state['storage']['record2priority'][$record_array['record_id']] = $priority;
-    }
-
-    $form_state['storage']['referring URL'] = $_SERVER["HTTP_REFERER"];
-  }
-  else {
-    $template = $form_state['storage']['template'];
-  }
-
-  // get the field from the path
-  if (!($_GET['record_id']===NULL || $_GET['field_index']===NULL)) {
-    $priority = $_GET['record_id'];
-    $field_index = $_GET['field_index'];
-    $template_field = $form_state['storage']['template_array'][$priority]['fields'][$field_index];
-    $form_state['storage']['original_field'] = $template_field;
-    $form_state['storage']['original_field']['priority'] = $priority;
-    $form_state['storage']['original_field']['field_index'] = $field_index;
-  }
-
-  $field_type = ($form_state['values']['field_type'])? $form_state['values']['field_type'] : $template_field['type'];
-
-  // Tables and default table
-  $tables = tripal_core_get_chado_tables();
-  if ($form_state['values']) {
-    $table = $form_state['values']['chado_table'];
-  }
-  else {
-    $table = $form_state['storage']['template_array'][$priority]['table'];
-  }
-
-
-  // Fields and foreign key mappings
-  $chado_fields = array();
-  $fk_options = array();
-  $fk_options['NULL'] = 'None';
-  $table_description = module_invoke_all('chado_' . $table . '_schema');
-  if ($field_type == 'foreign key') {
-    $foreign_field2table = array();
-    foreach ($table_description['foreign keys'] as $key_table => $key_array) {
-      foreach ($key_array['columns'] as $left_field => $right_field) {
-        $chado_fields[$left_field] = $left_field;
-        $foreign_field2table[$left_field] = $key_table;
-      }
-    }
-    reset($chado_fields);
-
-    // set default field
-    if (empty($chado_fields)) {
-      $field = NULL;
-    }
-    elseif ($chado_fields[$form_state['values']['chado_field']]) {
-      $field = $form_state['values']['chado_field'];
-    }
-    elseif ($template_field['field']) {
-      $field = $template_field['field'];
-    }
-    else {
-      $field = current($chado_fields);
-    }
-    //dpm($field, 'field');
-
-    // Foreign key options
-    $foreign_table = $foreign_field2table[$field];
-    if ($foreign_table) {
-      foreach ($form_state['storage']['record2priority'] as $record_name_ => $priority_ ) {
-        if (preg_match('/^' . $foreign_table . '$/', $form_state['storage']['template_array'][$priority_]['table'])) {
-          $fk_options[$record_name_] = $record_name_;
-        }
-      }
-    }
-  }
-  else {
-    foreach ($table_description['fields'] as $field_name => $field_array) {
-        $chado_fields[$field_name] = $field_name;
-    }
-  }
-
-//  dpm(array( 'tables' => $tables, 'default table' => $table, 'record name' => $record_name, 'priority' => $priority,
-//    'fields' => $chad_fields, 'default field' => $field, 'foreign field=>table' => $foreign_field2table,
-//    'table desc' => $table_description, 'foreign record options' => $fk_options, 'foreign table' => $foreign_table
-//    ), 'Variables');
-
-  // Start of Form Proper--------------------------------------------------------------
-
-  $form['template_name'] = array(
-    '#type' => 'item',
-    '#title' => 'Template',
-    '#value' => $template->name,
-  );
-
-  $form['template_id'] = array(
-    '#type' => 'hidden',
-    '#value' => $template_id,
-  );
-
-  $form['edit_fields'] = array(
-    '#type' => 'fieldset',
-    '#prefix' => '<div id="tripal_bulk_loader_template-edit_field">',
-    '#suffix' => '</div>',
-  );
-
-  $form['edit_fields']['field_type'] = array(
-    '#type' => 'radios',
-    '#title' => t('Type of Field'),
-    '#options' => array(
-      'table field' => t('Spreadsheet: Fields which maps to a Spreadsheet Column'),
-      'constant' => t('Constant: Field which remains Constant throughout the Spreadsheet'),
-      'foreign key' => t('Foreign Key: Fields which map to a record in another table'),
-    ),
-    '#required' => TRUE,
-    '#default_value' => $field_type,
-    '#ahah' => array(
-      'path' => 'admin/tripal/tripal_bulk_loader_template/edit_field_ahah',
-      'wrapper' => 'tripal_bulk_loader_template-edit_field',
-      'effect' => 'fade'
-    ),
-  );
-
-  // check template array for records then edit one more
-  if (!$form_state['storage']['record2priority']) {
-    $groups = array();
-  }
-  else {
-    $groups = array_flip($form_state['storage']['record2priority']);
-  }
-  $groups['NONE'] = 'Select a Record';
-  $groups['NEW'] = 'New Record';
-  $form['edit_fields']['field_group']  = array(
-    '#type' => 'select',
-    '#title' => 'Record',
-    '#description' => 'This is used to group a set of fields together allowing '
-      .'multiple records to be inserted into the same table per line of the spreadsheet',
-    '#options' => $groups,
-    '#default_value' => (preg_match('/(\d+|\w+)/', $form_state['values']['field_group'])) ? $form_state['values']['field_group'] : $priority,
-    '#ahah' => array(
-      'path' => 'admin/tripal/tripal_bulk_loader_template/edit_field_ahah',
-      'wrapper' => 'tripal_bulk_loader_template-edit_field',
-      'effect' => 'fade'
-    ),
-    '#required' => TRUE,
-  );
-
-  $form['edit_fields']['record_name'] = array(
-    '#type' => (preg_match('/NEW/', $form_state['values']['field_group'])) ? 'textfield' : 'hidden',
-    '#title' => 'Unique Record Name',
-    '#prefix' => '<div id="tripal_bulk_loader_template-edit_record">',
-    '#suffix' => '</div>',
-    '#default_value' => $form_state['values']['record_name'],
-  );
-
-  $form['edit_fields']['field_title'] = array(
-    '#type' => 'textfield',
-    '#title' => t('Human-readable Title for Field'),
-    '#default_value' => ($form_state['values']['field_title']) ? $form_state['values']['field_title'] : $template_field['title'],
-  );
-
-  // Spreadsheet column
-  $form['edit_fields']['columns'] = array(
-    '#type' => 'fieldset',
-    '#title' => t('Spreadsheet Column'),
-    '#collapsible' => TRUE,
-    '#collapsed' => ($field_type == 'table field')? FALSE : TRUE,
-  );
-
-  $form['edit_fields']['columns']['sheet_name'] = array(
-    '#type' => 'textfield',
-    '#title' => t('Worksheet'),
-    '#description' => t('Specify the name of the worksheet.'),
-    '#size' => 5,
-    '#default_value' => ($form_state['values']['sheet_name'])? $form_state['values']['sheet_name'] : $template_field['spreadsheet sheet'],
-  );
-
-  $form['edit_fields']['columns']['column_number'] = array(
-    '#type' => 'textfield',
-    '#title' => t('Column'),
-    '#description' => t('Specify the column in the spreadsheet that this field maps to where the first column is 1.'),
-    '#size' => 5,
-    '#default_value' => ($form_state['values']['column_number']) ? $form_state['values']['column_number'] : $template_field['spreadsheet column'],
-  );
-
-  $form['edit_fields']['columns']['column_exposed'] = array(
-    '#type' => 'checkbox',
-    '#title' => t('Allow Column to be set for each Bulk Loading Job'),
-    '#description' => t('Adds a textbox field to the Bulk Loader Page to allow users to set this value.'),
-    '#default_value' => ($form_state['values']['column_exposed']) ? $form_state['values']['column_exposed'] : $template_field['exposed'],
-  );
-
-  $form['edit_fields']['columns']['column_exposed_desc'] = array(
-    '#type' => 'textfield',
-    '#title' => t('Description for exposed field on bulk loading job'),
-    '#description' => t('This description should tell the user what column should be entered here.'),
-    '#default_value' => ($form_state['values']['column_exposed_desc']) ? $form_state['values']['column_exposed_desc'] : $template_field['exposed_description'],
-  );
-
-  // Global Value
-  $form['edit_fields']['constant'] = array(
-    '#type' => 'fieldset',
-    '#title' => t('Constant'),
-    '#collapsible' => TRUE,
-    '#collapsed' => ($field_type == 'constant')? FALSE : TRUE,
-  );
-
-  $form['edit_fields']['constant']['constant_value'] = array(
-    '#type' => 'textfield',
-    '#title' => t('Constant Value'),
-    '#description' => t('Specify the value you wish this field to have regardless of spreadsheet data.'),
-    '#default_value' => ($form_state['values']['constant_value']) ? $form_state['values']['constant_value'] : $template_field['constant value'],
-  );
-
-  $form['edit_fields']['constant']['constant_exposed'] = array(
-    '#type' => 'checkbox',
-    '#title' => t('Allow Constant to be set for each Bulk Loading Job'),
-    '#description' => t('Adds a textbox field to the Create Bulk Loader Form to allow users to set this value.'),
-    '#default_value' => ($form_state['values']['constant_exposed']) ? $form_state['values']['constant_exposed'] : $template_field['exposed'],
-  );
-
-  $form['edit_fields']['constant']['constant_validate'] = array(
-    '#type' => 'checkbox',
-    '#title' => t('Ensure value is in table'),
-    '#description' => t('Checks the database when a bulk loading job is created to ensure the value entered already exists in the database.'),
-    '#default_value' => ($form_state['values']['constant_validate']) ? $form_state['values']['constant_validate'] : $template_field['exposed_validate'],
-  );
-
-  // Foreign Key
-  $form['edit_fields']['foreign_key'] = array(
-    '#type' => 'fieldset',
-    '#title' => 'Foreign Key',
-    '#collapsible' => TRUE,
-    '#collapsed' => ($field_type == 'foreign key')? FALSE : TRUE,
-  );
-
-  $form['edit_fields']['foreign_key']['foreign_record'] = array(
-    '#type' => 'select',
-    '#title' => 'Record to refer to',
-    '#descripion' => 'Select the record that this foreign key shouold refer to. The record needs to already exist and be of the correct table.',
-    '#options' => $fk_options,
-  );
-
-  // Chado Field
-  $form['edit_fields']['chado'] = array(
-    '#type' => 'fieldset',
-    '#title' => t('Chado Field/Column Details'),
-    '#description' => t('Specify the Table/Field in chado that this field maps to.'),
-  );
-
-  $form['edit_fields']['chado']['chado_table'] = array(
-    '#type' => 'select',
-    '#title' => t('Chado Table'),
-    '#options' => $tables,
-    '#default_value' => $table,
-    '#ahah' => array(
-      'path' => 'admin/tripal/tripal_bulk_loader_template/edit_field_ahah',
-      'wrapper' => 'tripal_bulk_loader_template-edit_field',
-      'effect' => 'fade'
-      ),
-  );
-
-  $form['edit_fields']['chado']['chado_field'] = array(
-    '#type' => 'select',
-    '#title' => t('Chado Field/Column'),
-    '#options' => $chado_fields,
-    '#default_value' => ($form_state['values']['chado_field']) ? $form_state['values']['chado_field'] : $template_field['field'],
-    '#ahah' => array(
-      'path' => 'admin/tripal/tripal_bulk_loader_template/edit_field_ahah',
-      'wrapper' => 'tripal_bulk_loader_template-edit_field',
-      'effect' => 'fade'
-    ),
-  );
-
-  $form['edit_fields']['additional'] = array(
-    '#type' => 'fieldset',
-    '#title' => 'Additional Options',
-  );
-
-  $form['edit_fields']['additional']['required'] = array(
-    '#type' => 'checkbox',
-    '#title' => 'Make this file required',
-    '#default_value' => $template_field['required'],
-  );
-
-  $form['edit_fields']['additional']['regex_transform'] = array(
-    '#type' => 'fieldset',
-    '#title' => 'Transform Spreadsheet Value Rules',
-    '#collapsible' => TRUE,
-    '#collapsed' => (!$template_field['regex']['pattern']) ? TRUE : FALSE,
-  );
-
-  $transformation_msg = '<p>A transformation rule allows you to transform the original value '
-      .'(usually from a user submitted spreadsheet) into the form you would like it stored '
-      .'in the chado database. Each rule consists of a match pattern (a php regular expression '
-      .'which determines which replacement patterns are applied and captures regions of the '
-      .'original value) and a replacement pattern (a string which may contain capture references '
-      .'that describes what the new value should be). Each rule is applied to the result of the '
-      .'previous rule.<p>';
-  $form['edit_fields']['additional']['regex_transform']['regex_description'] = array(
-    '#type' => 'item',
-    '#value' => $transformation_msg,
-  );
-
-  $form['edit_fields']['additional']['regex_transform']['regex-data'] = array(
-    '#tree' => TRUE,
-  );
-  foreach ($template_field['regex']['pattern'] as $index => $pattern) {
-    $data_element = array(
-      'pattern' => array(
-        '#type' => 'item',
-        '#value' => $pattern,
-      ),
-      'replace' => array(
-        '#type' => 'item',
-        '#value' => $template_field['regex']['replace'][$index],
-      ),
-      'old_index' => array(
-        '#type' => 'hidden',
-        '#value' => $index,
-      ),
-      'new_index' => array(
-        '#type' => 'select',
-        '#options' => range(0, sizeof($template_field['regex']['pattern'])-1),
-        '#default_value' => $index,
-      ),
-      'id' => array(
-        '#type' => 'hidden',
-        '#value' => $index,
-      ),
-      'submit-delete' => array(
-        '#type' => 'submit',
-        '#value' => 'Delete Transformation',
-        '#name' => $index,
-      ),
-    );
-    $form['edit_fields']['additional']['regex_transform']['regex-data'][$index] = $data_element;
-  }
-
-  $form['edit_fields']['additional']['regex_transform']['submit-reorder_regex'] = array(
-    '#type' => 'submit',
-    '#value' => 'Save Transformation Rule Order'
-  );
-
-  $form['edit_fields']['additional']['regex_transform']['new_regex'] = array(
-    '#type' => 'fieldset',
-    '#title' => 'Add a new Transformation Rule',
-  );
-
-  $form['edit_fields']['additional']['regex_transform']['new_regex']['pattern'] = array(
-    '#type' => 'textfield',
-    '#title' => 'Match Pattern',
-    '#description' => 'You can use standard <b>php regular expressions</b> in this field to specify a '
-      .'pattern. Only if this pattern matches the value in the spreadsheet does the replacement '
-      .'pattern get applied to the value. To capture a section of your value for use in the '
-      .'replacement patten surround with round brackets. For example, <i>GI:(\d+)</i> will match '
-      .' NCBI gi numbers and will capture the numerical digits for use in the replacement pattern. '
-      .' To match and capture any value use <i>.*</i>',
-  );
-
-  $form['edit_fields']['additional']['regex_transform']['new_regex']['replace'] = array(
-    '#type' => 'textfield',
-    '#title' => 'Replacement Pattern',
-    '#description' => '<p>This pattern should contain the text you want to replace the match pattern '
-    .'mentioned above. It can include references of the form <b>\n</b> where n is the number of the '
-    .'capture in the match pattern. For example, \1 will be replaced with the text matched in your '
-    .'first set of round brackets.</p>',
-  );
-
-  if ($field_type == 'table field') {
-    $tab = '&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp';
-    $form['edit_fields']['additional']['regex_transform']['new_regex']['replace']['#description'] .= '<p>'
-      .'The following references are also available for spreadsheet fields: <b><#column:<i>number</i>#></b>. '
-      .'This allows you to substitute other spreadsheet values into the current field. For example, '
-      .'if you had the following line:<br>'
-      . $tab . 'SNP' . $tab . '15-Jan-2011' . $tab . '1' . $tab . '54' . $tab . 'Contig34355'
-      .'<br> and your current field is for column #1 and you\'re inserting into the chado field '
-      .'feature.uniquename then you might want to add in the data to ensure your uniquename is '
-      .'unique. The Match Pattern is (.*) to select all the first column and the Replacement '
-      .'Pattern could be \1_<#column:2#> which would insert SNP_15-Jan-2011 into the database.</p>';
-  }
-
-  $form['edit_fields']['additional']['regex_transform']['new_regex']['submit-add_transform'] = array(
-    '#type' => 'submit',
-    '#value' => 'Add Transformation',
-  );
-
-  $form['edit_fields']['additional']['regex_transform']['test_regex'] = array(
-    '#type' => 'fieldset',
-    '#title' => 'Test Transformation Rules',
-  );
-
-  $form['edit_fields']['additional']['regex_transform']['test_regex']['test_string'] = array(
-    '#type' => 'textfield',
-    '#title' => 'Test Value',
-    '#description' => 'This should be a value that you expect the above transformation rules '
-      .'to be applied to.',
-    '#default_value' => $form_state['storage']['test_regex_test'],
-  );
-
-  $form['edit_fields']['additional']['regex_transform']['test_regex']['test_result'] = array(
-    '#type' => 'textfield',
-    '#title' => 'Test Result',
-    '#description' => 'This is the value that would be saved to the database after the above transformation '
-      .'riles were applied to the Test Value.',
-    '#default_value' => $form_state['storage']['test_regex_result'],
-  );
-
-  $form['edit_fields']['additional']['regex_transform']['test_regex']['submit-test'] = array(
-    '#type' => 'submit',
-    '#value' => 'Test Transformation Rules'
-  );
-
-  $form['edit_fields']['submit-edit_field'] = array(
-      '#type' => 'submit',
-      '#value' => 'Edit Field'
-  );
-
-  $form['edit_fields']['submit-cancel'] = array(
-      '#type' => 'submit',
-      '#value' => 'Cancel'
-  );
-
-  return $form;
-}
-
-/**
- * Edit Field Form Submit
- *
- * @param $form
- *   The form that was submitted
- * @param $form_state
- *   The values and storage for the form
- */
-function tripal_bulk_loader_edit_template_field_form_submit($form, &$form_state) {
-
-  $op = $form_state['values'][ $form_state['clicked_button']['#name'] ];
-  //dpm($op, 'Operation Submitted');
-
-  //Clear Test
-  $form_state['storage']['test_regex_result'] = NULL;
-  $form_state['storage']['test_regex_test'] = NULL;
-
-  if (!$form_state['ahah_submission']) {
-    if ($op ==  'Edit Field') {
-
-      // If new record
-      if (preg_match('/NEW/', $form_state['values']['field_group'])) {
-        // add new record
-        $record_name = $form_state['values']['record_name'];
-        $priority = sizeof($form_state['storage']['template_array']) + 1;
-        $old_priority = $form_state['storage']['original_field']['priority'];
-        $field_index = $form_state['storage']['original_field']['field_index'];
-        $form_state['storage']['record2priority'][$record_name] = $priority;
-        $form_state['storage']['template_array'][$priority]['table'] = $form_state['values']['chado_table'];
-        $form_state['storage']['template_array'][$priority]['record_id'] = $record_name;
-
-      }
-      else {
-        $priority = $form_state['values']['field_group'];
-        $old_priority = $form_state['storage']['original_field']['priority'];
-        $field_index = $form_state['storage']['original_field']['field_index'];
-        $record_name = $form_state['storage']['record2priority'][$priority];
-      }
-
-      $field = $form_state['storage']['original_field'];
-      if ($form_state['values']['field_type'] == 'table field') {
-          $field['type'] = 'table field';
-          $field['title'] = $form_state['values']['field_title'];
-          $field['field'] = $form_state['values']['chado_field'];
-          $field['required'] = $form_state['values']['required'];
-          //$field['allowed values'] = empty by default;
-          $field['spreadsheet sheet'] = $form_state['values']['sheet_name'];
-          $field['spreadsheet column'] = $form_state['values']['column_number'];
-          $field['exposed'] = $form_state['values']['column_exposed'];
-          $field['exposed_description'] = $form_state['values']['column_exposed_desc'];
-      }
-      elseif ($form_state['values']['field_type'] == 'constant') {
-          $field['type'] = 'constant';
-          $field['title'] = $form_state['values']['field_title'];
-          $field['field'] = $form_state['values']['chado_field'];
-          $field['required'] = $form_state['values']['required'];
-          //$field['allowed values'] = empty by default;
-          $field['constant value'] = $form_state['values']['constant_value'];
-          $field['exposed_validate'] = $form_state['values']['constant_validate'];
-          $field['exposed'] = $form_state['values']['constant_exposed'];
-      }
-      elseif ($form_state['values']['field_type'] == 'foreign key') {
-          $field['type'] = 'foreign key';
-          $field['title'] = $form_state['values']['field_title'];
-          $field['field'] = $form_state['values']['chado_field'];
-          $field['foreign key'] = $form_state['values']['foreign_record'];
-          $field['required'] = $form_state['values']['required'];
-      }
-
-      // Deal with any additional options
-
-      // if the record has changed...
-      $form_state['storage']['template_array'][$priority]['table'] = $form_state['values']['chado_table'];
-      if ($old_priority != $priority) {
-        $form_state['storage']['template_array'][$priority]['fields'][] = $field;
-        unset($form_state['storage']['template_array'][$old_priority]['fields'][$field_index]);
-
-        // if there are no fields left delete the old record
-        if (!$form_state['storage']['template_array'][$old_priority]['fields']) {
-          unset($form_state['storage']['template_array'][$old_priority]);
-        }
-      }
-      else {
-        $form_state['storage']['template_array'][$priority]['fields'][$field_index] = $field;
-      }
-
-      // Save Template
-      $form_state['storage']['template']->template_array = serialize($form_state['storage']['template_array']);
-      $success = drupal_write_record('tripal_bulk_loader_template', $form_state['storage']['template'], array('template_id'));
-
-      if ($success) {
-        drupal_set_message('Successfully Updated Field');
-        drupal_set_message('Template Saved.');
-
-        $path = explode('?', $form_state['storage']['referring URL']);
-        parse_str($path[1], $query);
-        $query['template_id'] = $form_state['storage']['template']->template_id;
-        drupal_goto($path[0], $query);
-      }
-      else {
-        drupal_set_message('Unable to Save Template!', 'error');
-        watchdog('T_bulk_loader',
-          'Unable to save bulk loader template: %template',
-          array('%template' => print_r($form_state['storage']['template'], TRUE)),
-          WATCHDOG_ERROR
-        );
-      }
-
-    }
-    elseif ($op ==  'Cancel') {
-
-        $path = explode('?', $form_state['storage']['referring URL']);
-        parse_str($path[1], $query);
-        $query['template_id'] = $form_state['storage']['template']->template_id;
-        drupal_goto($path[0], $query);
-
-    }
-    elseif ($op == 'Add Transformation') {
-
-      // Add transformation rule to original field
-      $form_state['storage']['original_field']['regex']['pattern'][] = '/' . $form_state['values']['pattern'] . '/';
-      $form_state['storage']['original_field']['regex']['replace'][] = $form_state['values']['replace'];
-
-      // Add original field back into template
-      $priority = $form_state['storage']['original_field']['priority'];
-      $field_index = $form_state['storage']['original_field']['field_index'];
-      $form_state['storage']['template_array'][$priority]['fields'][$field_index] = $form_state['storage']['original_field'];
-
-      // Save Template
-      $form_state['storage']['template']->template_array = serialize($form_state['storage']['template_array']);
-      $success = drupal_write_record('tripal_bulk_loader_template', $form_state['storage']['template'], array('template_id'));
-
-      if ($success) {
-        drupal_set_message('Successfully Added Transformation Rule');
-        drupal_set_message('Template Saved.');
-      }
-      else {
-        drupal_set_message('Unable to Save Template!', 'error');
-        watchdog('T_bulk_loader',
-          'Unable to save bulk loader template: %template',
-          array('%template' => print_r($form_state['storage']['template'], TRUE)),
-          WATCHDOG_ERROR
-        );
-      }
-    }
-    elseif ($op == 'Save Transformation Rule Order') {
-
-      // Generate new regex array
-      $new_regex = array();
-      $old_regex = $form_state['storage']['original_field']['regex'];
-      foreach ($form_state['values']['regex-data'] as $key => $element) {
-        $new_regex['pattern'][ $element['new_index'] ] = $old_regex['pattern'][ $element['old_index'] ];
-        $new_regex['replace'][ $element['new_index'] ] = $old_regex['replace'][ $element['old_index'] ];
-      }
-
-      // sort new regex arrays
-      asort($new_regex['pattern']);
-      asort($new_regex['replace']);
-
-      // Add back to original field
-      $form_state['storage']['original_field']['regex'] = $new_regex;
-      $priority = $form_state['storage']['original_field']['priority'];
-      $field_index = $form_state['storage']['original_field']['field_index'];
-      $form_state['storage']['template_array'][$priority]['fields'][$field_index] = $form_state['storage']['original_field'];
-
-      // Save Template
-      $form_state['storage']['template']->template_array = serialize($form_state['storage']['template_array']);
-      $success = drupal_write_record('tripal_bulk_loader_template', $form_state['storage']['template'], array('template_id'));
-
-      if ($success) {
-        drupal_set_message('Successfully Reordered Transformation Rules');
-        drupal_set_message('Template Saved.');
-      }
-      else {
-        drupal_set_message('Unable to Save Template!', 'error');
-        watchdog('T_bulk_loader',
-          'Unable to save bulk loader template: %template',
-          array('%template' => print_r($form_state['storage']['template'], TRUE)),
-          WATCHDOG_ERROR
-        );
-      }
-    }
-    elseif ($op == 'Delete Transformation') {
-
-      // Unset regex rule
-      $index = $form_state['clicked_button']['#name'];
-      unset($form_state['storage']['original_field']['regex']['pattern'][$index]);
-      unset($form_state['storage']['original_field']['regex']['replace'][$index]);
-
-      $priority = $form_state['storage']['original_field']['priority'];
-      $field_index = $form_state['storage']['original_field']['field_index'];
-      $form_state['storage']['template_array'][$priority]['fields'][$field_index] = $form_state['storage']['original_field'];
-
-      // Save Template
-      $form_state['storage']['template']->template_array = serialize($form_state['storage']['template_array']);
-      $success = drupal_write_record('tripal_bulk_loader_template', $form_state['storage']['template'], array('template_id'));
-
-      if ($success) {
-        drupal_set_message('Successfully Reordered Transformation Rules');
-        drupal_set_message('Template Saved.');
-      }
-      else {
-        drupal_set_message('Unable to Save Template!', 'error');
-        watchdog('T_bulk_loader',
-          'Unable to save bulk loader template: %template',
-          array('%template' => print_r($form_state['storage']['template'], TRUE)),
-          WATCHDOG_ERROR
-        );
-      }
-
-    }
-    elseif ($op == 'Test Transformation Rules') {
-
-      $patterns = $form_state['storage']['original_field']['regex']['pattern'];
-      $replaces = $form_state['storage']['original_field']['regex']['replace'];
-      $test_string = $form_state['values']['test_string'];
-      $form_state['storage']['test_regex_result'] = preg_replace($patterns, $replaces, $test_string);
-      $form_state['storage']['test_regex_test'] = $test_string;
-    }
-  }
-
-}
-
-//////////////////////////////////////////////////////////////////////////////////////
-// AHAH Callbacks
-//////////////////////////////////////////////////////////////////////////////////////
-
-/**
- * AHAH Function: Replace $form['add_fields'] in tripal_bulk_loader_add_template_field_form
- *
- * @return
- *  JSON Data printed to the screen
- */
-function tripal_bulk_loader_add_field_ahah() {
-
-  $form_state = array('storage' => NULL, 'submitted' => FALSE);
-  $form_build_id = $_POST['form_build_id'];
-  $form = form_get_cache($form_build_id, $form_state);
-  $args = $form['#parameters'];
-  $form_id = array_shift($args);
-  $form_state['post'] = $form['#post'] = $_POST;
-
-  // Enable the submit/validate handlers to determine whether AHAH-submittted.
-  $form_state['ahah_submission'] = TRUE;
-
-  $form['#programmed'] = $form['#redirect'] = FALSE;
-  drupal_process_form($form_id, $form, $form_state);
-  $form = drupal_rebuild_form($form_id, $form_state, $args, $form_build_id);
-
-  $form_element = $form['add_fields'];
-  // Remove the wrapper so we don't double it up.
-  //unset($form_element['#prefix'], $form_element['#suffix']);
-
-  $output = theme('status_messages');
-  $output .= drupal_render($form_element);
-
-  // Final rendering callback.
-  print drupal_json(array('status' => TRUE, 'data' => $output));
-  exit();
-
-}
-
-/**
- * AHAH Function: Replace $form['edit_fields'] in tripal_bulk_loader_edit_template_field_form
- *
- * @return
- *  JSON Data printed to the screen
- */
-function tripal_bulk_loader_edit_field_ahah() {
-
-  $form_state = array('storage' => NULL, 'submitted' => FALSE);
-  $form_build_id = $_POST['form_build_id'];
-  $form = form_get_cache($form_build_id, $form_state);
-  $args = $form['#parameters'];
-  $form_id = array_shift($args);
-  $form_state['post'] = $form['#post'] = $_POST;
-
-  // Enable the submit/validate handlers to determine whether AHAH-submittted.
-  $form_state['ahah_submission'] = TRUE;
-
-  $form['#programmed'] = $form['#redirect'] = FALSE;
-  drupal_process_form($form_id, $form, $form_state);
-  $form = drupal_rebuild_form($form_id, $form_state, $args, $form_build_id);
-
-  $form_element = $form['edit_fields'];
-  // Remove the wrapper so we don't double it up.
-  unset($form_element['#prefix'], $form_element['#suffix']);
-
-  $output = theme('status_messages');
-  $output .= drupal_render($form_element);
-
-  // Final rendering callback.
-  print drupal_json(array('status' => TRUE, 'data' => $output));
-  exit();
+  variable_set('tripal_bulk_loader_prepare', $form_state['values']['prepare']);
+  variable_set('tripal_bulk_loader_disable_triggers', $form_state['values']['disable_triggers']);
+  variable_set('tripal_bulk_loader_skip_validation', $form_state['values']['no_validate']);
+  variable_set('tripal_bulk_loader_transactions', $form_state['values']['transactions']);
+  variable_set('tripal_bulk_loader_lock', $form_state['values']['lock']);
 
 }

+ 2149 - 2426
tripal_bulk_loader/tripal_bulk_loader.admin.inc.orig → tripal_bulk_loader/tripal_bulk_loader.admin.templates.inc

@@ -1,2427 +1,2150 @@
-<?php
-
-/**
- * @file
- * Handles Create/Edit/Delete Template Admin Forms
- */
-
-/**
- * Provides a description page and quick links for the bulk loader
- */
-<<<<<<< HEAD
-function tripal_bulk_loader_admin_template() {
-  $output = '';
-
-  $output .= '<br><h3>Quick Links:</h3>';
-  $output .= l('Create a new bulk loader template', 'admin/tripal/tripal_bulk_loader_template/create') . "<br>";
-  $output .= l('Edit a bulk loader template', 'admin/tripal/tripal_bulk_loader_template/edit') . "<br>";
-  $output .= l('Delete a bulk loader template', 'admin/tripal/tripal_bulk_loader_template/delete') . "<br>";
-  $output .= l('Export a bulk loader template', 'admin/tripal/tripal_bulk_loader_template/export') . "<br>";
-  $output .= l('Import a bulk loader template', 'admin/tripal/tripal_bulk_loader_template/import') . "<br>";
-=======
-function tripal_bulk_loader_admin_template () {
-	$output = '';
-
-	$output .= '<br><h3>Quick Links:</h3>';
-  $output .= l('Create a new bulk loader template', 'admin/tripal/tripal_bulk_loader_template/create')."<br>";
-  $output .= l('Edit a bulk loader template', 'admin/tripal/tripal_bulk_loader_template/edit')."<br>";
-  $output .= l('Delete a bulk loader template', 'admin/tripal/tripal_bulk_loader_template/delete')."<br>";
-  $output .= l('Export a bulk loader template', 'admin/tripal/tripal_bulk_loader_template/export')."<br>";
-  $output .= l('Import a bulk loader template', 'admin/tripal/tripal_bulk_loader_template/import')."<br>";
->>>>>>> 6.x-0.4-dev
-  $output .= '<br>';
-
-  $output .= '<h3>Module Description:</h3>';
-  $output .= '<p>This module provides the ability to create loading templates for any tab-delimited '
-    . 'data file allowing it to be loaded into chado. The Loading Templates are a direct mapping '
-    . 'between the columns in your file and the columns in chado tables. As such to use this tool '
-    . 'you need to be very familar with the chado schema -See '
-    . l('Chado -Getting Started', 'http://gmod.org/wiki/Chado_-_Getting_Started')
-    . '. The ability to add constants and specify foreign key contraints is also provided '
-    . 'in order for the loader to fill chado columns which may be required but are not specified '
-    . 'in your input file.</p>';
-  $output .= '<br>';
-
-  $output .= '<h3>Setup Instructions</h3>';
-  $output .= '<p>After intallation of the bulk loader module, the following tasks should be performed:</p>';
-  $output .= '<ol>';
-  $output .= '<li><b>Install Theme:</b> In order for Bulk Loading pages to be displayed correctly, '
-    .'the contents of the Tripal Bulk Loader theme directory ([drupal root]/sites/all/modules/tripal/tripal_bulk_loader/theme) '
-    .'should be moved to the base directory of the Tripal theme ([drupal root]/sites/all/themes/tripal). '
-    .'Finally the drupal cache should be cleared for the new theme to take effect -navigate to admin/settings/performance '
-    .'and click the Clear Cached Data button.</li>';
-  $output .= '</ol>';
-
-  return $output;
-}
-
-/**
- * A Configuration form for this module
- */
-function tripal_bulk_loader_configuration_form($form_state = NULL) {
-  $form = array();
-
-  $form['speed'] = array(
-    '#type' => 'fieldset',
-    '#title' => t('Possible Speed Improvements'),
-  );
-
-  $form['speed']['prepare'] = array(
-    '#type' => 'checkbox',
-    '#title' => t('Use Prepared Statements'),
-    '#description' => t('SQL Prepared Statements allow for SQL queries which will be run '
-      .'many times to be parsed, rewritten and planned only once rather then every time '
-      .'the query is run. In the case of the bulk loader, this ensures that planning only '
-      .'occurs once for each "record" in your bulk loading template.'),
-    '#default_value' => variable_get('tripal_bulk_loader_prepare', TRUE),
-  );
-
-  $form['submit1'] = array(
-    '#type' => 'submit',
-    '#value' => t('Save')
-  );
-
-  return $form;
-}
-
-/**
- * A Configuration form for this module (Submit)
- */
-function tripal_bulk_loader_configuration_form_submit($form, $form_state) {
-
-  variable_set('tripal_bulk_loader_prepare', $form_state['values']['prepare']);
-}
-
-//////////////////////////////////////////////////////////////////////////////////////
-// Modify Template
-//////////////////////////////////////////////////////////////////////////////////////
-
-
-/**
- * The main form reached at admin/tripal/tripal_bulk_loader/create and /edit
- */
-function tripal_bulk_loader_modify_template_base_form($form_state = NULL, $mode) {
-  $form = array();
-
-   // get template id from path and rebuild form
-   if ($_GET['template_id']) {
-    if (preg_match('/^\d+$/', $_GET['template_id'])) {
-      $form_state['storage']['template_id'] = $_GET['template_id'];
-    }
-
-    $sql = "SELECT * FROM {tripal_bulk_loader_template} WHERE template_id=%d";
-    $result = db_fetch_object(db_query($sql, $form_state['storage']['template_id']));
-    $form_state['storage']['template'] = unserialize($result->template_array);
-    $form_state['storage']['template_name'] = $result->name;
-
-    $form_state['storage']['record2priority'] = array();
-    foreach ($form_state['storage']['template'] as $priority => $record_array) {
-      if (!is_array($record_array)) {
-      continue; }
-      $form_state['storage']['record2priority'][$record_array['record_id']] = $priority;
-    }
-  }
-
-  $form['mode'] = array(
-    '#type' => 'hidden',
-    '#value' => $mode,
-  );
-
-  if ($form_state['storage']['template_id']) {
-    $form['template_name'] = array(
-        '#type' => 'item',
-        '#title' => 'Template',
-        '#value' => $form_state['storage']['template_name'],
-        '#weight' => 1,
-    );
-  }
-  else {
-    if (preg_match('/create/', $mode)) {
-     $form['new_template_name'] = array(
-        '#type' => 'textfield',
-        '#title' => 'Template Name',
-        '#weight' => 1,
-      );
-    }
-    elseif (preg_match('/edit/', $mode)) {
-      $sql = "SELECT * FROM {tripal_bulk_loader_template}";
-      $resource = db_query($sql);
-      $templates = array();
-      $templates[''] = 'Select a Template';
-      while ($r = db_fetch_object($resource)) {
-        $templates[$r->template_id] = $r->name;
-      }
-
-      $form['template_id'] = array(
-        '#title'         => t('Template'),
-        '#description'   => t('Please select the template you would like to edit.'),
-        '#type'          => 'select',
-        '#options'       => $templates,
-        '#default_value' => $form_state['storage']['template_id'],
-        '#weight'        => 0,
-        '#required'      => TRUE,
-        '#weight' => 1,
-      );
-    }
-  }
-
-  $form['records'] = array(
-<<<<<<< HEAD
-    '#type' => ($form_state['storage']['template_id'])? 'fieldset' : 'hidden',
-    '#title' => t('Current Records'),
-    '#collapsible' => TRUE,
-    '#weight' => 2,
-=======
-		'#type' => ($form_state['storage']['template_id'])? 'fieldset' : 'hidden',
-		'#title' => t('Current Records'),
-		'#collapsible' => TRUE,
-		'#weight' => 2,
->>>>>>> 6.x-0.4-dev
-  );
-
-  $form['records']['description'] = array(
-    '#type' => 'item',
-    '#value' => 'Records will be inserted into the chado database in the order listed below. To '
-      .'change this order: <ul><li>Drag the rows into the correct order OR</li><li>Enter '
-      .'the numbers 1 and up in the Order textboxes to indicate the correct order.</li></ul>',
-  );
-
-  $form['records']['records-data'] = array(
-    '#tree' => TRUE,
-  );
-
-  $form['records']['no_records'] = array(
-    '#type' => 'hidden',
-    '#value' => TRUE,
-  );
-
-  $form['records']['submit-new_record'] = array(
-    '#type' => 'submit',
-    '#value' => 'New Record/Field',
-  );
-
-  $form['records']['submit-reorder'] = array(
-    '#type' => 'submit',
-    '#value' => 'Save Order',
-  );
-
-<<<<<<< HEAD
-  $form['fields'] = array(
-    '#type' => ($form_state['storage']['template_id'])? 'fieldset' : 'hidden',
-    '#title' => t('Current Fields'),
-    '#collapsible' => TRUE,
-    '#weight' => 3,
-  );
-=======
-	$form['fields'] = array(
-		'#type' => ($form_state['storage']['template_id'])? 'fieldset' : 'hidden',
-		'#title' => t('Current Fields'),
-		'#collapsible' => TRUE,
-		'#weight' => 3,
-	);
->>>>>>> 6.x-0.4-dev
-
-  $form['fields']['fields-data'] = array(
-    '#tree' => TRUE,
-  );
-
-<<<<<<< HEAD
-  if ($form_state['storage']['template']) {
-=======
-	if ($form_state['storage']['template']) {
->>>>>>> 6.x-0.4-dev
-
-    // List Current Fields -------------------------------------------------------------
-    $i=1;
-    foreach ($form_state['storage']['template'] as $priority => $table_array) {
-<<<<<<< HEAD
-      if (!is_array($table_array)) {
-      continue; }
-=======
-      if (!is_array($table_array)) { continue; }
->>>>>>> 6.x-0.4-dev
-
-        $form['records']['no_records']['#value'] = FALSE;
-
-        $form['records']['records-data'][$priority] = array(
-          'title' => array(
-            '#type' => 'markup',
-            '#value' => $table_array['record_id'],
-          ),
-          'chado_table' => array(
-            '#type' => 'markup',
-            '#value' => $table_array['table'],
-          ),
-          'mode' => array(
-            '#type' => 'item',
-            '#value' => ($table_array['mode']) ? $table_array['mode'] : 'insert_unique',
-          ),
-          'new_priority' => array(
-            '#type' => 'select',
-            '#options' => range(1, sizeof($form_state['storage']['template'])),
-            '#default_value' => $priority,
-          ),
-          'old_priority' => array(
-            '#type' => 'hidden',
-            '#value' => $priority,
-          ),
-          'id'  => array(
-            '#type' => 'hidden',
-            '#value' => $priority,
-          ),
-          'submit-edit_record' => array(
-            '#type' => 'submit',
-            '#name' => (string)$priority,
-            '#value' => 'Edit Record',
-          ),
-          'submit-add_field' => array(
-            '#type' => 'submit',
-            '#name' => (string)$priority,
-            '#value' => 'Add Field',
-          ),
-          'submit-duplicate_record' => array(
-            '#type' => 'submit',
-            '#name' => (string)$priority,
-            '#value' => 'Duplicate Record'
-          ),
-        );
-
-        foreach ($table_array['fields'] as $field_index => $field) {
-
-          $form['fields']['fields-data'][$i] = array(
-            'record_id' => array(
-              '#type' => 'item',
-              '#value' => $table_array['record_id'],
-            ),
-            'priority_hidden' => array(
-              '#type' => 'hidden',
-              '#value' => $priority,
-            ),
-            'field_name' => array(
-              '#type' => 'item',
-              '#value' => $field['title'],
-            ),
-            'chado_table_name' => array(
-              '#type' => 'item',
-              '#value' => $table_array['table'],
-            ),
-            'chado_table_hidden' => array(
-              '#type' => 'hidden',
-              '#value' => $table_array['table'],
-            ),
-            'chado_field_name' => array(
-              '#type' => 'item',
-              '#value' => $field['field'],
-            ),
-            'sheet_name' => array(
-              '#type' => 'item',
-              '#value' => $field['spreadsheet sheet'],
-            ),
-            'column_num' => array(
-              '#type' => 'item',
-              '#value' => $field['spreadsheet column'],
-            ),
-            'constant_value' => array(
-              '#type' => 'item',
-              '#value' => $field['constant value'],
-            ),
-            'field_index' => array(
-              '#type' => 'hidden',
-              '#value' => $field_index
-            ),
-            'foreign_record_id' => array(
-              '#type' => 'item',
-              '#value' => $field['foreign key'],
-            ),
-            'edit_submit' => array(
-              '#type' => 'submit',
-              '#name' => (string)$i,
-              '#value' => "Edit Field",
-            ),
-            'delete_submit' => array(
-              '#type' => 'submit',
-              '#name' => (string)$i,
-              '#value' => "Delete Field",
-            ),
-          );
-
-          $i++;
-        }
-    }
-    $form['fields']['total_fields'] = array(
-      '#type' => 'item',
-      '#value' => $i,
-    );
-
-  }
-
-  if ($form['records']['no_records']['#value']) {
-    $form['records']['description'] = array(
-      '#type' => 'item',
-      '#value' => 'There are currently no records.',
-    );
-    unset($form['records']['submit-reorder']);
-
-    $form['fields']['description'] = array(
-      '#type' => 'item',
-      '#value' => 'There are currently no fields.',
-    );
-
-  }
-
-<<<<<<< HEAD
-  $mode_title = (preg_match('/create/', $mode)) ? 'Create Template' : 'Edit Template';
-  $value = ($form_state['storage']['template_id'])? 'Save Template' : $mode_title;
-  $form['submit'] = array(
-    '#type' => 'submit',
-    '#value' => $value,
-    '#weight' => 4,
-  );
-  return $form;
-=======
-  $mode_title = (preg_match('/create/',$mode)) ? 'Create Template' : 'Edit Template';
-	$value = ($form_state['storage']['template_id'])? 'Save Template' : $mode_title;
-	$form['submit'] = array(
-		'#type' => 'submit',
-		'#value' => $value,
-		'#weight' => 4,
-	);
-
-	return $form;
->>>>>>> 6.x-0.4-dev
-}
-
-/**
- * Submit for tripal_bulk_loader_modify_template_base_form
- */
-function tripal_bulk_loader_modify_template_base_form_submit($form, &$form_state) {
-
-  $form_state['rebuild'] = TRUE;
-  if ($form_state['storage']['template_id']) {
-    $sql = "SELECT * FROM {tripal_bulk_loader_template} WHERE template_id=%d";
-    $result = db_fetch_object(db_query($sql, $form_state['storage']['template_id']));
-    $form_state['storage']['template'] = unserialize($result->template_array);
-  }
-
-  $op = $form_state['values'][ $form_state['clicked_button']['#name'] ];
-  switch ($op) {
-    // Initialize after template is chosen ----------------------------------------
-    case 'Edit Template':
-      $form_state['storage']['template_id'] = $form_state['values']['template_id'];
-
-      $sql = "SELECT * FROM {tripal_bulk_loader_template} WHERE template_id=%d";
-      $result = db_fetch_object(db_query($sql, $form_state['storage']['template_id']));
-      $form_state['storage']['template'] = unserialize($result->template_array);
-      $form_state['storage']['template_name'] = $result->name;
-
-      $form_state['storage']['record2priority'] = array();
-      foreach ($form_state['storage']['template'] as $priority => $record_array) {
-        if (!is_array($record_array)) {
-         continue;
-         }
-        $form_state['storage']['record2priority'][$record_array['record_id']] = $priority;
-      }
-    break;
-
-    case 'Create Template':
-      $record = array(
-        'name' => $form_state['values']['new_template_name'],
-        'template_array' => array(),
-      );
-      drupal_write_record('tripal_bulk_loader_template', $record);
-      $form_state['storage']['template_id'] = $record['template_id'];
-      $form_state['storage']['template_name'] = $record['name'];
-      $form_state['storage']['template'] = array();
-    break;
-
-    // Save Reordered Records -----------------------------------------------------
-    case 'Save Order':
-      $new_template = $form_state['storage']['template'];
-      // unset old elements
-       $form_state['storage']['record2priority'] = array();
-      foreach ($new_template as $priority => $record_array) {
-<<<<<<< HEAD
-        if (preg_match('/\d+/', $priority)) {
-           unset($new_template[$priority]);
-         }
-=======
-        if (preg_match('/\d+/', $priority)) { unset($new_template[$priority]); }
->>>>>>> 6.x-0.4-dev
-      }
-      //set elements in new order
-      foreach ($form_state['values']['records-data'] as $item) {
-        $new_template[$item['new_priority']] = $form_state['storage']['template'][$item['old_priority']];
-        $record_name = $new_template[$item['new_priority']]['record_id'];
-        $form_state['storage']['record2priority'][$record_name] = $item['new_priority'];
-      }
-      ksort($new_template);
-      $form_state['storage']['template'] = $new_template;
-    break;
-
-    case 'New Record/Field':
-      $query = array(
-<<<<<<< HEAD
-        'template_id' => $form_state['storage']['template_id'],
-=======
-        'template_id'=> $form_state['storage']['template_id'],
->>>>>>> 6.x-0.4-dev
-        'record_id' => 'NEW',
-      );
-      drupal_goto('admin/tripal/tripal_bulk_loader_template/add_field', $query);
-    break;
-
-    case 'Edit Record':
-      $query = array(
-<<<<<<< HEAD
-        'template_id' => $form_state['storage']['template_id'],
-=======
-        'template_id'=> $form_state['storage']['template_id'],
->>>>>>> 6.x-0.4-dev
-        'record_id' => $form_state['clicked_button']['#name'],
-      );
-      drupal_goto('admin/tripal/tripal_bulk_loader_template/edit_record', $query);
-    break;
-
-    case 'Add Field':
-      $query = array(
-<<<<<<< HEAD
-        'template_id' => $form_state['storage']['template_id'],
-=======
-        'template_id'=> $form_state['storage']['template_id'],
->>>>>>> 6.x-0.4-dev
-        'record_id' => $form_state['clicked_button']['#name'],
-      );
-      drupal_goto('admin/tripal/tripal_bulk_loader_template/add_field', $query);
-    break;
-
-    case 'Duplicate Record':
-      // original record (one to be duplicated)
-      $orig_priority = $form_state['clicked_button']['#name'];
-      $record = $form_state['storage']['template'][ $orig_priority ];
-
-      // new record
-      $new_priority = sizeof($form_state['storage']['template']) + 1;
-      $record['record_id'] = $record['record_id'] . '_' . date('YzHi');
-      $form_state['storage']['template'][ $new_priority ] = $record;
-    break;
-
-    case 'Edit Field':
-      $field_data_index = $form_state['clicked_button']['#name'];
-      $query = array(
-<<<<<<< HEAD
-        'template_id' => $form_state['storage']['template_id'],
-=======
-        'template_id'=> $form_state['storage']['template_id'],
->>>>>>> 6.x-0.4-dev
-        'record_id' => $form_state['values']['fields-data'][$field_data_index]['priority_hidden'],
-        'field_index' => $form_state['values']['fields-data'][$field_data_index]['field_index'],
-      );
-      drupal_goto('admin/tripal/tripal_bulk_loader_template/edit_field', $query);
-    break;
-
-    case 'Delete Field':
-      $field_data = $form_state['values']['fields-data'][$form_state['clicked_button']['#name']];
-      $priority = $field_data['priority_hidden'];
-      $field_key = $field_data['field_index'];
-      unset($form_state['storage']['template'][$priority]['fields'][$field_key]);
-      if (!$form_state['storage']['template'][$priority]['fields']) {
-        unset($form_state['storage']['record2priority'][$form_state['storage']['template'][$priority]['record_id']]);
-        unset($form_state['storage']['template'][$priority]);
-      }
-      drupal_set_message('Deleted Field from Template.');
-    break;
-  } //end of switch
-
-  // Save Template
-  $record = array(
-    'template_id' => $form_state['storage']['template_id'],
-    'template_array' => serialize($form_state['storage']['template'])
-  );
-  drupal_write_record('tripal_bulk_loader_template', $record, array('template_id'));
-  drupal_set_message('Template Saved.');
-
-}
-
-//////////////////////////////////////////////////////////////////////////////////////
-// Delete Template
-//////////////////////////////////////////////////////////////////////////////////////
-
-/**
- * Delete Template Form
- * This form allows admin to delete already existing templates
- */
-function tripal_bulk_loader_delete_template_base_form() {
-  $form = array();
-
-  $sql = "SELECT * FROM {tripal_bulk_loader_template}";
-  $resource = db_query($sql);
-  $templates = array();
-  $templates[''] = 'Select a Template';
-  while ($r = db_fetch_object($resource)) {
-    $templates[$r->template_id] = $r->name;
-  }
-  $form['template_name'] = array(
-      '#title'         => t('Template'),
-      '#description'   => t('Please select the template you would like to delete.'),
-      '#type'          => 'select',
-      '#options'       => $templates,
-      '#weight'        => 0,
-      '#required'      => TRUE,
-<<<<<<< HEAD
-  );
-
-  $form['submit'] = array(
-    '#type' => 'submit',
-    '#value' => 'Delete Template',
-  );
-
-  return $form;
-=======
-	);
-
-	$form['submit'] = array(
-		'#type' => 'submit',
-		'#value' => 'Delete Template',
-	);
-
-	return $form;
->>>>>>> 6.x-0.4-dev
-}
-
-/**
- * Delete Template Form Submit
- *
- * @param $form
- *   The form that was submitted
- * @param $form_state
- *   The values and storage that were submitted
- */
-function tripal_bulk_loader_delete_template_base_form_submit($form, &$form_state) {
-  $sql = "DELETE FROM {tripal_bulk_loader_template} WHERE template_id=%d";
-  db_query($sql, $form_state['values']['template_name']);
-}
-
-//////////////////////////////////////////////////////////////////////////////////////
-// Import/Export Template
-//////////////////////////////////////////////////////////////////////////////////////
-
-/**
- * Import/Export Template Form
- *
- * On export, simply selects the serialized array from the db for a given template
- * and presents it to the user. On import, a serialized template array and a name is
- * supplied and a template record is created.
- *
- * @todo Make array presented to the user more readable. (ie: unserialize and print to the screen)
- *
- * @param $form_state
- *   The values and storage for the form
- * @param $mode
- *   Either 'import' or 'export' to indicate which function is being performed
- * @return
- *   A form array to be rendered by drupal_get_form
- */
-function tripal_bulk_loader_import_export_template_form($form_state = NULL, $mode) {
-  $form = array();
-
-  $form['mode'] = array(
-    '#type' => 'hidden',
-    '#value' => $mode,
-  );
-
-  if (preg_match('/import/', $mode)) {
-   $form['new_template_name'] = array(
-      '#type' => 'textfield',
-      '#title' => 'Template Name',
-      '#weight' => 1,
-    );
-  }
-  elseif (preg_match('/export/', $mode)) {
-    $sql = "SELECT * FROM {tripal_bulk_loader_template}";
-    $resource = db_query($sql);
-    $templates = array();
-    $templates[''] = 'Select a Template';
-    while ($r = db_fetch_object($resource)) {
-      $templates[$r->template_id] = $r->name;
-    }
-
-    $form['template_id'] = array(
-      '#title'         => t('Template'),
-      '#description'   => t('Please select the template you would like to edit.'),
-      '#type'          => 'select',
-      '#options'       => $templates,
-      '#default_value' => $form_state['storage']['template_id'],
-      '#weight'        => 0,
-      '#required'      => TRUE,
-      '#weight' => 1,
-    );
-  }
-
-  $form['template_array'] = array(
-    '#type' => 'textarea',
-    '#title' => 'Template Array',
-    '#default_value' => $form_state['storage']['template_array'],
-    '#weight' => 2,
-  );
-
-  $form['submit'] = array(
-    '#type' => 'submit',
-    '#value' => 'Submit',
-    '#weight' => 10,
-  );
-
-  return $form;
-}
-
-/**
- * Import/Export Template Form Submit
- *
- * @param $form
- *   The form that was submitted
- * @param $form_state
- *   The values and storage that were submitted
- */
-function tripal_bulk_loader_import_export_template_form_submit($form, &$form_state) {
-  switch ($form_state['values']['mode']) {
-    case 'export':
-      $record = db_fetch_object(db_query("SELECT * FROM {tripal_bulk_loader_template} WHERE template_id=%d", $form_state['values']['template_id']));
-      $form_state['storage']['template_array'] = $record->template_array;
-      $form_state['storage']['template_id'] = $form_state['values']['template_id'];
-    break;
-    case 'import':
-      $record = array(
-        'name' => $form_state['values']['new_template_name'],
-        'template_array' => $form_state['values']['template_array'],
-      );
-      drupal_write_record('tripal_bulk_loader_template', $record);
-      if ($record->template_id) {
-        drupal_set_message('Successfully imported Tripal Bulk Loader Template.');
-      }
-    break;
-  }
-}
-
-//////////////////////////////////////////////////////////////////////////////////////
-// Edit Record Form
-//////////////////////////////////////////////////////////////////////////////////////
-
-/**
- * Edit Record Form
- *
- * This form is meant to be called from a bulk loader form. The following should be set
- * in the query section of the path:
- *  - template_id=\d+: the template which the edited record is part of
- *  - record_id=\d+: the priority or key in the template array of the record to be edited
- *
- * @param $form_state
- *   Contains the values and storage for the form
- * @return
- *   A form array to be rendered by drupal_get_form
- */
-<<<<<<< HEAD
-function tripal_bulk_loader_edit_template_record_form(&$form_state = NULL) {
-   $form['#cache'] = TRUE; // Make sure the form is cached.
-
-   // get template id from path
-   $template_id = ($_GET['template_id'] !== NULL) ? $_GET['template_id'] : $form_state['values']['template_id'];
-
-   // if there is no template supplied don't return rest of form
-   if (!$template_id) {
-     return $form;
-   }
-=======
-function tripal_bulk_loader_edit_template_record_form (&$form_state = NULL) {
- 	$form['#cache'] = TRUE; // Make sure the form is cached.
-
- 	// get template id from path
- 	$template_id = ($_GET['template_id'] !== NULL) ? $_GET['template_id'] : $form_state['values']['template_id'];
-
- 	// if there is no template supplied don't return rest of form
- 	if (!$template_id) {
- 	  return $form;
- 	}
->>>>>>> 6.x-0.4-dev
-
-  // Pre-process values/defaults ---------------------------
-
-   // If this is the first load of the form (no form state) we need to initialize some variables
-   if (!$form_state['storage']['template']) {
-    $sql = "SELECT * FROM {tripal_bulk_loader_template} WHERE template_id=%d";
-    $template = db_fetch_object(db_query($sql, $template_id));
-    $form_state['storage']['template_array'] = unserialize($template->template_array);
-    $form_state['storage']['template'] = $template;
-
-    $form_state['storage']['record2priority'] = array();
-    foreach ($form_state['storage']['template_array'] as $priority => $record_array) {
-      if (!is_array($record_array)) {
-         continue;
-       }
-      $form_state['storage']['record2priority'][$record_array['record_id']] = $priority;
-    }
-
-    $form_state['storage']['referring URL'] = $_SERVER["HTTP_REFERER"];
-  }
-  else {
-    $template = $form_state['storage']['template'];
-  }
-
-   // get the record_id from the path
-   if ($_GET['record_id'] !== NULL) {
-     $form_state['values']['field_group'] = $_GET['record_id'];
-     $form_state['storage']['original_priority'] = $_GET['record_id'];
-  }
-
-
-  // Tables and default table
-  $tables = tripal_core_get_chado_tables();
-  if ($form_state['values']['chado_table']) {
-    $table = $form_state['values']['chado_table'];
-<<<<<<< HEAD
-  }
-  else {
-=======
-  } else {
->>>>>>> 6.x-0.4-dev
-    $table = $form_state['storage']['template_array'][$form_state['storage']['original_priority']]['table'];
-  }
-
-  //dpm($form_state, 'form state');
-
-<<<<<<< HEAD
-   // Form Proper -------------------------------------------
-=======
- 	// Form Proper -------------------------------------------
->>>>>>> 6.x-0.4-dev
-  $form['template_name'] = array(
-    '#type' => 'item',
-    '#title' => 'Template',
-    '#value' => $template->name,
-  );
-
-  $form['template_id'] = array(
-    '#type' => 'hidden',
-    '#value' => $template_id,
-  );
-
-  $form['edit_record'] = array(
-    '#type' => 'fieldset',
-  );
-
-  // check template array for records then add one more
-  if (!$form_state['storage']['record2priority']) {
-    $groups = array();
-  }
-  else {
-    $groups = array_flip($form_state['storage']['record2priority']);
-  }
-  $priority_default = $form_state['values']['field_group'];
-  $form['edit_record']['field_group']  = array(
-    '#type' => 'select',
-    '#title' => 'Record',
-    '#description' => 'By Changing the record here, you can move all the fields from the current record into the selected record.',
-    '#options' => $groups,
-    '#default_value' => $priority_default,
-    '#required' => TRUE,
-  );
-
-  $form['edit_record']['record_name'] = array(
-    '#type' => 'textfield',
-    '#title' => 'Unique Record Name',
-    '#default_value' => $groups[$priority_default],
-  );
-
-  $form['edit_record']['chado_table'] = array(
-    '#type' => 'select',
-    '#title' => t('Chado Table'),
-    '#description' => 'This changes the chado table for all fields in this record.',
-    '#options' => $tables,
-    '#default_value' => $table,
-  );
-
-  $form['edit_record']['mode'] = array(
-    '#type' => 'radios',
-    '#title' => 'Action to take when Loading Record',
-    '#options' => array(
-      'select' => 'SELECT: Don\'t insert this record: it\'s used to define a foreign key in another record',
-      'insert' => 'INSERT: Insert the record',
-      'optional' => 'OPTIONAL: Record will only be inserted if all required data is filled in',
-      'insert_once' => 'INSERT ONCE: Record will be inserted once for the entire spreadsheet',
-      'insert_unique' => 'INSERT UNIQUE: Only insert record if there isn\'t a record with the same values',
-    ),
-    '#default_value' => 'insert_unique'
-  );
-
-  $form['edit_record']['submit-edit_record'] = array(
-      '#type' => 'submit',
-      '#value' => 'Edit Record'
-  );
-
-  $form['edit_record']['submit-cancel'] = array(
-      '#type' => 'submit',
-      '#value' => 'Cancel'
-  );
-
-  return $form;
-}
-
-
-/**
- * Edit Record Form Submit
- *
- * @param $form
- *   The form that was submitted
- * @param $form_state
- *   Contains the values and storage for the form
- */
-function tripal_bulk_loader_edit_template_record_form_submit($form, &$form_state) {
-  //dpm($form_state, 'form state -start submit');
-
-  if (!$form_state['ahah_submission']) {
-    if ($form_state['values']['op'] ==  'Edit Record') {
-
-      $template = $form_state['storage']['template_array'];
-
-      // Edit Record
-      $record = $template[ $form_state['storage']['original_priority'] ];
-      $record['record_id'] = $form_state['values']['record_name'];
-      $record['mode'] = $form_state['values']['mode'];
-      $record['table'] = $form_state['values']['chado_table'];
-
-      if ($form_state['storage']['original_priority'] != $form_state['values']['field_group']) {
-        $record['fields'] = array_merge($record['fields'], $template[ $form_state['values']['field_group'] ]['fields']);
-        $template[ $form_state['values']['field_group'] ] = $record;
-        unset($template[ $form_state['storage']['original_priority'] ]);
-      }
-      else {
-        $template[ $form_state['storage']['original_priority'] ] = $record;
-      }
-
-      // Save Template
-      $form_state['storage']['template']->template_array = serialize($template);
-      $success = drupal_write_record('tripal_bulk_loader_template', $form_state['storage']['template'], array('template_id'));
-
-      if ($success) {
-        drupal_set_message('Successfully Updated Template Record');
-        drupal_set_message('Template Saved.');
-
-<<<<<<< HEAD
-        $path = explode('?', $form_state['storage']['referring URL']);
-=======
-        $path = explode('?',$form_state['storage']['referring URL']);
->>>>>>> 6.x-0.4-dev
-        parse_str($path[1], $query);
-        $query['template_id'] = $form_state['storage']['template']->template_id;
-        drupal_goto($path[0], $query);
-      }
-      else {
-        drupal_set_message('Unable to Save Template!', 'error');
-        watchdog('T_bulk_loader',
-          'Unable to save bulk loader template: %template',
-          array('%template' => print_r($form_state['storage']['template'], TRUE)),
-          WATCHDOG_ERROR
-        );
-      }
-    }
-    elseif ($form_state['values']['op'] ==  'Cancel') {
-        $path = explode('?', $form_state['storage']['referring URL']);
-        parse_str($path[1], $query);
-        $query['template_id'] = $form_state['storage']['template']->template_id;
-        //dpm('Redirecting to: '.$path[0].'?'.print_r($query,TRUE).' where the referring URL:'.$form_state['storage']['referring URL']);
-        drupal_goto($path[0], $query);
-    }
-  }
-
-}
-
-//////////////////////////////////////////////////////////////////////////////////////
-// Add/Edit Field Forms
-//////////////////////////////////////////////////////////////////////////////////////
-
-/**
- * Add Field Form
- *
- * This form is meant to be called from a bulk loader form. Blank Defaults are in place but you
- * can use the following in the query of the path to set defaults for a given template:
- *  - template_id=\d+: the template to add the field to
- *  - record_id=\d+: the priority or key in the template array of the record to add the field to
- *
- * @param $form_state
- *   Contains the values and storage for the form
- * @return
- *   A form array to be rendered by drupal_get_form
- */
-function tripal_bulk_loader_add_template_field_form(&$form_state = NULL) {
-  $form = array();
-<<<<<<< HEAD
-   $form['#cache'] = TRUE; // Make sure the form is cached.
-
-   // get template id from path
-   $template_id = ($_GET['template_id']) ? $_GET['template_id'] : $form_state['values']['template_id'];
-
-   // if there is no template supplied don't return rest of form
-   if (!$template_id) {
-     return $form;
-   }
-=======
- 	$form['#cache'] = TRUE; // Make sure the form is cached.
-
- 	// get template id from path
- 	$template_id = ($_GET['template_id']) ? $_GET['template_id'] : $form_state['values']['template_id'];
-
- 	// if there is no template supplied don't return rest of form
- 	if (!$template_id) {
- 	  return $form;
- 	}
->>>>>>> 6.x-0.4-dev
-
-  // Pre-set Variables needed for form proper------------------------------------------
-
-   // If this is the first load of the form (no form state) we need to initialize some variables
-   if (!$form_state['storage']['template']) {
-    $sql = "SELECT * FROM {tripal_bulk_loader_template} WHERE template_id=%d";
-    $template = db_fetch_object(db_query($sql, $template_id));
-    $form_state['storage']['template_array'] = unserialize($template->template_array);
-    $form_state['storage']['template'] = $template;
-
-    $form_state['storage']['record2priority'] = array();
-    foreach ($form_state['storage']['template_array'] as $priority => $record_array) {
-      if (!is_array($record_array)) {
-        continue;
-      }
-      $form_state['storage']['record2priority'][$record_array['record_id']] = $priority;
-    }
-
-    $form_state['storage']['referring URL'] = $_SERVER["HTTP_REFERER"];
-  }
-  else {
-    $template = $form_state['storage']['template'];
-  }
-
-  $field_type = ($form_state['values']['field_type'])? $form_state['values']['field_type'] : 'table field';
-
-  // Tables and default table
-  $tables = tripal_core_get_chado_tables();
-  if ($form_state['values']) {
-    if (!preg_match('/^' . current($tables) . '$/', $form_state['values']['chado_table'])) {
-      $table = $form_state['values']['chado_table'];
-    }
-    elseif ($form_state['values']['record_name']) {
-      $record_name = $form_state['values']['record_name'];
-      $priority = $form_state['storage']['record2priority'][$record_name];
-      $table = $form_state['storage']['template_array'][$priority]['table'];
-    }
-    else {
-      $priority = $form_state['values']['field_group'];
-      $table = $form_state['storage']['template_array'][$priority]['table'];
-    }
-  }
-  if (!$table) {
-    $table = reset($tables);
-  }
-
-   // get the record_id from the path
-   if ($_GET['record_id'] !== NULL) {
-     $form_state['values']['field_group'] = $_GET['record_id'];
-    if (preg_match('/\d+/', $_GET['record_id'])) {
-      $priority = $form_state['values']['field_group'];
-      $table = $form_state['storage']['template_array'][$priority]['table'];
-    }
-  }
-
-  // Fields and foreign key mappings
-  $chado_fields = array();
-  $fk_options = array();
-  $fk_options['NULL'] = 'None';
-  $table_description = module_invoke_all('chado_' . $table . '_schema');
-  //dpm($table_description, 'table description for |'.$table.'|');
-  if ($field_type == 'foreign key') {
-    $foreign_field2table = array();
-    foreach ($table_description['foreign keys'] as $key_table => $key_array) {
-      foreach ($key_array['columns'] as $left_field => $right_field) {
-        $chado_fields[$left_field] = $left_field;
-        $foreign_field2table[$left_field] = $key_table;
-      }
-    }
-    reset($chado_fields);
-
-    // set default field
-    if (empty($chado_fields)) {
-      $field = NULL;
-    }
-    elseif ($chado_fields[$form_state['values']['chado_field']]) {
-      $field = $form_state['values']['chado_field'];
-    }
-    else {
-      $field = current($chado_fields);
-    }
-
-    // Foreign key options
-    $foreign_table = $foreign_field2table[$field];
-    if ($foreign_table) {
-      foreach ($form_state['storage']['record2priority'] as $record_name => $priority ) {
-        if (preg_match('/^' . $foreign_table . '$/', $form_state['storage']['template_array'][$priority]['table'])) {
-          $fk_options[$record_name] = $record_name;
-        }
-      }
-    }
-  }
-  else {
-    foreach ($table_description['fields'] as $field_name => $field_array) {
-        $chado_fields[$field_name] = $field_name;
-    }
-  }
-
-  $variables = array(
-    'form_state' => $form_state,
-    'tables' => $tables,
-    'default table' => $table,
-    'fields' => $chado_fields,
-    'default_field' => $field,
-    'priority' => $priority,
-    'record_name' => $record_name,
-    'table description' => $table_description,
-    'foreign key options' => $fk_options,
-    'foreign field=>table' => $foreign_field2table,
-    'foreign table' => $foreign_table,
-  );
-  //dpm($variables, 'variables');
-
-  // Start of Form Proper--------------------------------------------------------------
-  //dpm($form_state, 'Form State');
-
-  $form['template_name'] = array(
-    '#type' => 'item',
-    '#title' => 'Template',
-    '#value' => $template->name,
-  );
-
-  $form['template_id'] = array(
-    '#type' => 'hidden',
-    '#value' => $template_id,
-  );
-
-  $form['add_fields'] = array(
-    '#type' => 'fieldset',
-    '#prefix' => '<div id="tripal_bulk_loader_template-add_field">',
-    '#suffix' => '</div>',
-  );
-
-  $form['add_fields']['field_type'] = array(
-    '#type' => 'radios',
-    '#title' => t('Type of Field'),
-    '#options' => array(
-      'table field' => t('Spreadsheet: Fields which maps to a Spreadsheet Column'),
-      'constant' => t('Constant: Field which remains Constant throughout the Spreadsheet'),
-      'foreign key' => t('Foreign Key: Fields which map to a record in another table'),
-    ),
-    '#required' => TRUE,
-    '#default_value' => $field_type,
-    '#ahah' => array(
-      'path' => 'admin/tripal/tripal_bulk_loader_template/add_field_ahah',
-      'wrapper' => 'tripal_bulk_loader_template-add_field',
-      'effect' => 'fade'
-    ),
-  );
-
-  // check template array for records then add one more
-  if (!$form_state['storage']['record2priority']) {
-    $groups = array();
-  }
-  else {
-    $groups = array_flip($form_state['storage']['record2priority']);
-  }
-  $groups['NONE'] = 'Select a Record';
-  $groups['NEW'] = 'New Record';
-  $form['add_fields']['field_group']  = array(
-    '#type' => 'select',
-    '#title' => 'Record',
-    '#description' => 'This is used to group a set of fields together allowing '
-      .'multiple records to be inserted into the same table per line of the spreadsheet',
-    '#options' => $groups,
-    '#default_value' => (preg_match('/\w+.*/', $form_state['values']['field_group'])) ? $form_state['values']['field_group'] : 'NONE',
-    '#ahah' => array(
-      'path' => 'admin/tripal/tripal_bulk_loader_template/add_field_ahah',
-      'wrapper' => 'tripal_bulk_loader_template-add_field',
-      'effect' => 'fade'
-    ),
-    '#required' => TRUE,
-  );
-
-  $form['add_fields']['record_name'] = array(
-    '#type' => (preg_match('/NEW/', $form_state['values']['field_group'])) ? 'textfield' : 'hidden',
-    '#title' => 'Unique Record Name',
-    '#prefix' => '<div id="tripal_bulk_loader_template-add_record">',
-    '#suffix' => '</div>',
-    '#default_value' => $form_state['values']['record_name'],
-  );
-
-  $form['add_fields']['field_title'] = array(
-    '#type' => 'textfield',
-    '#title' => t('Human-readable Title for Field'),
-    '#default_value' => $form_state['values']['field_title'],
-  );
-
-  // Spreadsheet column
-  $form['add_fields']['columns'] = array(
-    '#type' => 'fieldset',
-    '#title' => t('Spreadsheet Column'),
-    '#collapsible' => TRUE,
-    '#collapsed' => ($field_type == 'table field')? FALSE : TRUE,
-  );
-
-  $form['add_fields']['columns']['sheet_name'] = array(
-    '#type' => 'textfield',
-    '#title' => t('Worksheet'),
-    '#description' => t('Specify the name of the worksheet.'),
-    '#size' => 5,
-    '#default_value' => ($form_state['values']['sheet_name'])? $form_state['values']['sheet_name'] : 'Sheet1',
-  );
-
-  $form['add_fields']['columns']['column_number'] = array(
-    '#type' => 'textfield',
-    '#title' => t('Column'),
-    '#description' => t('Specify the column in the spreadsheet that this field maps to where the first column is 1.'),
-    '#size' => 5,
-    '#default_value' => $form_state['values']['column_number'],
-  );
-
-  $form['add_fields']['columns']['column_exposed'] = array(
-    '#type' => 'checkbox',
-    '#title' => t('Allow Column to be set for each Bulk Loading Job'),
-    '#description' => t('Adds a textbox field to the Bulk Loader Page to allow users to set this value.'),
-    '#default_value' => ($form_state['values']['column_exposed']) ? $form_state['values']['column_exposed'] : $template_field['exposed'],
-  );
-
-  $form['add_fields']['columns']['column_exposed_desc'] = array(
-    '#type' => 'textfield',
-    '#title' => t('Description for exposed field on bulk loading job'),
-    '#description' => t('This description should tell the user what column should be entered here.'),
-    '#default_value' => ($form_state['values']['column_exposed_desc']) ? $form_state['values']['column_exposed_desc'] : $template_field['exposed_description'],
-  );
-
-  // Global Value
-  $form['add_fields']['constant'] = array(
-    '#type' => 'fieldset',
-    '#title' => t('Constant'),
-    '#collapsible' => TRUE,
-    '#collapsed' => ($field_type == 'constant')? FALSE : TRUE,
-  );
-
-  $form['add_fields']['constant']['constant_value'] = array(
-    '#type' => 'textfield',
-    '#title' => t('Constant Value'),
-    '#description' => t('Specify the value you wish this field to have regardless of spreadsheet data.'),
-    '#default_value' => $form_state['values']['constant_value']
-  );
-
-  $form['add_fields']['constant']['constant_exposed'] = array(
-    '#type' => 'checkbox',
-    '#title' => t('Allow Constant to be set for each Bulk Loading Job'),
-    '#description' => t('Adds a textbox field to the Create Bulk Loader Form to allow users to set this value.')
-  );
-
-  $form['add_fields']['constant']['constant_validate'] = array(
-    '#type' => 'checkbox',
-    '#title' => t('Ensure value is in table'),
-    '#description' => t('Checks the database when a bulk loading job is created to ensure the value entered already exists in the database.'),
-  );
-
-  // Foreign Key
-  $form['add_fields']['foreign_key'] = array(
-    '#type' => 'fieldset',
-    '#title' => 'Foreign Key',
-    '#collapsible' => TRUE,
-    '#collapsed' => ($field_type == 'foreign key')? FALSE : TRUE,
-  );
-
-  $form['add_fields']['foreign_key']['foreign_record'] = array(
-    '#type' => 'select',
-    '#title' => 'Record to refer to',
-    '#descripion' => 'Select the record that this foreign key shouold refer to. The record needs to already exist and be of the correct table.',
-    '#options' => $fk_options,
-  );
-
-  // Chado Field
-  $form['add_fields']['chado'] = array(
-    '#type' => 'fieldset',
-    '#title' => t('Chado Field/Column Details'),
-    '#description' => t('Specify the Table/Field in chado that this field maps to.'),
-  );
-
-  $form['add_fields']['chado']['chado_table'] = array(
-    '#type' => 'select',
-    '#title' => t('Chado Table'),
-    '#options' => $tables,
-    '#default_value' => $table,
-    '#ahah' => array(
-      'path' => 'admin/tripal/tripal_bulk_loader_template/add_field_ahah',
-      'wrapper' => 'tripal_bulk_loader_template-add_field',
-      'effect' => 'fade'
-      ),
-  );
-
-  $form['add_fields']['chado']['chado_field'] = array(
-    '#type' => 'select',
-    '#title' => t('Chado Field/Column'),
-    '#options' => $chado_fields,
-    '#default_value' => $form_state['values']['chado_field'],
-    '#ahah' => array(
-      'path' => 'admin/tripal/tripal_bulk_loader_template/add_field_ahah',
-      'wrapper' => 'tripal_bulk_loader_template-add_field',
-      'effect' => 'fade'
-    ),
-  );
-
-  $form['add_fields']['additional'] = array(
-    '#type' => 'fieldset',
-    '#title' => 'Additional Options',
-  );
-
-  $form['add_fields']['additional']['required'] = array(
-    '#type' => 'checkbox',
-    '#title' => 'Make this file required',
-  );
-
-  $form['add_fields']['additional']['regex_transform'] = array(
-    '#type' => 'fieldset',
-    '#title' => 'Transform Spreadsheet Value Rules',
-    '#collapsible' => TRUE,
-    '#collapsed' => (!$form_state['storage']['regex']['pattern']) ? TRUE : FALSE,
-  );
-
-  $form['add_fields']['additional']['regex_transform']['regex_description'] = array(
-    '#type' => 'item',
-    '#value' => 'A transformation rule allows you to transform the original value '
-      .'(usually from a user submitted spreadsheet) into the form you would like it stored '
-      .'in the chado database. Each rule consists of a match pattern (a php regular expression '
-      .'which determines which replacement patterns are applied and captures regions of the '
-      .'original value) and a replacement pattern (a string which may contain capture references '
-      .'that describes what the new value should be). Each rule is applied to the result of the '
-      .'previous rule.'
-  );
-
-  $form['add_fields']['additional']['regex_transform']['regex-data'] = array(
-    '#tree' => TRUE,
-  );
-  if (!$form_state['storage']['regex']['pattern']) {
-    $form_state['storage']['regex']['pattern'] = array();
-  }
-  foreach ($form_state['storage']['regex']['pattern'] as $index => $pattern) {
-    $data_element = array(
-      'pattern' => array(
-        '#type' => 'item',
-        '#value' => $pattern,
-      ),
-      'replace' => array(
-        '#type' => 'item',
-        '#value' => $form_state['storage']['regex']['replace'][$index],
-      ),
-      'old_index' => array(
-        '#type' => 'hidden',
-        '#value' => $index,
-      ),
-      'new_index' => array(
-        '#type' => 'select',
-        '#options' => range(0, sizeof($form_state['storage']['regex']['pattern'])-1),
-        '#default_value' => $index,
-      ),
-      'id' => array(
-        '#type' => 'hidden',
-        '#value' => $index,
-      ),
-      'submit-delete' => array(
-        '#type' => 'submit',
-        '#value' => 'Delete Transformation',
-        '#name' => $index,
-      ),
-    );
-    $form['add_fields']['additional']['regex_transform']['regex-data'][$index] = $data_element;
-  }
-
-  $form['add_fields']['additional']['regex_transform']['submit-reorder_regex'] = array(
-    '#type' => ($form_state['storage']['regex']['pattern']) ? 'submit' : 'hidden',
-    '#value' => 'Save Transformation Rule Order'
-  );
-
-  $form['add_fields']['additional']['regex_transform']['new_regex'] = array(
-    '#type' => 'fieldset',
-    '#title' => 'Add a new Transformation Rule',
-  );
-
-  $form['add_fields']['additional']['regex_transform']['new_regex']['pattern'] = array(
-    '#type' => 'textfield',
-    '#title' => 'Match Pattern',
-    '#description' => 'You can use standard php regular expressions in this field to specify a '
-      .'pattern. Only if this pattern matches the value in the spreadsheet does the replacement '
-      .'pattern get applied to the value. To capture a section of your value for use in the '
-      .'replacement patten surround with round brackets. For example, <i>GI:(\d+)</i> will match '
-      .' NCBI gi numbers and will capture the numerical digits for use in the replacement pattern. '
-      .' To match and capture any value use <i>.*</i>',
-  );
-
-  $form['add_fields']['additional']['regex_transform']['new_regex']['replace'] = array(
-    '#type' => 'textfield',
-    '#title' => 'Replacement Pattern',
-    '#description' => 'This pattern should contain the text you want to replace the match pattern '
-    .'mentioned above. It can include references of the form \n where n is the number of the '
-    .'capture in the match pattern. For example, \1 will be replaced with the text matched in your '
-    .'first set of round brackets.',
-  );
-
-  if ($field_type == 'table field') {
-    $tab = '&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp';
-    $form['add_fields']['additional']['regex_transform']['new_regex']['replace']['#description'] .= '<p>'
-      .'The following references are also available for spreadsheet fields: <b><#column:<i>number</i>#></b>. '
-      .'This allows you to substitute other spreadsheet values into the current field. For example, '
-      .'if you had the following line:<br>'
-      . $tab . 'SNP' . $tab . '15-Jan-2011' . $tab . '1' . $tab . '54' . $tab . 'Contig34355'
-      .'<br> and your current field is for column #1 and you\'re inserting into the chado field '
-      .'feature.uniquename then you might want to add in the data to ensure your uniquename is '
-      .'unique. The Match Pattern is (.*) to select all the first column and the Replacement '
-      .'Pattern could be \1_<#column:2#> which would insert SNP_15-Jan-2011 into the database.</p>';
-  }
-
-  $form['add_fields']['additional']['regex_transform']['new_regex']['submit-add_transform'] = array(
-    '#type' => 'submit',
-    '#value' => 'Add Transformation',
-  );
-
-  $form['add_fields']['additional']['regex_transform']['test_regex'] = array(
-    '#type' => 'fieldset',
-    '#title' => 'Test Transformation Rules',
-  );
-
-  $form['add_fields']['additional']['regex_transform']['test_regex']['test_string'] = array(
-    '#type' => 'textfield',
-    '#title' => 'Test Value',
-    '#description' => 'This should be a value that you expect the above transformation rules '
-      .'to be applied to.',
-    '#default_value' => $form_state['storage']['test_regex_test'],
-  );
-
-  $form['add_fields']['additional']['regex_transform']['test_regex']['test_result'] = array(
-    '#type' => 'textfield',
-    '#title' => 'Test Result',
-    '#description' => 'This is the value that would be saved to the database after the above transformation '
-      .'riles were applied to the Test Value.',
-    '#default_value' => $form_state['storage']['test_regex_result'],
-  );
-
-  $form['add_fields']['additional']['regex_transform']['test_regex']['submit-test'] = array(
-    '#type' => 'submit',
-    '#value' => 'Test Transformation Rules'
-  );
-
-  $form['add_fields']['submit-add_field'] = array(
-      '#type' => 'submit',
-      '#value' => 'Add Field'
-  );
-
-  $form['add_fields']['submit-cancel'] = array(
-      '#type' => 'submit',
-      '#value' => 'Cancel'
-  );
-
-  return $form;
-}
-
-/**
- * Add Field Submit
- *
- * @param $form
- *   The form that was submitted
- * @param $form_state
- *   The values and storage for the form
- */
-<<<<<<< HEAD
-function tripal_bulk_loader_add_template_field_form_submit($form, &$form_state) {
-=======
-function tripal_bulk_loader_add_template_field_form_submit ($form, &$form_state) {
->>>>>>> 6.x-0.4-dev
-
-  $op = $form_state['values'][ $form_state['clicked_button']['#name'] ];
-
-  if (!$form_state['ahah_submission']) {
-    if ($op ==  'Add Field') {
-
-      $template = $form_state['storage']['template_array'];
-
-       // If new record
-      if (preg_match('/NEW/', $form_state['values']['field_group'])) {
-        $record_name = $form_state['values']['record_name'];
-        $priority = sizeof($form_state['storage']['template_array']) + 1;
-        $record2priority[$record_name] = $priority;
-        $template[$priority]['table'] = $form_state['values']['chado_table'];
-        $template[$priority]['record_id'] = $record_name;
-
-<<<<<<< HEAD
-      }
-      else {
-=======
-      } else {
->>>>>>> 6.x-0.4-dev
-        $priority = $form_state['values']['field_group'];
-        $record_name = $record2priority[$priority];
-      }
-
-      // Add field to template array
-      if ($form_state['values']['field_type'] == 'table field') {
-        $field = array(
-          'type' => 'table field',
-          'title' => $form_state['values']['field_title'],
-          'field' => $form_state['values']['chado_field'],
-          'required' => $form_state['values']['required'],
-          //'allowed values' => empty by default,
-          'spreadsheet sheet' => $form_state['values']['sheet_name'],
-          'spreadsheet column' => $form_state['values']['column_number'],
-          'exposed' => $form_state['values']['column_exposed'],
-          'exposed_description' => $form_state['values']['column_exposed_desc'],
-        );
-      }
-      elseif ($form_state['values']['field_type'] == 'constant') {
-        $field = array(
-          'type' => 'constant',
-          'title' => $form_state['values']['field_title'],
-          'field' => $form_state['values']['chado_field'],
-          'required' => $form_state['values']['required'],
-          //'allowed values' => empty by default,
-          'constant value' => $form_state['values']['constant_value'],
-          'exposed' => $form_state['values']['constant_exposed'],
-          'exposed_validate' => $form_state['values']['constant_validate'],
-        );
-<<<<<<< HEAD
-      }
-      elseif ($form_state['values']['field_type'] == 'foreign key') {
-=======
-      } elseif ($form_state['values']['field_type'] == 'foreign key') {
->>>>>>> 6.x-0.4-dev
-        $field = array(
-          'type' => 'foreign key',
-          'title' => $form_state['values']['field_title'],
-          'field' => $form_state['values']['chado_field'],
-          'foreign key' => $form_state['values']['foreign_record'],
-          'required' => $form_state['values']['required'],
-        );
-      }
-
-      // Deal with any additional options
-      if ($form_state['storage']['regex']) {
-        $field['regex'] = $form_state['storage']['regex'];
-      }
-
-      // Save Template
-      $template[$priority]['fields'][] = $field;
-      $form_state['storage']['template']->template_array = serialize($template);
-      $success = drupal_write_record('tripal_bulk_loader_template', $form_state['storage']['template'], array('template_id'));
-
-      if ($success) {
-        drupal_set_message('Successfully Added Field to Template');
-        drupal_set_message('Template Saved.');
-
-<<<<<<< HEAD
-        $path = explode('?', $form_state['storage']['referring URL']);
-=======
-        $path = explode('?',$form_state['storage']['referring URL']);
->>>>>>> 6.x-0.4-dev
-        parse_str($path[1], $query);
-        $query['template_id'] = $form_state['storage']['template']->template_id;
-        drupal_goto($path[0], $query);
-      }
-      else {
-        drupal_set_message('Unable to Save Template!', 'error');
-        watchdog('T_bulk_loader',
-          'Unable to save bulk loader template: %template',
-          array('%template' => print_r($form_state['storage']['template'], TRUE)),
-          WATCHDOG_ERROR
-        );
-      }
-    }
-    elseif ($op ==  'Cancel') {
-        $path = explode('?', $form_state['storage']['referring URL']);
-        parse_str($path[1], $query);
-        $query['template_id'] = $form_state['storage']['template']->template_id;
-        drupal_goto($path[0], $query);
-<<<<<<< HEAD
-    }
-    elseif ($op == 'Add Transformation') {
-=======
-    } elseif ($op == 'Add Transformation') {
->>>>>>> 6.x-0.4-dev
-
-      // Add transformation rule to original field
-      $form_state['storage']['regex']['pattern'][] = '/' . $form_state['values']['pattern'] . '/';
-      $form_state['storage']['regex']['replace'][] = $form_state['values']['replace'];
-      drupal_set_message('Successfully Added Transformation Rule');
-
-<<<<<<< HEAD
-    }
-    elseif ($op == 'Save Transformation Rule Order') {
-=======
-    } elseif ($op == 'Save Transformation Rule Order') {
->>>>>>> 6.x-0.4-dev
-
-      // Generate new regex array
-      $new_regex = array();
-      $old_regex = $form_state['storage']['regex'];
-      foreach ($form_state['values']['regex-data'] as $key => $element) {
-        $new_regex['pattern'][ $element['new_index'] ] = $old_regex['pattern'][ $element['old_index'] ];
-        $new_regex['replace'][ $element['new_index'] ] = $old_regex['replace'][ $element['old_index'] ];
-      }
-
-      // sort new regex arrays
-      asort($new_regex['pattern']);
-      asort($new_regex['replace']);
-
-      $form_state['storage']['regex'] = $new_regex;
-<<<<<<< HEAD
-    }
-    elseif ($op == 'Delete Transformation') {
-=======
-    } elseif ($op == 'Delete Transformation') {
->>>>>>> 6.x-0.4-dev
-
-      // Unset regex rule
-      $index = $form_state['clicked_button']['#name'];
-      unset($form_state['storage']['regex']['pattern'][$index]);
-      unset($form_state['storage']['regex']['replace'][$index]);
-
-<<<<<<< HEAD
-    }
-    elseif ($op == 'Test Transformation Rules') {
-=======
-    } elseif ($op == 'Test Transformation Rules') {
->>>>>>> 6.x-0.4-dev
-
-      $patterns = $form_state['storage']['regex']['pattern'];
-      $replaces = $form_state['storage']['regex']['replace'];
-      $test_string = $form_state['values']['test_string'];
-      $form_state['storage']['test_regex_result'] = preg_replace($patterns, $replaces, $test_string);
-      $form_state['storage']['test_regex_test'] = $test_string;
-    }
-  }
-
-}
-
-/**
- * Edit Field Form
- *
- * This form is meant to be called from a bulk loader form. The following should be set
- * in the query section of the path:
- *  - template_id=\d+: the template which the edited field is part of
- *  - record_id=\d+: the priority or key in the template array of the record the field
- *      is currently part of
- *  - field_index=\d+: the key of the field in the fields array of the previously
- *      specified record
- *
- * @param $form_state
- *   Contains the values and storage for the form
- * @return
- *   A form array to be rendered by drupal_get_form
- */
-function tripal_bulk_loader_edit_template_field_form(&$form_state = NULL) {
-  $form = array();
-<<<<<<< HEAD
-   $form['#cache'] = TRUE; // Make sure the form is cached.
-
-   // get template id from path
-   $template_id = ($_GET['template_id']) ? $_GET['template_id'] : $form_state['values']['template_id'];
-
-   // if there is no template supplied don't return rest of form
-   if (!$template_id) {
-     return $form;
-   }
-=======
- 	$form['#cache'] = TRUE; // Make sure the form is cached.
-
- 	// get template id from path
- 	$template_id = ($_GET['template_id']) ? $_GET['template_id'] : $form_state['values']['template_id'];
-
- 	// if there is no template supplied don't return rest of form
- 	if (!$template_id) {
- 	  return $form;
- 	}
->>>>>>> 6.x-0.4-dev
-
-  // Pre-set Variables needed for form proper------------------------------------------
-
-   // If this is the first load of the form (no form state) we need to initialize some variables
-   if (!$form_state['storage']['template']) {
-    $sql = "SELECT * FROM {tripal_bulk_loader_template} WHERE template_id=%d";
-    $template = db_fetch_object(db_query($sql, $template_id));
-    $form_state['storage']['template_array'] = unserialize($template->template_array);
-    $form_state['storage']['template'] = $template;
-
-    $form_state['storage']['record2priority'] = array();
-    foreach ($form_state['storage']['template_array'] as $priority => $record_array) {
-      if (!is_array($record_array)) {
-         continue;
-       }
-      $form_state['storage']['record2priority'][$record_array['record_id']] = $priority;
-    }
-
-    $form_state['storage']['referring URL'] = $_SERVER["HTTP_REFERER"];
-  }
-  else {
-    $template = $form_state['storage']['template'];
-  }
-
-  // get the field from the path
-  if (!($_GET['record_id']===NULL || $_GET['field_index']===NULL)) {
-    $priority = $_GET['record_id'];
-    $field_index = $_GET['field_index'];
-    $template_field = $form_state['storage']['template_array'][$priority]['fields'][$field_index];
-    $form_state['storage']['original_field'] = $template_field;
-    $form_state['storage']['original_field']['priority'] = $priority;
-    $form_state['storage']['original_field']['field_index'] = $field_index;
-  }
-
-  $field_type = ($form_state['values']['field_type'])? $form_state['values']['field_type'] : $template_field['type'];
-
-  // Tables and default table
-  $tables = tripal_core_get_chado_tables();
-  if ($form_state['values']) {
-    $table = $form_state['values']['chado_table'];
-<<<<<<< HEAD
-  }
-  else {
-    $table = $form_state['storage']['template_array'][$priority]['table'];
-  }
-=======
-  } else {
-    $table = $form_state['storage']['template_array'][$priority]['table'];
-  }
->>>>>>> 6.x-0.4-dev
-
-
-  // Fields and foreign key mappings
-  $chado_fields = array();
-  $fk_options = array();
-  $fk_options['NULL'] = 'None';
-  $table_description = module_invoke_all('chado_' . $table . '_schema');
-  if ($field_type == 'foreign key') {
-    $foreign_field2table = array();
-    foreach ($table_description['foreign keys'] as $key_table => $key_array) {
-      foreach ($key_array['columns'] as $left_field => $right_field) {
-        $chado_fields[$left_field] = $left_field;
-        $foreign_field2table[$left_field] = $key_table;
-      }
-    }
-    reset($chado_fields);
-
-    // set default field
-    if (empty($chado_fields)) {
-      $field = NULL;
-    }
-    elseif ($chado_fields[$form_state['values']['chado_field']]) {
-      $field = $form_state['values']['chado_field'];
-    }
-    elseif ($template_field['field']) {
-      $field = $template_field['field'];
-    }
-    else {
-      $field = current($chado_fields);
-    }
-    //dpm($field, 'field');
-
-    // Foreign key options
-    $foreign_table = $foreign_field2table[$field];
-    if ($foreign_table) {
-      foreach ($form_state['storage']['record2priority'] as $record_name_ => $priority_ ) {
-        if (preg_match('/^' . $foreign_table . '$/', $form_state['storage']['template_array'][$priority_]['table'])) {
-          $fk_options[$record_name_] = $record_name_;
-        }
-      }
-    }
-  }
-  else {
-    foreach ($table_description['fields'] as $field_name => $field_array) {
-        $chado_fields[$field_name] = $field_name;
-    }
-  }
-
-//  dpm(array( 'tables' => $tables, 'default table' => $table, 'record name' => $record_name, 'priority' => $priority,
-//    'fields' => $chad_fields, 'default field' => $field, 'foreign field=>table' => $foreign_field2table,
-//    'table desc' => $table_description, 'foreign record options' => $fk_options, 'foreign table' => $foreign_table
-//    ), 'Variables');
-
-  // Start of Form Proper--------------------------------------------------------------
-
-  $form['template_name'] = array(
-    '#type' => 'item',
-    '#title' => 'Template',
-    '#value' => $template->name,
-  );
-
-  $form['template_id'] = array(
-    '#type' => 'hidden',
-    '#value' => $template_id,
-  );
-
-  $form['edit_fields'] = array(
-    '#type' => 'fieldset',
-    '#prefix' => '<div id="tripal_bulk_loader_template-edit_field">',
-    '#suffix' => '</div>',
-  );
-
-  $form['edit_fields']['field_type'] = array(
-    '#type' => 'radios',
-    '#title' => t('Type of Field'),
-    '#options' => array(
-      'table field' => t('Spreadsheet: Fields which maps to a Spreadsheet Column'),
-      'constant' => t('Constant: Field which remains Constant throughout the Spreadsheet'),
-      'foreign key' => t('Foreign Key: Fields which map to a record in another table'),
-    ),
-    '#required' => TRUE,
-    '#default_value' => $field_type,
-    '#ahah' => array(
-      'path' => 'admin/tripal/tripal_bulk_loader_template/edit_field_ahah',
-      'wrapper' => 'tripal_bulk_loader_template-edit_field',
-      'effect' => 'fade'
-    ),
-  );
-
-  // check template array for records then edit one more
-  if (!$form_state['storage']['record2priority']) {
-    $groups = array();
-  }
-  else {
-    $groups = array_flip($form_state['storage']['record2priority']);
-  }
-  $groups['NONE'] = 'Select a Record';
-  $groups['NEW'] = 'New Record';
-  $form['edit_fields']['field_group']  = array(
-    '#type' => 'select',
-    '#title' => 'Record',
-    '#description' => 'This is used to group a set of fields together allowing '
-      .'multiple records to be inserted into the same table per line of the spreadsheet',
-    '#options' => $groups,
-    '#default_value' => (preg_match('/(\d+|\w+)/', $form_state['values']['field_group'])) ? $form_state['values']['field_group'] : $priority,
-    '#ahah' => array(
-      'path' => 'admin/tripal/tripal_bulk_loader_template/edit_field_ahah',
-      'wrapper' => 'tripal_bulk_loader_template-edit_field',
-      'effect' => 'fade'
-    ),
-    '#required' => TRUE,
-  );
-
-  $form['edit_fields']['record_name'] = array(
-    '#type' => (preg_match('/NEW/', $form_state['values']['field_group'])) ? 'textfield' : 'hidden',
-    '#title' => 'Unique Record Name',
-    '#prefix' => '<div id="tripal_bulk_loader_template-edit_record">',
-    '#suffix' => '</div>',
-    '#default_value' => $form_state['values']['record_name'],
-  );
-
-  $form['edit_fields']['field_title'] = array(
-    '#type' => 'textfield',
-    '#title' => t('Human-readable Title for Field'),
-    '#default_value' => ($form_state['values']['field_title']) ? $form_state['values']['field_title'] : $template_field['title'],
-  );
-
-  // Spreadsheet column
-  $form['edit_fields']['columns'] = array(
-    '#type' => 'fieldset',
-    '#title' => t('Spreadsheet Column'),
-    '#collapsible' => TRUE,
-    '#collapsed' => ($field_type == 'table field')? FALSE : TRUE,
-  );
-
-  $form['edit_fields']['columns']['sheet_name'] = array(
-    '#type' => 'textfield',
-    '#title' => t('Worksheet'),
-    '#description' => t('Specify the name of the worksheet.'),
-    '#size' => 5,
-    '#default_value' => ($form_state['values']['sheet_name'])? $form_state['values']['sheet_name'] : $template_field['spreadsheet sheet'],
-  );
-
-  $form['edit_fields']['columns']['column_number'] = array(
-    '#type' => 'textfield',
-    '#title' => t('Column'),
-    '#description' => t('Specify the column in the spreadsheet that this field maps to where the first column is 1.'),
-    '#size' => 5,
-    '#default_value' => ($form_state['values']['column_number']) ? $form_state['values']['column_number'] : $template_field['spreadsheet column'],
-  );
-
-  $form['edit_fields']['columns']['column_exposed'] = array(
-    '#type' => 'checkbox',
-    '#title' => t('Allow Column to be set for each Bulk Loading Job'),
-    '#description' => t('Adds a textbox field to the Bulk Loader Page to allow users to set this value.'),
-    '#default_value' => ($form_state['values']['column_exposed']) ? $form_state['values']['column_exposed'] : $template_field['exposed'],
-  );
-
-  $form['edit_fields']['columns']['column_exposed_desc'] = array(
-    '#type' => 'textfield',
-    '#title' => t('Description for exposed field on bulk loading job'),
-    '#description' => t('This description should tell the user what column should be entered here.'),
-    '#default_value' => ($form_state['values']['column_exposed_desc']) ? $form_state['values']['column_exposed_desc'] : $template_field['exposed_description'],
-  );
-
-  // Global Value
-  $form['edit_fields']['constant'] = array(
-    '#type' => 'fieldset',
-    '#title' => t('Constant'),
-    '#collapsible' => TRUE,
-    '#collapsed' => ($field_type == 'constant')? FALSE : TRUE,
-  );
-
-  $form['edit_fields']['constant']['constant_value'] = array(
-    '#type' => 'textfield',
-    '#title' => t('Constant Value'),
-    '#description' => t('Specify the value you wish this field to have regardless of spreadsheet data.'),
-    '#default_value' => ($form_state['values']['constant_value']) ? $form_state['values']['constant_value'] : $template_field['constant value'],
-  );
-
-  $form['edit_fields']['constant']['constant_exposed'] = array(
-    '#type' => 'checkbox',
-    '#title' => t('Allow Constant to be set for each Bulk Loading Job'),
-    '#description' => t('Adds a textbox field to the Create Bulk Loader Form to allow users to set this value.'),
-    '#default_value' => ($form_state['values']['constant_exposed']) ? $form_state['values']['constant_exposed'] : $template_field['exposed'],
-  );
-
-  $form['edit_fields']['constant']['constant_validate'] = array(
-    '#type' => 'checkbox',
-    '#title' => t('Ensure value is in table'),
-    '#description' => t('Checks the database when a bulk loading job is created to ensure the value entered already exists in the database.'),
-    '#default_value' => ($form_state['values']['constant_validate']) ? $form_state['values']['constant_validate'] : $template_field['exposed_validate'],
-  );
-
-  // Foreign Key
-  $form['edit_fields']['foreign_key'] = array(
-    '#type' => 'fieldset',
-    '#title' => 'Foreign Key',
-    '#collapsible' => TRUE,
-    '#collapsed' => ($field_type == 'foreign key')? FALSE : TRUE,
-  );
-
-  $form['edit_fields']['foreign_key']['foreign_record'] = array(
-    '#type' => 'select',
-    '#title' => 'Record to refer to',
-    '#descripion' => 'Select the record that this foreign key shouold refer to. The record needs to already exist and be of the correct table.',
-    '#options' => $fk_options,
-  );
-
-  // Chado Field
-  $form['edit_fields']['chado'] = array(
-    '#type' => 'fieldset',
-    '#title' => t('Chado Field/Column Details'),
-    '#description' => t('Specify the Table/Field in chado that this field maps to.'),
-  );
-
-  $form['edit_fields']['chado']['chado_table'] = array(
-    '#type' => 'select',
-    '#title' => t('Chado Table'),
-    '#options' => $tables,
-    '#default_value' => $table,
-    '#ahah' => array(
-      'path' => 'admin/tripal/tripal_bulk_loader_template/edit_field_ahah',
-      'wrapper' => 'tripal_bulk_loader_template-edit_field',
-      'effect' => 'fade'
-      ),
-  );
-
-  $form['edit_fields']['chado']['chado_field'] = array(
-    '#type' => 'select',
-    '#title' => t('Chado Field/Column'),
-    '#options' => $chado_fields,
-    '#default_value' => ($form_state['values']['chado_field']) ? $form_state['values']['chado_field'] : $template_field['field'],
-    '#ahah' => array(
-      'path' => 'admin/tripal/tripal_bulk_loader_template/edit_field_ahah',
-      'wrapper' => 'tripal_bulk_loader_template-edit_field',
-      'effect' => 'fade'
-    ),
-  );
-
-  $form['edit_fields']['additional'] = array(
-    '#type' => 'fieldset',
-    '#title' => 'Additional Options',
-  );
-
-  $form['edit_fields']['additional']['required'] = array(
-    '#type' => 'checkbox',
-    '#title' => 'Make this file required',
-    '#default_value' => $template_field['required'],
-  );
-
-  $form['edit_fields']['additional']['regex_transform'] = array(
-    '#type' => 'fieldset',
-    '#title' => 'Transform Spreadsheet Value Rules',
-    '#collapsible' => TRUE,
-    '#collapsed' => (!$template_field['regex']['pattern']) ? TRUE : FALSE,
-  );
-
-  $transformation_msg = '<p>A transformation rule allows you to transform the original value '
-      .'(usually from a user submitted spreadsheet) into the form you would like it stored '
-      .'in the chado database. Each rule consists of a match pattern (a php regular expression '
-      .'which determines which replacement patterns are applied and captures regions of the '
-      .'original value) and a replacement pattern (a string which may contain capture references '
-      .'that describes what the new value should be). Each rule is applied to the result of the '
-      .'previous rule.<p>';
-  $form['edit_fields']['additional']['regex_transform']['regex_description'] = array(
-    '#type' => 'item',
-    '#value' => $transformation_msg,
-  );
-
-  $form['edit_fields']['additional']['regex_transform']['regex-data'] = array(
-    '#tree' => TRUE,
-  );
-  foreach ($template_field['regex']['pattern'] as $index => $pattern) {
-    $data_element = array(
-      'pattern' => array(
-        '#type' => 'item',
-        '#value' => $pattern,
-      ),
-      'replace' => array(
-        '#type' => 'item',
-        '#value' => $template_field['regex']['replace'][$index],
-      ),
-      'old_index' => array(
-        '#type' => 'hidden',
-        '#value' => $index,
-      ),
-      'new_index' => array(
-        '#type' => 'select',
-        '#options' => range(0, sizeof($template_field['regex']['pattern'])-1),
-        '#default_value' => $index,
-      ),
-      'id' => array(
-        '#type' => 'hidden',
-        '#value' => $index,
-      ),
-      'submit-delete' => array(
-        '#type' => 'submit',
-        '#value' => 'Delete Transformation',
-        '#name' => $index,
-      ),
-    );
-    $form['edit_fields']['additional']['regex_transform']['regex-data'][$index] = $data_element;
-  }
-
-  $form['edit_fields']['additional']['regex_transform']['submit-reorder_regex'] = array(
-    '#type' => 'submit',
-    '#value' => 'Save Transformation Rule Order'
-  );
-
-  $form['edit_fields']['additional']['regex_transform']['new_regex'] = array(
-    '#type' => 'fieldset',
-    '#title' => 'Add a new Transformation Rule',
-  );
-
-  $form['edit_fields']['additional']['regex_transform']['new_regex']['pattern'] = array(
-    '#type' => 'textfield',
-    '#title' => 'Match Pattern',
-    '#description' => 'You can use standard <b>php regular expressions</b> in this field to specify a '
-      .'pattern. Only if this pattern matches the value in the spreadsheet does the replacement '
-      .'pattern get applied to the value. To capture a section of your value for use in the '
-      .'replacement patten surround with round brackets. For example, <i>GI:(\d+)</i> will match '
-      .' NCBI gi numbers and will capture the numerical digits for use in the replacement pattern. '
-      .' To match and capture any value use <i>.*</i>',
-  );
-
-  $form['edit_fields']['additional']['regex_transform']['new_regex']['replace'] = array(
-    '#type' => 'textfield',
-    '#title' => 'Replacement Pattern',
-    '#description' => '<p>This pattern should contain the text you want to replace the match pattern '
-    .'mentioned above. It can include references of the form <b>\n</b> where n is the number of the '
-    .'capture in the match pattern. For example, \1 will be replaced with the text matched in your '
-    .'first set of round brackets.</p>',
-  );
-
-  if ($field_type == 'table field') {
-    $tab = '&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp';
-    $form['edit_fields']['additional']['regex_transform']['new_regex']['replace']['#description'] .= '<p>'
-      .'The following references are also available for spreadsheet fields: <b><#column:<i>number</i>#></b>. '
-      .'This allows you to substitute other spreadsheet values into the current field. For example, '
-      .'if you had the following line:<br>'
-      . $tab . 'SNP' . $tab . '15-Jan-2011' . $tab . '1' . $tab . '54' . $tab . 'Contig34355'
-      .'<br> and your current field is for column #1 and you\'re inserting into the chado field '
-      .'feature.uniquename then you might want to add in the data to ensure your uniquename is '
-      .'unique. The Match Pattern is (.*) to select all the first column and the Replacement '
-      .'Pattern could be \1_<#column:2#> which would insert SNP_15-Jan-2011 into the database.</p>';
-  }
-
-  $form['edit_fields']['additional']['regex_transform']['new_regex']['submit-add_transform'] = array(
-    '#type' => 'submit',
-    '#value' => 'Add Transformation',
-  );
-
-  $form['edit_fields']['additional']['regex_transform']['test_regex'] = array(
-    '#type' => 'fieldset',
-    '#title' => 'Test Transformation Rules',
-  );
-
-  $form['edit_fields']['additional']['regex_transform']['test_regex']['test_string'] = array(
-    '#type' => 'textfield',
-    '#title' => 'Test Value',
-    '#description' => 'This should be a value that you expect the above transformation rules '
-      .'to be applied to.',
-    '#default_value' => $form_state['storage']['test_regex_test'],
-  );
-
-  $form['edit_fields']['additional']['regex_transform']['test_regex']['test_result'] = array(
-    '#type' => 'textfield',
-    '#title' => 'Test Result',
-    '#description' => 'This is the value that would be saved to the database after the above transformation '
-      .'riles were applied to the Test Value.',
-    '#default_value' => $form_state['storage']['test_regex_result'],
-  );
-
-  $form['edit_fields']['additional']['regex_transform']['test_regex']['submit-test'] = array(
-    '#type' => 'submit',
-    '#value' => 'Test Transformation Rules'
-  );
-
-  $form['edit_fields']['submit-edit_field'] = array(
-      '#type' => 'submit',
-      '#value' => 'Edit Field'
-  );
-
-  $form['edit_fields']['submit-cancel'] = array(
-      '#type' => 'submit',
-      '#value' => 'Cancel'
-  );
-
-  return $form;
-}
-
-/**
- * Edit Field Form Submit
- *
- * @param $form
- *   The form that was submitted
- * @param $form_state
- *   The values and storage for the form
- */
-function tripal_bulk_loader_edit_template_field_form_submit($form, &$form_state) {
-
-  $op = $form_state['values'][ $form_state['clicked_button']['#name'] ];
-  //dpm($op, 'Operation Submitted');
-
-  //Clear Test
-  $form_state['storage']['test_regex_result'] = NULL;
-  $form_state['storage']['test_regex_test'] = NULL;
-
-  if (!$form_state['ahah_submission']) {
-    if ($op ==  'Edit Field') {
-
-      // If new record
-      if (preg_match('/NEW/', $form_state['values']['field_group'])) {
-        // add new record
-        $record_name = $form_state['values']['record_name'];
-        $priority = sizeof($form_state['storage']['template_array']) + 1;
-        $old_priority = $form_state['storage']['original_field']['priority'];
-        $field_index = $form_state['storage']['original_field']['field_index'];
-        $form_state['storage']['record2priority'][$record_name] = $priority;
-        $form_state['storage']['template_array'][$priority]['table'] = $form_state['values']['chado_table'];
-        $form_state['storage']['template_array'][$priority]['record_id'] = $record_name;
-
-<<<<<<< HEAD
-      }
-      else {
-=======
-      } else {
->>>>>>> 6.x-0.4-dev
-        $priority = $form_state['values']['field_group'];
-        $old_priority = $form_state['storage']['original_field']['priority'];
-        $field_index = $form_state['storage']['original_field']['field_index'];
-        $record_name = $form_state['storage']['record2priority'][$priority];
-      }
-
-      $field = $form_state['storage']['original_field'];
-      if ($form_state['values']['field_type'] == 'table field') {
-          $field['type'] = 'table field';
-          $field['title'] = $form_state['values']['field_title'];
-          $field['field'] = $form_state['values']['chado_field'];
-          $field['required'] = $form_state['values']['required'];
-          //$field['allowed values'] = empty by default;
-          $field['spreadsheet sheet'] = $form_state['values']['sheet_name'];
-          $field['spreadsheet column'] = $form_state['values']['column_number'];
-          $field['exposed'] = $form_state['values']['column_exposed'];
-          $field['exposed_description'] = $form_state['values']['column_exposed_desc'];
-      }
-      elseif ($form_state['values']['field_type'] == 'constant') {
-          $field['type'] = 'constant';
-          $field['title'] = $form_state['values']['field_title'];
-          $field['field'] = $form_state['values']['chado_field'];
-          $field['required'] = $form_state['values']['required'];
-          //$field['allowed values'] = empty by default;
-          $field['constant value'] = $form_state['values']['constant_value'];
-          $field['exposed_validate'] = $form_state['values']['constant_validate'];
-          $field['exposed'] = $form_state['values']['constant_exposed'];
-<<<<<<< HEAD
-      }
-      elseif ($form_state['values']['field_type'] == 'foreign key') {
-=======
-      } elseif ($form_state['values']['field_type'] == 'foreign key') {
->>>>>>> 6.x-0.4-dev
-          $field['type'] = 'foreign key';
-          $field['title'] = $form_state['values']['field_title'];
-          $field['field'] = $form_state['values']['chado_field'];
-          $field['foreign key'] = $form_state['values']['foreign_record'];
-          $field['required'] = $form_state['values']['required'];
-      }
-
-      // Deal with any additional options
-
-      // if the record has changed...
-      $form_state['storage']['template_array'][$priority]['table'] = $form_state['values']['chado_table'];
-      if ($old_priority != $priority) {
-        $form_state['storage']['template_array'][$priority]['fields'][] = $field;
-        unset($form_state['storage']['template_array'][$old_priority]['fields'][$field_index]);
-
-        // if there are no fields left delete the old record
-        if (!$form_state['storage']['template_array'][$old_priority]['fields']) {
-          unset($form_state['storage']['template_array'][$old_priority]);
-        }
-      }
-      else {
-        $form_state['storage']['template_array'][$priority]['fields'][$field_index] = $field;
-      }
-
-      // Save Template
-      $form_state['storage']['template']->template_array = serialize($form_state['storage']['template_array']);
-      $success = drupal_write_record('tripal_bulk_loader_template', $form_state['storage']['template'], array('template_id'));
-
-      if ($success) {
-        drupal_set_message('Successfully Updated Field');
-        drupal_set_message('Template Saved.');
-
-        $path = explode('?', $form_state['storage']['referring URL']);
-        parse_str($path[1], $query);
-        $query['template_id'] = $form_state['storage']['template']->template_id;
-        drupal_goto($path[0], $query);
-<<<<<<< HEAD
-      }
-      else {
-=======
-      } else {
->>>>>>> 6.x-0.4-dev
-        drupal_set_message('Unable to Save Template!', 'error');
-        watchdog('T_bulk_loader',
-          'Unable to save bulk loader template: %template',
-          array('%template' => print_r($form_state['storage']['template'], TRUE)),
-          WATCHDOG_ERROR
-        );
-      }
-
-<<<<<<< HEAD
-    }
-    elseif ($op ==  'Cancel') {
-
-        $path = explode('?', $form_state['storage']['referring URL']);
-=======
-    } elseif ($op ==  'Cancel') {
-
-        $path = explode('?',$form_state['storage']['referring URL']);
->>>>>>> 6.x-0.4-dev
-        parse_str($path[1], $query);
-        $query['template_id'] = $form_state['storage']['template']->template_id;
-        drupal_goto($path[0], $query);
-
-    }
-    elseif ($op == 'Add Transformation') {
-
-      // Add transformation rule to original field
-      $form_state['storage']['original_field']['regex']['pattern'][] = '/' . $form_state['values']['pattern'] . '/';
-      $form_state['storage']['original_field']['regex']['replace'][] = $form_state['values']['replace'];
-
-      // Add original field back into template
-      $priority = $form_state['storage']['original_field']['priority'];
-      $field_index = $form_state['storage']['original_field']['field_index'];
-      $form_state['storage']['template_array'][$priority]['fields'][$field_index] = $form_state['storage']['original_field'];
-
-      // Save Template
-      $form_state['storage']['template']->template_array = serialize($form_state['storage']['template_array']);
-      $success = drupal_write_record('tripal_bulk_loader_template', $form_state['storage']['template'], array('template_id'));
-
-      if ($success) {
-        drupal_set_message('Successfully Added Transformation Rule');
-        drupal_set_message('Template Saved.');
-<<<<<<< HEAD
-      }
-      else {
-=======
-      } else {
->>>>>>> 6.x-0.4-dev
-        drupal_set_message('Unable to Save Template!', 'error');
-        watchdog('T_bulk_loader',
-          'Unable to save bulk loader template: %template',
-          array('%template' => print_r($form_state['storage']['template'], TRUE)),
-          WATCHDOG_ERROR
-        );
-      }
-<<<<<<< HEAD
-    }
-    elseif ($op == 'Save Transformation Rule Order') {
-=======
-    } elseif ($op == 'Save Transformation Rule Order') {
->>>>>>> 6.x-0.4-dev
-
-      // Generate new regex array
-      $new_regex = array();
-      $old_regex = $form_state['storage']['original_field']['regex'];
-      foreach ($form_state['values']['regex-data'] as $key => $element) {
-        $new_regex['pattern'][ $element['new_index'] ] = $old_regex['pattern'][ $element['old_index'] ];
-        $new_regex['replace'][ $element['new_index'] ] = $old_regex['replace'][ $element['old_index'] ];
-      }
-
-      // sort new regex arrays
-      asort($new_regex['pattern']);
-      asort($new_regex['replace']);
-
-      // Add back to original field
-      $form_state['storage']['original_field']['regex'] = $new_regex;
-      $priority = $form_state['storage']['original_field']['priority'];
-      $field_index = $form_state['storage']['original_field']['field_index'];
-      $form_state['storage']['template_array'][$priority]['fields'][$field_index] = $form_state['storage']['original_field'];
-
-      // Save Template
-      $form_state['storage']['template']->template_array = serialize($form_state['storage']['template_array']);
-      $success = drupal_write_record('tripal_bulk_loader_template', $form_state['storage']['template'], array('template_id'));
-
-      if ($success) {
-        drupal_set_message('Successfully Reordered Transformation Rules');
-        drupal_set_message('Template Saved.');
-<<<<<<< HEAD
-      }
-      else {
-=======
-      } else {
->>>>>>> 6.x-0.4-dev
-        drupal_set_message('Unable to Save Template!', 'error');
-        watchdog('T_bulk_loader',
-          'Unable to save bulk loader template: %template',
-          array('%template' => print_r($form_state['storage']['template'], TRUE)),
-          WATCHDOG_ERROR
-        );
-      }
-<<<<<<< HEAD
-    }
-    elseif ($op == 'Delete Transformation') {
-=======
-    } elseif ($op == 'Delete Transformation') {
->>>>>>> 6.x-0.4-dev
-
-      // Unset regex rule
-      $index = $form_state['clicked_button']['#name'];
-      unset($form_state['storage']['original_field']['regex']['pattern'][$index]);
-      unset($form_state['storage']['original_field']['regex']['replace'][$index]);
-
-      $priority = $form_state['storage']['original_field']['priority'];
-      $field_index = $form_state['storage']['original_field']['field_index'];
-      $form_state['storage']['template_array'][$priority]['fields'][$field_index] = $form_state['storage']['original_field'];
-
-      // Save Template
-      $form_state['storage']['template']->template_array = serialize($form_state['storage']['template_array']);
-      $success = drupal_write_record('tripal_bulk_loader_template', $form_state['storage']['template'], array('template_id'));
-
-      if ($success) {
-        drupal_set_message('Successfully Reordered Transformation Rules');
-        drupal_set_message('Template Saved.');
-<<<<<<< HEAD
-      }
-      else {
-=======
-      } else {
->>>>>>> 6.x-0.4-dev
-        drupal_set_message('Unable to Save Template!', 'error');
-        watchdog('T_bulk_loader',
-          'Unable to save bulk loader template: %template',
-          array('%template' => print_r($form_state['storage']['template'], TRUE)),
-          WATCHDOG_ERROR
-        );
-      }
-
-<<<<<<< HEAD
-    }
-    elseif ($op == 'Test Transformation Rules') {
-=======
-    } elseif ($op == 'Test Transformation Rules') {
->>>>>>> 6.x-0.4-dev
-
-      $patterns = $form_state['storage']['original_field']['regex']['pattern'];
-      $replaces = $form_state['storage']['original_field']['regex']['replace'];
-      $test_string = $form_state['values']['test_string'];
-      $form_state['storage']['test_regex_result'] = preg_replace($patterns, $replaces, $test_string);
-      $form_state['storage']['test_regex_test'] = $test_string;
-    }
-  }
-
-}
-
-//////////////////////////////////////////////////////////////////////////////////////
-// AHAH Callbacks
-//////////////////////////////////////////////////////////////////////////////////////
-
-/**
- * AHAH Function: Replace $form['add_fields'] in tripal_bulk_loader_add_template_field_form
- *
- * @return
- *  JSON Data printed to the screen
- */
-function tripal_bulk_loader_add_field_ahah() {
-
-  $form_state = array('storage' => NULL, 'submitted' => FALSE);
-  $form_build_id = $_POST['form_build_id'];
-  $form = form_get_cache($form_build_id, $form_state);
-  $args = $form['#parameters'];
-  $form_id = array_shift($args);
-  $form_state['post'] = $form['#post'] = $_POST;
-
-  // Enable the submit/validate handlers to determine whether AHAH-submittted.
-  $form_state['ahah_submission'] = TRUE;
-
-  $form['#programmed'] = $form['#redirect'] = FALSE;
-  drupal_process_form($form_id, $form, $form_state);
-  $form = drupal_rebuild_form($form_id, $form_state, $args, $form_build_id);
-
-  $form_element = $form['add_fields'];
-  // Remove the wrapper so we don't double it up.
-  //unset($form_element['#prefix'], $form_element['#suffix']);
-
-  $output = theme('status_messages');
-  $output .= drupal_render($form_element);
-
-  // Final rendering callback.
-  print drupal_json(array('status' => TRUE, 'data' => $output));
-  exit();
-
-}
-
-/**
- * AHAH Function: Replace $form['edit_fields'] in tripal_bulk_loader_edit_template_field_form
- *
- * @return
- *  JSON Data printed to the screen
- */
-function tripal_bulk_loader_edit_field_ahah() {
-
-  $form_state = array('storage' => NULL, 'submitted' => FALSE);
-  $form_build_id = $_POST['form_build_id'];
-  $form = form_get_cache($form_build_id, $form_state);
-  $args = $form['#parameters'];
-  $form_id = array_shift($args);
-  $form_state['post'] = $form['#post'] = $_POST;
-
-  // Enable the submit/validate handlers to determine whether AHAH-submittted.
-  $form_state['ahah_submission'] = TRUE;
-
-  $form['#programmed'] = $form['#redirect'] = FALSE;
-  drupal_process_form($form_id, $form, $form_state);
-  $form = drupal_rebuild_form($form_id, $form_state, $args, $form_build_id);
-
-  $form_element = $form['edit_fields'];
-  // Remove the wrapper so we don't double it up.
-  unset($form_element['#prefix'], $form_element['#suffix']);
-
-  $output = theme('status_messages');
-  $output .= drupal_render($form_element);
-
-  // Final rendering callback.
-  print drupal_json(array('status' => TRUE, 'data' => $output));
-  exit();
-
-<<<<<<< HEAD
-}
-=======
+<?php
+
+/**
+ * @file
+ * All functions in this file pertain to administrative management of bulk loader templates
+ */
+
+/**
+ * @section
+ * Modify Template
+ * The main form for creating/editing templates as a whole
+ */
+
+
+/**
+ * The main form reached at admin/tripal/tripal_bulk_loader/create and /edit
+ */
+function tripal_bulk_loader_modify_template_base_form($form_state = NULL, $mode) {
+  $form = array();
+
+   // get template id from path and rebuild form
+  if ($_GET['template_id']) {
+    if (preg_match('/^\d+$/', $_GET['template_id'])) {
+      $form_state['storage']['template_id'] = $_GET['template_id'];
+    }
+
+    $sql = "SELECT * FROM {tripal_bulk_loader_template} WHERE template_id=%d";
+    $result = db_fetch_object(db_query($sql, $form_state['storage']['template_id']));
+    $form_state['storage']['template'] = unserialize($result->template_array);
+    $form_state['storage']['template_name'] = $result->name;
+
+    $form_state['storage']['record2priority'] = array();
+    foreach ($form_state['storage']['template'] as $priority => $record_array) {
+      if (!is_array($record_array)) {
+        continue; }
+      $form_state['storage']['record2priority'][$record_array['record_id']] = $priority;
+    }
+  }
+
+  $form['mode'] = array(
+    '#type' => 'hidden',
+    '#value' => $mode,
+  );
+
+  if ($form_state['storage']['template_id']) {
+    $form['template_name'] = array(
+      '#type' => 'item',
+      '#title' => 'Template',
+      '#value' => $form_state['storage']['template_name'],
+      '#weight' => 1,
+    );
+  }
+  else {
+    if (preg_match('/create/', $mode)) {
+      $form['new_template_name'] = array(
+        '#type' => 'textfield',
+        '#title' => 'Template Name',
+        '#weight' => 1,
+      );
+    }
+    elseif (preg_match('/edit/', $mode)) {
+      $sql = "SELECT * FROM {tripal_bulk_loader_template}";
+      $resource = db_query($sql);
+      $templates = array();
+      $templates[''] = 'Select a Template';
+      while ($r = db_fetch_object($resource)) {
+        $templates[$r->template_id] = $r->name;
+      }
+
+      $form['template_id'] = array(
+        '#title'         => t('Template'),
+        '#description'   => t('Please select the template you would like to edit.'),
+        '#type'          => 'select',
+        '#options'       => $templates,
+        '#default_value' => $form_state['storage']['template_id'],
+        '#weight'        => 0,
+        '#required'      => TRUE,
+        '#weight' => 1,
+      );
+    }
+  }
+
+  $form['records'] = array(
+    '#type' => ($form_state['storage']['template_id'])? 'fieldset' : 'hidden',
+    '#title' => t('Current Records'),
+    '#collapsible' => TRUE,
+    '#weight' => 2,
+  );
+
+  $form['records']['description'] = array(
+    '#type' => 'item',
+    '#value' => 'Records will be inserted into the chado database in the order listed below. To '
+      .'change this order: <ul><li>Drag the rows into the correct order OR</li><li>Enter '
+      .'the numbers 1 and up in the Order textboxes to indicate the correct order.</li></ul>',
+  );
+
+  $form['records']['records-data'] = array(
+    '#tree' => TRUE,
+  );
+
+  $form['records']['no_records'] = array(
+    '#type' => 'hidden',
+    '#value' => TRUE,
+  );
+
+  $form['records']['submit-new_record'] = array(
+    '#type' => 'submit',
+    '#value' => 'New Record/Field',
+  );
+
+  $form['records']['submit-reorder'] = array(
+    '#type' => 'submit',
+    '#value' => 'Save Order',
+  );
+
+  $form['fields'] = array(
+    '#type' => ($form_state['storage']['template_id'])? 'fieldset' : 'hidden',
+    '#title' => t('Current Fields'),
+    '#collapsible' => TRUE,
+    '#weight' => 3,
+  );
+
+  $form['fields']['fields-data'] = array(
+    '#tree' => TRUE,
+  );
+
+  if ($form_state['storage']['template']) {
+
+    // List Current Fields -------------------------------------------------------------
+    $i=1;
+    foreach ($form_state['storage']['template'] as $priority => $table_array) {
+      if (!is_array($table_array)) {
+      continue; }
+
+        $form['records']['no_records']['#value'] = FALSE;
+
+        $form['records']['records-data'][$priority] = array(
+          'title' => array(
+            '#type' => 'markup',
+            '#value' => filter_xss($table_array['record_id']),
+          ),
+          'chado_table' => array(
+            '#type' => 'markup',
+            '#value' => filter_xss($table_array['table']),
+          ),
+          'mode' => array(
+            '#type' => 'item',
+            '#value' => ($table_array['mode']) ? $table_array['mode'] : 'insert_unique',
+          ),
+          'new_priority' => array(
+            '#type' => 'select',
+            '#options' => range(1, sizeof($form_state['storage']['template'])),
+            '#default_value' => $priority,
+          ),
+          'old_priority' => array(
+            '#type' => 'hidden',
+            '#value' => $priority,
+          ),
+          'id'  => array(
+            '#type' => 'hidden',
+            '#value' => $priority,
+          ),
+          'submit-edit_record' => array(
+            '#type' => 'submit',
+            '#name' => (string)$priority,
+            '#value' => 'Edit Record',
+          ),
+          'submit-add_field' => array(
+            '#type' => 'submit',
+            '#name' => (string)$priority,
+            '#value' => 'Add Field',
+          ),
+          'submit-duplicate_record' => array(
+            '#type' => 'submit',
+            '#name' => (string)$priority,
+            '#value' => 'Duplicate Record'
+          ),
+        );
+
+        foreach ($table_array['fields'] as $field_index => $field) {
+
+          $form['fields']['fields-data'][$i] = array(
+            'record_id' => array(
+              '#type' => 'item',
+              '#value' => $table_array['record_id'],
+            ),
+            'priority_hidden' => array(
+              '#type' => 'hidden',
+              '#value' => $priority,
+            ),
+            'field_name' => array(
+              '#type' => 'item',
+              '#value' => $field['title'],
+            ),
+            'chado_table_name' => array(
+              '#type' => 'item',
+              '#value' => $table_array['table'],
+            ),
+            'chado_table_hidden' => array(
+              '#type' => 'hidden',
+              '#value' => $table_array['table'],
+            ),
+            'chado_field_name' => array(
+              '#type' => 'item',
+              '#value' => $field['field'],
+            ),
+            'sheet_name' => array(
+              '#type' => 'item',
+              '#value' => $field['spreadsheet sheet'],
+            ),
+            'column_num' => array(
+              '#type' => 'item',
+              '#value' => $field['spreadsheet column'],
+            ),
+            'constant_value' => array(
+              '#type' => 'item',
+              '#value' => $field['constant value'],
+            ),
+            'field_index' => array(
+              '#type' => 'hidden',
+              '#value' => $field_index
+            ),
+            'foreign_record_id' => array(
+              '#type' => 'item',
+              '#value' => $field['foreign key'],
+            ),
+            'edit_submit' => array(
+              '#type' => 'submit',
+              '#name' => (string)$i,
+              '#value' => "Edit Field",
+            ),
+            'delete_submit' => array(
+              '#type' => 'submit',
+              '#name' => (string)$i,
+              '#value' => "Delete Field",
+            ),
+          );
+
+          $i++;
+        }
+    }
+    $form['fields']['total_fields'] = array(
+      '#type' => 'item',
+      '#value' => $i,
+    );
+
+  }
+
+  if ($form['records']['no_records']['#value']) {
+    $form['records']['description'] = array(
+      '#type' => 'item',
+      '#value' => 'There are currently no records.',
+    );
+    unset($form['records']['submit-reorder']);
+
+    $form['fields']['description'] = array(
+      '#type' => 'item',
+      '#value' => 'There are currently no fields.',
+    );
+
+  }
+
+  $mode_title = (preg_match('/create/', $mode)) ? 'Create Template' : 'Edit Template';
+  $value = ($form_state['storage']['template_id'])? 'Save Template' : $mode_title;
+  $form['submit'] = array(
+    '#type' => 'submit',
+    '#value' => $value,
+    '#weight' => 4,
+  );
+
+  return $form;
 }
->>>>>>> 6.x-0.4-dev
+
+/**
+ * Submit for tripal_bulk_loader_modify_template_base_form
+ */
+function tripal_bulk_loader_modify_template_base_form_submit($form, &$form_state) {
+
+  $form_state['rebuild'] = TRUE;
+  if ($form_state['storage']['template_id']) {
+    $sql = "SELECT * FROM {tripal_bulk_loader_template} WHERE template_id=%d";
+    $result = db_fetch_object(db_query($sql, $form_state['storage']['template_id']));
+    $form_state['storage']['template'] = unserialize($result->template_array);
+  }
+
+  $op = $form_state['values'][ $form_state['clicked_button']['#name'] ];
+  switch ($op) {
+    // Initialize after template is chosen ----------------------------------------
+    case 'Edit Template':
+      $form_state['storage']['template_id'] = $form_state['values']['template_id'];
+
+      $sql = "SELECT * FROM {tripal_bulk_loader_template} WHERE template_id=%d";
+      $result = db_fetch_object(db_query($sql, $form_state['storage']['template_id']));
+      $form_state['storage']['template'] = unserialize($result->template_array);
+      $form_state['storage']['template_name'] = $result->name;
+
+      $form_state['storage']['record2priority'] = array();
+      foreach ($form_state['storage']['template'] as $priority => $record_array) {
+        if (!is_array($record_array)) {
+          continue;
+        }
+        $form_state['storage']['record2priority'][$record_array['record_id']] = $priority;
+      }
+    break;
+
+    case 'Create Template':
+      $record = array(
+        'name' => $form_state['values']['new_template_name'],
+        'template_array' => array(),
+      );
+      drupal_write_record('tripal_bulk_loader_template', $record);
+      $form_state['storage']['template_id'] = $record['template_id'];
+      $form_state['storage']['template_name'] = $record['name'];
+      $form_state['storage']['template'] = array();
+    break;
+
+    // Save Reordered Records -----------------------------------------------------
+    case 'Save Order':
+      $new_template = $form_state['storage']['template'];
+      // unset old elements
+      $form_state['storage']['record2priority'] = array();
+      foreach ($new_template as $priority => $record_array) {
+        if (preg_match('/\d+/', $priority)) {
+          unset($new_template[$priority]);
+        }
+      }
+      //set elements in new order
+      foreach ($form_state['values']['records-data'] as $item) {
+        $new_template[$item['new_priority']] = $form_state['storage']['template'][$item['old_priority']];
+        $record_name = $new_template[$item['new_priority']]['record_id'];
+        $form_state['storage']['record2priority'][$record_name] = $item['new_priority'];
+      }
+      ksort($new_template);
+      $form_state['storage']['template'] = $new_template;
+    break;
+
+    case 'New Record/Field':
+      $query = array(
+        'template_id' => $form_state['storage']['template_id'],
+        'record_id' => 'NEW',
+      );
+      drupal_goto('admin/tripal/tripal_bulk_loader_template/add_field', $query);
+    break;
+
+    case 'Edit Record':
+      $query = array(
+        'template_id' => $form_state['storage']['template_id'],
+        'record_id' => $form_state['clicked_button']['#name'],
+      );
+      drupal_goto('admin/tripal/tripal_bulk_loader_template/edit_record', $query);
+    break;
+
+    case 'Add Field':
+      $query = array(
+        'template_id' => $form_state['storage']['template_id'],
+        'record_id' => $form_state['clicked_button']['#name'],
+      );
+      drupal_goto('admin/tripal/tripal_bulk_loader_template/add_field', $query);
+    break;
+
+    case 'Duplicate Record':
+      // original record (one to be duplicated)
+      $orig_priority = $form_state['clicked_button']['#name'];
+      $record = $form_state['storage']['template'][ $orig_priority ];
+
+      // new record
+      $new_priority = sizeof($form_state['storage']['template']) + 1;
+      $record['record_id'] = $record['record_id'] . '_' . date('YzHi');
+      $form_state['storage']['template'][ $new_priority ] = $record;
+    break;
+
+    case 'Edit Field':
+      $field_data_index = $form_state['clicked_button']['#name'];
+      $query = array(
+        'template_id' => $form_state['storage']['template_id'],
+        'record_id' => $form_state['values']['fields-data'][$field_data_index]['priority_hidden'],
+        'field_index' => $form_state['values']['fields-data'][$field_data_index]['field_index'],
+      );
+      drupal_goto('admin/tripal/tripal_bulk_loader_template/edit_field', $query);
+    break;
+
+    case 'Delete Field':
+      $field_data = $form_state['values']['fields-data'][$form_state['clicked_button']['#name']];
+      $priority = $field_data['priority_hidden'];
+      $field_key = $field_data['field_index'];
+      unset($form_state['storage']['template'][$priority]['fields'][$field_key]);
+      if (!$form_state['storage']['template'][$priority]['fields']) {
+        unset($form_state['storage']['record2priority'][$form_state['storage']['template'][$priority]['record_id']]);
+        unset($form_state['storage']['template'][$priority]);
+      }
+      drupal_set_message(t('Deleted Field from Template.'));
+    break;
+  } //end of switch
+
+  // Save Template
+  $record = array(
+    'template_id' => $form_state['storage']['template_id'],
+    'template_array' => serialize($form_state['storage']['template'])
+  );
+  drupal_write_record('tripal_bulk_loader_template', $record, array('template_id'));
+  drupal_set_message(t('Template Saved.'));
+
+}
+
+/**
+ * @section
+ * Delete Template
+ */
+
+/**
+ * Delete Template Form
+ * This form allows admin to delete already existing templates
+ */
+function tripal_bulk_loader_delete_template_base_form() {
+  $form = array();
+
+  $sql = "SELECT * FROM {tripal_bulk_loader_template}";
+  $resource = db_query($sql);
+  $templates = array();
+  $templates[''] = 'Select a Template';
+  while ($r = db_fetch_object($resource)) {
+    $templates[$r->template_id] = $r->name;
+  }
+  $form['template_name'] = array(
+      '#title'         => t('Template'),
+      '#description'   => t('Please select the template you would like to delete.'),
+      '#type'          => 'select',
+      '#options'       => $templates,
+      '#weight'        => 0,
+      '#required'      => TRUE,
+  );
+
+  $form['submit'] = array(
+    '#type' => 'submit',
+    '#value' => 'Delete Template',
+  );
+
+  return $form;
+}
+
+/**
+ * Delete Template Form Submit
+ *
+ * @param $form
+ *   The form that was submitted
+ * @param $form_state
+ *   The values and storage that were submitted
+ */
+function tripal_bulk_loader_delete_template_base_form_submit($form, &$form_state) {
+  $sql = "DELETE FROM {tripal_bulk_loader_template} WHERE template_id=%d";
+  db_query($sql, $form_state['values']['template_name']);
+}
+
+/**
+ * @section
+ * Import/Export Template
+ */
+
+/**
+ * Import/Export Template Form
+ *
+ * On export, simply selects the serialized array from the db for a given template
+ * and presents it to the user. On import, a serialized template array and a name is
+ * supplied and a template record is created.
+ *
+ * @todo Make array presented to the user more readable. (ie: unserialize and print to the screen)
+ *
+ * @param $form_state
+ *   The values and storage for the form
+ * @param $mode
+ *   Either 'import' or 'export' to indicate which function is being performed
+ * @return
+ *   A form array to be rendered by drupal_get_form
+ */
+function tripal_bulk_loader_import_export_template_form($form_state = NULL, $mode) {
+  $form = array();
+
+  $form['mode'] = array(
+    '#type' => 'hidden',
+    '#value' => $mode,
+  );
+
+  if (preg_match('/import/', $mode)) {
+    $form['new_template_name'] = array(
+      '#type' => 'textfield',
+      '#title' => 'Template Name',
+      '#weight' => 1,
+    );
+  }
+  elseif (preg_match('/export/', $mode)) {
+    $sql = "SELECT * FROM {tripal_bulk_loader_template}";
+    $resource = db_query($sql);
+    $templates = array();
+    $templates[''] = 'Select a Template';
+    while ($r = db_fetch_object($resource)) {
+      $templates[$r->template_id] = $r->name;
+    }
+
+    $form['template_id'] = array(
+      '#title'         => t('Template'),
+      '#description'   => t('Please select the template you would like to edit.'),
+      '#type'          => 'select',
+      '#options'       => $templates,
+      '#default_value' => $form_state['storage']['template_id'],
+      '#weight'        => 0,
+      '#required'      => TRUE,
+      '#weight' => 1,
+    );
+  }
+
+  $form['template_array'] = array(
+    '#type' => 'textarea',
+    '#title' => 'Template Array',
+    '#default_value' => $form_state['storage']['template_array'],
+    '#weight' => 2,
+  );
+
+  $form['submit'] = array(
+    '#type' => 'submit',
+    '#value' => 'Submit',
+    '#weight' => 10,
+  );
+
+  return $form;
+}
+
+/**
+ * Import/Export Template Form Submit
+ *
+ * @param $form
+ *   The form that was submitted
+ * @param $form_state
+ *   The values and storage that were submitted
+ */
+function tripal_bulk_loader_import_export_template_form_submit($form, &$form_state) {
+  switch ($form_state['values']['mode']) {
+    case 'export':
+      $record = db_fetch_object(db_query("SELECT * FROM {tripal_bulk_loader_template} WHERE template_id=%d", $form_state['values']['template_id']));
+      $form_state['storage']['template_array'] = $record->template_array;
+      $form_state['storage']['template_id'] = $form_state['values']['template_id'];
+    break;
+    case 'import':
+      $record = array(
+        'name' => $form_state['values']['new_template_name'],
+        'template_array' => $form_state['values']['template_array'],
+      );
+      drupal_write_record('tripal_bulk_loader_template', $record);
+      if ($record->template_id) {
+        drupal_set_message(t('Successfully imported Tripal Bulk Loader Template.'));
+      }
+    break;
+  }
+}
+
+/**
+ * @section
+ * Edit Record Form
+ */
+
+/**
+ * Edit Record Form
+ *
+ * This form is meant to be called from a bulk loader form. The following should be set
+ * in the query section of the path:
+ *  - template_id=\d+: the template which the edited record is part of
+ *  - record_id=\d+: the priority or key in the template array of the record to be edited
+ *
+ * @param $form_state
+ *   Contains the values and storage for the form
+ * @return
+ *   A form array to be rendered by drupal_get_form
+ */
+function tripal_bulk_loader_edit_template_record_form(&$form_state = NULL) {
+  $form['#cache'] = TRUE; // Make sure the form is cached.
+
+   // get template id from path
+  $template_id = ($_GET['template_id'] !== NULL) ? $_GET['template_id'] : $form_state['values']['template_id'];
+
+  // if there is no template supplied don't return rest of form
+  if (!$template_id) {
+    return $form;
+  }
+
+  // Pre-process values/defaults ---------------------------
+
+  // If this is the first load of the form (no form state) we need to initialize some variables
+  if (!$form_state['storage']['template']) {
+    $sql = "SELECT * FROM {tripal_bulk_loader_template} WHERE template_id=%d";
+    $template = db_fetch_object(db_query($sql, $template_id));
+    $form_state['storage']['template_array'] = unserialize($template->template_array);
+    $form_state['storage']['template'] = $template;
+
+    $form_state['storage']['record2priority'] = array();
+    foreach ($form_state['storage']['template_array'] as $priority => $record_array) {
+      if (!is_array($record_array)) {
+        continue;
+      }
+      $form_state['storage']['record2priority'][$record_array['record_id']] = $priority;
+    }
+
+    $form_state['storage']['referring URL'] = $_SERVER["HTTP_REFERER"];
+  }
+  else {
+    $template = $form_state['storage']['template'];
+  }
+
+  // get the record_id from the path
+  if ($_GET['record_id'] !== NULL) {
+    $form_state['values']['field_group'] = $_GET['record_id'];
+    $form_state['storage']['original_priority'] = $_GET['record_id'];
+  }
+
+
+  // Tables and default table
+  $tables = tripal_core_get_chado_tables();
+  if ($form_state['values']['chado_table']) {
+    $table = $form_state['values']['chado_table'];
+  }
+  else {
+    $table = $form_state['storage']['template_array'][$form_state['storage']['original_priority']]['table'];
+  }
+
+  //dpm($form_state, 'form state');
+
+   // Form Proper -------------------------------------------
+  $form['template_name'] = array(
+    '#type' => 'item',
+    '#title' => 'Template',
+    '#value' => $template->name,
+  );
+
+  $form['template_id'] = array(
+    '#type' => 'hidden',
+    '#value' => $template_id,
+  );
+
+  $form['edit_record'] = array(
+    '#type' => 'fieldset',
+  );
+
+  // check template array for records then add one more
+  if (!$form_state['storage']['record2priority']) {
+    $groups = array();
+  }
+  else {
+    $groups = array_flip($form_state['storage']['record2priority']);
+  }
+  $priority_default = $form_state['values']['field_group'];
+  $form['edit_record']['field_group']  = array(
+    '#type' => 'select',
+    '#title' => 'Record',
+    '#description' => 'By Changing the record here, you can move all the fields from the current record into the selected record.',
+    '#options' => $groups,
+    '#default_value' => $priority_default,
+    '#required' => TRUE,
+  );
+
+  $form['edit_record']['record_name'] = array(
+    '#type' => 'textfield',
+    '#title' => 'Unique Record Name',
+    '#default_value' => $groups[$priority_default],
+  );
+
+  $form['edit_record']['chado_table'] = array(
+    '#type' => 'select',
+    '#title' => t('Chado Table'),
+    '#description' => 'This changes the chado table for all fields in this record.',
+    '#options' => $tables,
+    '#default_value' => $table,
+  );
+
+  $form['edit_record']['mode'] = array(
+    '#type' => 'radios',
+    '#title' => 'Action to take when Loading Record',
+    '#options' => array(
+      'select' => 'SELECT: Don\'t insert this record: it\'s used to define a foreign key in another record',
+      'insert' => 'INSERT: Insert the record',
+      'optional' => 'OPTIONAL: Record will only be inserted if all required data is filled in',
+      'insert_once' => 'INSERT ONCE: Record will be inserted once for the entire file',
+      'insert_unique' => 'INSERT UNIQUE: Only insert record if there isn\'t a record with the same values',
+    ),
+    '#default_value' => 'insert_unique'
+  );
+
+  $form['edit_record']['submit-edit_record'] = array(
+      '#type' => 'submit',
+      '#value' => 'Edit Record'
+  );
+
+  $form['edit_record']['submit-cancel'] = array(
+      '#type' => 'submit',
+      '#value' => 'Cancel'
+  );
+
+  return $form;
+}
+
+
+/**
+ * Edit Record Form Submit
+ *
+ * @param $form
+ *   The form that was submitted
+ * @param $form_state
+ *   Contains the values and storage for the form
+ */
+function tripal_bulk_loader_edit_template_record_form_submit($form, &$form_state) {
+  //dpm($form_state, 'form state -start submit');
+
+  if (!$form_state['ahah_submission']) {
+    if ($form_state['values']['op'] ==  'Edit Record') {
+
+      $template = $form_state['storage']['template_array'];
+
+      // Edit Record
+      $record = $template[ $form_state['storage']['original_priority'] ];
+      $record['record_id'] = $form_state['values']['record_name'];
+      $record['mode'] = $form_state['values']['mode'];
+      $record['table'] = $form_state['values']['chado_table'];
+
+      if ($form_state['storage']['original_priority'] != $form_state['values']['field_group']) {
+        $record['fields'] = array_merge($record['fields'], $template[ $form_state['values']['field_group'] ]['fields']);
+        $template[ $form_state['values']['field_group'] ] = $record;
+        unset($template[ $form_state['storage']['original_priority'] ]);
+      }
+      else {
+        $template[ $form_state['storage']['original_priority'] ] = $record;
+      }
+
+      // Save Template
+      $form_state['storage']['template']->template_array = serialize($template);
+      $success = drupal_write_record('tripal_bulk_loader_template', $form_state['storage']['template'], array('template_id'));
+
+      if ($success) {
+        drupal_set_message(t('Successfully Updated Template Record'));
+        drupal_set_message(t('Template Saved.'));
+
+        $path = explode('?', $form_state['storage']['referring URL']);
+        parse_str($path[1], $query);
+        $query['template_id'] = $form_state['storage']['template']->template_id;
+        drupal_goto($path[0], $query);
+      }
+      else {
+        drupal_set_message(t('Unable to Save Template!'), 'error');
+        watchdog('T_bulk_loader',
+          'Unable to save bulk loader template: %template',
+          array('%template' => print_r($form_state['storage']['template'], TRUE)),
+          WATCHDOG_ERROR
+        );
+      }
+    }
+    elseif ($form_state['values']['op'] ==  'Cancel') {
+        $path = explode('?', $form_state['storage']['referring URL']);
+        parse_str($path[1], $query);
+        $query['template_id'] = $form_state['storage']['template']->template_id;
+        //dpm('Redirecting to: '.$path[0].'?'.print_r($query,TRUE).' where the referring URL:'.$form_state['storage']['referring URL']);
+        drupal_goto($path[0], $query);
+    }
+  }
+
+}
+
+/**
+ * @section
+ * Add/Edit Field Forms
+ */
+
+/**
+ * Add Field Form
+ *
+ * This form is meant to be called from a bulk loader form. Blank Defaults are in place but you
+ * can use the following in the query of the path to set defaults for a given template:
+ *  - template_id=\d+: the template to add the field to
+ *  - record_id=\d+: the priority or key in the template array of the record to add the field to
+ *
+ * @param $form_state
+ *   Contains the values and storage for the form
+ * @return
+ *   A form array to be rendered by drupal_get_form
+ */
+function tripal_bulk_loader_add_template_field_form(&$form_state = NULL) {
+  $form = array();
+  $form['#cache'] = TRUE; // Make sure the form is cached.
+
+  // get template id from path
+  $template_id = ($_GET['template_id']) ? $_GET['template_id'] : $form_state['values']['template_id'];
+
+  // if there is no template supplied don't return rest of form
+  if (!$template_id) {
+    return $form;
+  }
+
+  // Pre-set Variables needed for form proper------------------------------------------
+
+   // If this is the first load of the form (no form state) we need to initialize some variables
+  if (!$form_state['storage']['template']) {
+    $sql = "SELECT * FROM {tripal_bulk_loader_template} WHERE template_id=%d";
+    $template = db_fetch_object(db_query($sql, $template_id));
+    $form_state['storage']['template_array'] = unserialize($template->template_array);
+    $form_state['storage']['template'] = $template;
+
+    $form_state['storage']['record2priority'] = array();
+  foreach ($form_state['storage']['template_array'] as $priority => $record_array) {
+    if (!is_array($record_array)) {
+      continue;
+    }
+    $form_state['storage']['record2priority'][$record_array['record_id']] = $priority;
+  }
+
+    $form_state['storage']['referring URL'] = $_SERVER["HTTP_REFERER"];
+  }
+  else {
+    $template = $form_state['storage']['template'];
+  }
+
+  $field_type = ($form_state['values']['field_type'])? $form_state['values']['field_type'] : 'table field';
+
+  // Tables and default table
+  $tables = tripal_core_get_chado_tables();
+  if ($form_state['values']) {
+    if (!preg_match('/^' . current($tables) . '$/', $form_state['values']['chado_table'])) {
+      $table = $form_state['values']['chado_table'];
+    }
+    elseif ($form_state['values']['record_name']) {
+      $record_name = $form_state['values']['record_name'];
+      $priority = $form_state['storage']['record2priority'][$record_name];
+      $table = $form_state['storage']['template_array'][$priority]['table'];
+    }
+    else {
+      $priority = $form_state['values']['field_group'];
+      $table = $form_state['storage']['template_array'][$priority]['table'];
+    }
+  }
+  if (!$table) {
+    $table = reset($tables);
+  }
+
+   // get the record_id from the path
+  if ($_GET['record_id'] !== NULL) {
+    $form_state['values']['field_group'] = $_GET['record_id'];
+    if (preg_match('/\d+/', $_GET['record_id'])) {
+      $priority = $form_state['values']['field_group'];
+      $table = $form_state['storage']['template_array'][$priority]['table'];
+    }
+  }
+
+  // Fields and foreign key mappings
+  $chado_fields = array();
+  $fk_options = array();
+  $fk_options['NULL'] = 'None';
+  $table_description = module_invoke_all('chado_' . $table . '_schema');
+  //dpm($table_description, 'table description for |'.$table.'|');
+  if ($field_type == 'foreign key') {
+    $foreign_field2table = array();
+    foreach ($table_description['foreign keys'] as $key_table => $key_array) {
+      foreach ($key_array['columns'] as $left_field => $right_field) {
+        $chado_fields[$left_field] = $left_field;
+        $foreign_field2table[$left_field] = $key_table;
+      }
+    }
+    reset($chado_fields);
+
+    // set default field
+    if (empty($chado_fields)) {
+      $field = NULL;
+    }
+    elseif ($chado_fields[$form_state['values']['chado_field']]) {
+      $field = $form_state['values']['chado_field'];
+    }
+    else {
+      $field = current($chado_fields);
+    }
+
+    // Foreign key options
+    $foreign_table = $foreign_field2table[$field];
+    if ($foreign_table) {
+      foreach ($form_state['storage']['record2priority'] as $record_name => $priority ) {
+        if (preg_match('/^' . $foreign_table . '$/', $form_state['storage']['template_array'][$priority]['table'])) {
+          $fk_options[$record_name] = $record_name;
+        }
+      }
+    }
+  }
+  else {
+    foreach ($table_description['fields'] as $field_name => $field_array) {
+        $chado_fields[$field_name] = $field_name;
+    }
+  }
+
+  $variables = array(
+    'form_state' => $form_state,
+    'tables' => $tables,
+    'default table' => $table,
+    'fields' => $chado_fields,
+    'default_field' => $field,
+    'priority' => $priority,
+    'record_name' => $record_name,
+    'table description' => $table_description,
+    'foreign key options' => $fk_options,
+    'foreign field=>table' => $foreign_field2table,
+    'foreign table' => $foreign_table,
+  );
+  //dpm($variables, 'variables');
+
+  // Start of Form Proper--------------------------------------------------------------
+  //dpm($form_state, 'Form State');
+
+  $form['template_name'] = array(
+    '#type' => 'item',
+    '#title' => 'Template',
+    '#value' => $template->name,
+  );
+
+  $form['template_id'] = array(
+    '#type' => 'hidden',
+    '#value' => $template_id,
+  );
+
+  $form['add_fields'] = array(
+    '#type' => 'fieldset',
+    '#prefix' => '<div id="tripal_bulk_loader_template-add_field">',
+    '#suffix' => '</div>',
+  );
+
+  $form['add_fields']['field_type'] = array(
+    '#type' => 'radios',
+    '#title' => t('Type of Field'),
+    '#options' => array(
+      'table field' => t('Data: A Field which maps to a column in the supplied file.'),
+      'constant' => t('Constant: Field which remains Constant throughout the file'),
+      'foreign key' => t('Foreign Key: Fields which map to a record in another table'),
+    ),
+    '#required' => TRUE,
+    '#default_value' => $field_type,
+    '#ahah' => array(
+      'path' => 'admin/tripal/tripal_bulk_loader_template/add_field_ahah',
+      'wrapper' => 'tripal_bulk_loader_template-add_field',
+      'effect' => 'fade'
+    ),
+  );
+
+  // check template array for records then add one more
+  if (!$form_state['storage']['record2priority']) {
+    $groups = array();
+  }
+  else {
+    $groups = array_flip($form_state['storage']['record2priority']);
+  }
+  $groups['NONE'] = 'Select a Record';
+  $groups['NEW'] = 'New Record';
+  $form['add_fields']['field_group']  = array(
+    '#type' => 'select',
+    '#title' => 'Record',
+    '#description' => 'This is used to group a set of fields together allowing '
+      .'multiple records to be inserted into the same table per line of the file',
+    '#options' => $groups,
+    '#default_value' => (preg_match('/\w+.*/', $form_state['values']['field_group'])) ? $form_state['values']['field_group'] : 'NONE',
+    '#ahah' => array(
+      'path' => 'admin/tripal/tripal_bulk_loader_template/add_field_ahah',
+      'wrapper' => 'tripal_bulk_loader_template-add_field',
+      'effect' => 'fade'
+    ),
+    '#required' => TRUE,
+  );
+
+  $form['add_fields']['record_name'] = array(
+    '#type' => (preg_match('/NEW/', $form_state['values']['field_group'])) ? 'textfield' : 'hidden',
+    '#title' => 'Unique Record Name',
+    '#prefix' => '<div id="tripal_bulk_loader_template-add_record">',
+    '#suffix' => '</div>',
+    '#default_value' => $form_state['values']['record_name'],
+  );
+
+  $form['add_fields']['field_title'] = array(
+    '#type' => 'textfield',
+    '#title' => t('Human-readable Title for Field'),
+    '#default_value' => $form_state['values']['field_title'],
+  );
+
+  // loading file data column
+  $form['add_fields']['columns'] = array(
+    '#type' => 'fieldset',
+    '#title' => t('Data File Column'),
+    '#collapsible' => TRUE,
+    '#collapsed' => ($field_type == 'table field')? FALSE : TRUE,
+  );
+
+  /**
+  $form['add_fields']['columns']['sheet_name'] = array(
+    '#type' => 'textfield',
+    '#title' => t('Worksheet'),
+    '#description' => t('Specify the name of the worksheet.'),
+    '#size' => 5,
+    '#default_value' => ($form_state['values']['sheet_name'])? $form_state['values']['sheet_name'] : 'Sheet1',
+  );
+  */
+
+  $form['add_fields']['columns']['column_number'] = array(
+    '#type' => 'textfield',
+    '#title' => t('Column'),
+    '#description' => t('Specify the column in the data that this field maps to where the first column is 1.'),
+    '#size' => 5,
+    '#default_value' => $form_state['values']['column_number'],
+  );
+
+  $form['add_fields']['columns']['column_exposed'] = array(
+    '#type' => 'checkbox',
+    '#title' => t('Allow Column to be set for each Bulk Loading Job'),
+    '#description' => t('Adds a textbox field to the Bulk Loader Page to allow users to set this value.'),
+    '#default_value' => ($form_state['values']['column_exposed']) ? $form_state['values']['column_exposed'] : $template_field['exposed'],
+  );
+
+  $form['add_fields']['columns']['column_exposed_desc'] = array(
+    '#type' => 'textfield',
+    '#title' => t('Description for exposed field on bulk loading job'),
+    '#description' => t('This description should tell the user what column should be entered here.'),
+    '#default_value' => ($form_state['values']['column_exposed_desc']) ? $form_state['values']['column_exposed_desc'] : $template_field['exposed_description'],
+  );
+
+  // Global Value
+  $form['add_fields']['constant'] = array(
+    '#type' => 'fieldset',
+    '#title' => t('Constant'),
+    '#collapsible' => TRUE,
+    '#collapsed' => ($field_type == 'constant')? FALSE : TRUE,
+  );
+
+  $form['add_fields']['constant']['constant_value'] = array(
+    '#type' => 'textfield',
+    '#title' => t('Constant Value'),
+    '#description' => t('Specify the value you wish this field to have regardless of data file value.'),
+    '#default_value' => $form_state['values']['constant_value']
+  );
+
+  $form['add_fields']['constant']['constant_exposed'] = array(
+    '#type' => 'checkbox',
+    '#title' => t('Allow Constant to be set for each Bulk Loading Job'),
+    '#description' => t('Adds a textbox field to the Create Bulk Loader Form to allow users to set this value.')
+  );
+
+  $form['add_fields']['constant']['constant_validate'] = array(
+    '#type' => 'checkbox',
+    '#title' => t('Ensure value is in table'),
+    '#description' => t('Checks the database when a bulk loading job is created to ensure the value entered already exists in the database.'),
+  );
+
+  // Foreign Key
+  $form['add_fields']['foreign_key'] = array(
+    '#type' => 'fieldset',
+    '#title' => 'Foreign Key',
+    '#collapsible' => TRUE,
+    '#collapsed' => ($field_type == 'foreign key')? FALSE : TRUE,
+  );
+
+  $form['add_fields']['foreign_key']['foreign_record'] = array(
+    '#type' => 'select',
+    '#title' => 'Record to refer to',
+    '#descripion' => 'Select the record that this foreign key shouold refer to. The record needs to already exist and be of the correct table.',
+    '#options' => $fk_options,
+  );
+
+  // Chado Field
+  $form['add_fields']['chado'] = array(
+    '#type' => 'fieldset',
+    '#title' => t('Chado Field/Column Details'),
+    '#description' => t('Specify the Table/Field in chado that this field maps to.'),
+  );
+
+  $form['add_fields']['chado']['chado_table'] = array(
+    '#type' => 'select',
+    '#title' => t('Chado Table'),
+    '#options' => $tables,
+    '#default_value' => $table,
+    '#ahah' => array(
+      'path' => 'admin/tripal/tripal_bulk_loader_template/add_field_ahah',
+      'wrapper' => 'tripal_bulk_loader_template-add_field',
+      'effect' => 'fade'
+      ),
+  );
+
+  $form['add_fields']['chado']['chado_field'] = array(
+    '#type' => 'select',
+    '#title' => t('Chado Field/Column'),
+    '#options' => $chado_fields,
+    '#default_value' => $form_state['values']['chado_field'],
+    '#ahah' => array(
+      'path' => 'admin/tripal/tripal_bulk_loader_template/add_field_ahah',
+      'wrapper' => 'tripal_bulk_loader_template-add_field',
+      'effect' => 'fade'
+    ),
+  );
+
+  $form['add_fields']['additional'] = array(
+    '#type' => 'fieldset',
+    '#title' => 'Additional Options',
+  );
+
+  $form['add_fields']['additional']['required'] = array(
+    '#type' => 'checkbox',
+    '#title' => 'Make this file required',
+  );
+
+  $form['add_fields']['additional']['regex_transform'] = array(
+    '#type' => 'fieldset',
+    '#title' => 'Transform Data File Value Rules',
+    '#collapsible' => TRUE,
+    '#collapsed' => (!$form_state['storage']['regex']['pattern']) ? TRUE : FALSE,
+  );
+
+  $form['add_fields']['additional']['regex_transform']['regex_description'] = array(
+    '#type' => 'item',
+    '#value' => 'A transformation rule allows you to transform the original value '
+      .'(usually from a user submitted data file) into the form you would like it stored '
+      .'in the chado database. Each rule consists of a match pattern (a php regular expression '
+      .'which determines which replacement patterns are applied and captures regions of the '
+      .'original value) and a replacement pattern (a string which may contain capture references '
+      .'that describes what the new value should be). Each rule is applied to the result of the '
+      .'previous rule.'
+  );
+
+  $form['add_fields']['additional']['regex_transform']['regex-data'] = array(
+    '#tree' => TRUE,
+  );
+  if (!$form_state['storage']['regex']['pattern']) {
+    $form_state['storage']['regex']['pattern'] = array();
+  }
+  foreach ($form_state['storage']['regex']['pattern'] as $index => $pattern) {
+    $data_element = array(
+      'pattern' => array(
+        '#type' => 'item',
+        '#value' => $pattern,
+      ),
+      'replace' => array(
+        '#type' => 'item',
+        '#value' => $form_state['storage']['regex']['replace'][$index],
+      ),
+      'old_index' => array(
+        '#type' => 'hidden',
+        '#value' => $index,
+      ),
+      'new_index' => array(
+        '#type' => 'select',
+        '#options' => range(0, sizeof($form_state['storage']['regex']['pattern'])-1),
+        '#default_value' => $index,
+      ),
+      'id' => array(
+        '#type' => 'hidden',
+        '#value' => $index,
+      ),
+      'submit-delete' => array(
+        '#type' => 'submit',
+        '#value' => 'Delete Transformation',
+        '#name' => $index,
+      ),
+    );
+    $form['add_fields']['additional']['regex_transform']['regex-data'][$index] = $data_element;
+  }
+
+  $form['add_fields']['additional']['regex_transform']['submit-reorder_regex'] = array(
+    '#type' => ($form_state['storage']['regex']['pattern']) ? 'submit' : 'hidden',
+    '#value' => 'Save Transformation Rule Order'
+  );
+
+  $form['add_fields']['additional']['regex_transform']['new_regex'] = array(
+    '#type' => 'fieldset',
+    '#title' => 'Add a new Transformation Rule',
+  );
+
+  $form['add_fields']['additional']['regex_transform']['new_regex']['pattern'] = array(
+    '#type' => 'textfield',
+    '#title' => 'Match Pattern',
+    '#description' => 'You can use standard php regular expressions in this field to specify a '
+      .'pattern. Only if this pattern matches the value in the data file does the replacement '
+      .'pattern get applied to the value. To capture a section of your value for use in the '
+      .'replacement patten surround with round brackets. For example, <i>GI:(\d+)</i> will match '
+      .' NCBI gi numbers and will capture the numerical digits for use in the replacement pattern. '
+      .' To match and capture any value use <i>.*</i>',
+  );
+
+  $form['add_fields']['additional']['regex_transform']['new_regex']['replace'] = array(
+    '#type' => 'textfield',
+    '#title' => 'Replacement Pattern',
+    '#description' => 'This pattern should contain the text you want to replace the match pattern '
+    .'mentioned above. It can include references of the form \n where n is the number of the '
+    .'capture in the match pattern. For example, \1 will be replaced with the text matched in your '
+    .'first set of round brackets.',
+  );
+
+  if ($field_type == 'table field') {
+    $tab = '&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp';
+    $form['add_fields']['additional']['regex_transform']['new_regex']['replace']['#description'] .= '<p>'
+      .'The following references are also available for data file fields: <b><#column:<i>number</i>#></b>. '
+      .'This allows you to substitute other data file values into the current field. For example, '
+      .'if you had the following line:<br />'
+      . $tab . 'SNP' . $tab . '15-Jan-2011' . $tab . '1' . $tab . '54' . $tab . 'Contig34355'
+      .'<br /> and your current field is for column #1 and you\'re inserting into the chado field '
+      .'feature.uniquename then you might want to add in the data to ensure your uniquename is '
+      .'unique. The Match Pattern is (.*) to select all the first column and the Replacement '
+      .'Pattern could be \1_<#column:2#> which would insert SNP_15-Jan-2011 into the database.</p>';
+  }
+
+  $form['add_fields']['additional']['regex_transform']['new_regex']['submit-add_transform'] = array(
+    '#type' => 'submit',
+    '#value' => 'Add Transformation',
+  );
+
+  $form['add_fields']['additional']['regex_transform']['test_regex'] = array(
+    '#type' => 'fieldset',
+    '#title' => 'Test Transformation Rules',
+  );
+
+  $form['add_fields']['additional']['regex_transform']['test_regex']['test_string'] = array(
+    '#type' => 'textfield',
+    '#title' => 'Test Value',
+    '#description' => 'This should be a value that you expect the above transformation rules '
+      .'to be applied to.',
+    '#default_value' => $form_state['storage']['test_regex_test'],
+  );
+
+  $form['add_fields']['additional']['regex_transform']['test_regex']['test_result'] = array(
+    '#type' => 'textfield',
+    '#title' => 'Test Result',
+    '#description' => 'This is the value that would be saved to the database after the above transformation '
+      .'riles were applied to the Test Value.',
+    '#default_value' => $form_state['storage']['test_regex_result'],
+  );
+
+  $form['add_fields']['additional']['regex_transform']['test_regex']['submit-test'] = array(
+    '#type' => 'submit',
+    '#value' => 'Test Transformation Rules'
+  );
+
+  $form['add_fields']['submit-add_field'] = array(
+      '#type' => 'submit',
+      '#value' => 'Add Field'
+  );
+
+  $form['add_fields']['submit-cancel'] = array(
+      '#type' => 'submit',
+      '#value' => 'Cancel'
+  );
+
+  return $form;
+}
+
+/**
+ * Add Field Submit
+ *
+ * @param $form
+ *   The form that was submitted
+ * @param $form_state
+ *   The values and storage for the form
+ */
+function tripal_bulk_loader_add_template_field_form_submit($form, &$form_state) {
+
+  $op = $form_state['values'][ $form_state['clicked_button']['#name'] ];
+
+  if (!$form_state['ahah_submission']) {
+    if ($op ==  'Add Field') {
+
+      $template = $form_state['storage']['template_array'];
+
+       // If new record
+      if (preg_match('/NEW/', $form_state['values']['field_group'])) {
+        $record_name = $form_state['values']['record_name'];
+        $priority = sizeof($form_state['storage']['template_array']) + 1;
+        $record2priority[$record_name] = $priority;
+        $template[$priority]['table'] = $form_state['values']['chado_table'];
+        $template[$priority]['record_id'] = $record_name;
+
+      }
+      else {
+        $priority = $form_state['values']['field_group'];
+        $record_name = $record2priority[$priority];
+      }
+
+      // Add field to template array
+      if ($form_state['values']['field_type'] == 'table field') {
+        $field = array(
+          'type' => 'table field',
+          'title' => $form_state['values']['field_title'],
+          'field' => $form_state['values']['chado_field'],
+          'required' => $form_state['values']['required'],
+          //'allowed values' => empty by default,
+          'spreadsheet column' => $form_state['values']['column_number'],
+          'exposed' => $form_state['values']['column_exposed'],
+          'exposed_description' => $form_state['values']['column_exposed_desc'],
+        );
+      }
+      elseif ($form_state['values']['field_type'] == 'constant') {
+        $field = array(
+          'type' => 'constant',
+          'title' => $form_state['values']['field_title'],
+          'field' => $form_state['values']['chado_field'],
+          'required' => $form_state['values']['required'],
+          //'allowed values' => empty by default,
+          'constant value' => $form_state['values']['constant_value'],
+          'exposed' => $form_state['values']['constant_exposed'],
+          'exposed_validate' => $form_state['values']['constant_validate'],
+        );
+      }
+      elseif ($form_state['values']['field_type'] == 'foreign key') {
+        $field = array(
+          'type' => 'foreign key',
+          'title' => $form_state['values']['field_title'],
+          'field' => $form_state['values']['chado_field'],
+          'foreign key' => $form_state['values']['foreign_record'],
+          'required' => $form_state['values']['required'],
+        );
+      }
+
+      // Deal with any additional options
+      if ($form_state['storage']['regex']) {
+        $field['regex'] = $form_state['storage']['regex'];
+      }
+
+      // Save Template
+      $template[$priority]['fields'][] = $field;
+      $form_state['storage']['template']->template_array = serialize($template);
+      $success = drupal_write_record('tripal_bulk_loader_template', $form_state['storage']['template'], array('template_id'));
+
+      if ($success) {
+        drupal_set_message(t('Successfully Added Field to Template'));
+        drupal_set_message(t('Template Saved.'));
+
+        $path = explode('?', $form_state['storage']['referring URL']);
+        parse_str($path[1], $query);
+        $query['template_id'] = $form_state['storage']['template']->template_id;
+        drupal_goto($path[0], $query);
+      }
+      else {
+        drupal_set_message(t('Unable to Save Template!'), 'error');
+        watchdog('T_bulk_loader',
+          'Unable to save bulk loader template: %template',
+          array('%template' => print_r($form_state['storage']['template'], TRUE)),
+          WATCHDOG_ERROR
+        );
+      }
+    }
+    elseif ($op ==  'Cancel') {
+        $path = explode('?', $form_state['storage']['referring URL']);
+        parse_str($path[1], $query);
+        $query['template_id'] = $form_state['storage']['template']->template_id;
+        drupal_goto($path[0], $query);
+    }
+    elseif ($op == 'Add Transformation') {
+
+      // Add transformation rule to original field
+      $form_state['storage']['regex']['pattern'][] = '/' . $form_state['values']['pattern'] . '/';
+      $form_state['storage']['regex']['replace'][] = $form_state['values']['replace'];
+      drupal_set_message(t('Successfully Added Transformation Rule'));
+
+    }
+    elseif ($op == 'Save Transformation Rule Order') {
+
+      // Generate new regex array
+      $new_regex = array();
+      $old_regex = $form_state['storage']['regex'];
+      foreach ($form_state['values']['regex-data'] as $key => $element) {
+        $new_regex['pattern'][ $element['new_index'] ] = $old_regex['pattern'][ $element['old_index'] ];
+        $new_regex['replace'][ $element['new_index'] ] = $old_regex['replace'][ $element['old_index'] ];
+      }
+
+      // sort new regex arrays
+      asort($new_regex['pattern']);
+      asort($new_regex['replace']);
+
+      $form_state['storage']['regex'] = $new_regex;
+    }
+    elseif ($op == 'Delete Transformation') {
+
+      // Unset regex rule
+      $index = $form_state['clicked_button']['#name'];
+      unset($form_state['storage']['regex']['pattern'][$index]);
+      unset($form_state['storage']['regex']['replace'][$index]);
+
+    }
+    elseif ($op == 'Test Transformation Rules') {
+
+      $patterns = $form_state['storage']['regex']['pattern'];
+      $replaces = $form_state['storage']['regex']['replace'];
+      $test_string = $form_state['values']['test_string'];
+      $form_state['storage']['test_regex_result'] = preg_replace($patterns, $replaces, $test_string);
+      $form_state['storage']['test_regex_test'] = $test_string;
+    }
+  }
+
+}
+
+/**
+ * Edit Field Form
+ *
+ * This form is meant to be called from a bulk loader form. The following should be set
+ * in the query section of the path:
+ *  - template_id=\d+: the template which the edited field is part of
+ *  - record_id=\d+: the priority or key in the template array of the record the field
+ *      is currently part of
+ *  - field_index=\d+: the key of the field in the fields array of the previously
+ *      specified record
+ *
+ * @param $form_state
+ *   Contains the values and storage for the form
+ * @return
+ *   A form array to be rendered by drupal_get_form
+ */
+function tripal_bulk_loader_edit_template_field_form(&$form_state = NULL) {
+  $form = array();
+  $form['#cache'] = TRUE; // Make sure the form is cached.
+
+  // get template id from path
+  $template_id = ($_GET['template_id']) ? $_GET['template_id'] : $form_state['values']['template_id'];
+
+  // if there is no template supplied don't return rest of form
+  if (!$template_id) {
+    return $form;
+  }
+
+  // Pre-set Variables needed for form proper------------------------------------------
+
+  // If this is the first load of the form (no form state) we need to initialize some variables
+  if (!$form_state['storage']['template']) {
+    $sql = "SELECT * FROM {tripal_bulk_loader_template} WHERE template_id=%d";
+    $template = db_fetch_object(db_query($sql, $template_id));
+    $form_state['storage']['template_array'] = unserialize($template->template_array);
+    $form_state['storage']['template'] = $template;
+
+    $form_state['storage']['record2priority'] = array();
+    foreach ($form_state['storage']['template_array'] as $priority => $record_array) {
+      if (!is_array($record_array)) {
+        continue;
+      }
+      $form_state['storage']['record2priority'][$record_array['record_id']] = $priority;
+    }
+
+    $form_state['storage']['referring URL'] = $_SERVER["HTTP_REFERER"];
+  }
+  else {
+    $template = $form_state['storage']['template'];
+  }
+
+  // get the field from the path
+  if (!($_GET['record_id']===NULL || $_GET['field_index']===NULL)) {
+    $priority = $_GET['record_id'];
+    $field_index = $_GET['field_index'];
+    $template_field = $form_state['storage']['template_array'][$priority]['fields'][$field_index];
+    $form_state['storage']['original_field'] = $template_field;
+    $form_state['storage']['original_field']['priority'] = $priority;
+    $form_state['storage']['original_field']['field_index'] = $field_index;
+  }
+
+  $field_type = ($form_state['values']['field_type'])? $form_state['values']['field_type'] : $template_field['type'];
+
+  // Tables and default table
+  $tables = tripal_core_get_chado_tables();
+  if ($form_state['values']) {
+    $table = $form_state['values']['chado_table'];
+  }
+  else {
+    $table = $form_state['storage']['template_array'][$priority]['table'];
+  }
+
+
+  // Fields and foreign key mappings
+  $chado_fields = array();
+  $fk_options = array();
+  $fk_options['NULL'] = 'None';
+  $table_description = module_invoke_all('chado_' . $table . '_schema');
+  if ($field_type == 'foreign key') {
+    $foreign_field2table = array();
+    foreach ($table_description['foreign keys'] as $key_table => $key_array) {
+      foreach ($key_array['columns'] as $left_field => $right_field) {
+        $chado_fields[$left_field] = $left_field;
+        $foreign_field2table[$left_field] = $key_table;
+      }
+    }
+    reset($chado_fields);
+
+    // set default field
+    if (empty($chado_fields)) {
+      $field = NULL;
+    }
+    elseif ($chado_fields[$form_state['values']['chado_field']]) {
+      $field = $form_state['values']['chado_field'];
+    }
+    elseif ($template_field['field']) {
+      $field = $template_field['field'];
+    }
+    else {
+      $field = current($chado_fields);
+    }
+    //dpm($field, 'field');
+
+    // Foreign key options
+    $foreign_table = $foreign_field2table[$field];
+    if ($foreign_table) {
+      foreach ($form_state['storage']['record2priority'] as $record_name_ => $priority_ ) {
+        if (preg_match('/^' . $foreign_table . '$/', $form_state['storage']['template_array'][$priority_]['table'])) {
+          $fk_options[$record_name_] = $record_name_;
+        }
+      }
+    }
+  }
+  else {
+    foreach ($table_description['fields'] as $field_name => $field_array) {
+        $chado_fields[$field_name] = $field_name;
+    }
+  }
+
+//  dpm(array( 'tables' => $tables, 'default table' => $table, 'record name' => $record_name, 'priority' => $priority,
+//    'fields' => $chad_fields, 'default field' => $field, 'foreign field=>table' => $foreign_field2table,
+//    'table desc' => $table_description, 'foreign record options' => $fk_options, 'foreign table' => $foreign_table
+//    ), 'Variables');
+
+  // Start of Form Proper--------------------------------------------------------------
+
+  $form['template_name'] = array(
+    '#type' => 'item',
+    '#title' => 'Template',
+    '#value' => $template->name,
+  );
+
+  $form['template_id'] = array(
+    '#type' => 'hidden',
+    '#value' => $template_id,
+  );
+
+  $form['edit_fields'] = array(
+    '#type' => 'fieldset',
+    '#prefix' => '<div id="tripal_bulk_loader_template-edit_field">',
+    '#suffix' => '</div>',
+  );
+
+  $form['edit_fields']['field_type'] = array(
+    '#type' => 'radios',
+    '#title' => t('Type of Field'),
+    '#options' => array(
+      'table field' => t('Data Field: Fields which maps to a data file column'),
+      'constant' => t('Constant: Field which remains Constant throughout the data file'),
+      'foreign key' => t('Foreign Key: Fields which map to a record in another table'),
+    ),
+    '#required' => TRUE,
+    '#default_value' => $field_type,
+    '#ahah' => array(
+      'path' => 'admin/tripal/tripal_bulk_loader_template/edit_field_ahah',
+      'wrapper' => 'tripal_bulk_loader_template-edit_field',
+      'effect' => 'fade'
+    ),
+  );
+
+  // check template array for records then edit one more
+  if (!$form_state['storage']['record2priority']) {
+    $groups = array();
+  }
+  else {
+    $groups = array_flip($form_state['storage']['record2priority']);
+  }
+  $groups['NONE'] = 'Select a Record';
+  $groups['NEW'] = 'New Record';
+  $form['edit_fields']['field_group']  = array(
+    '#type' => 'select',
+    '#title' => 'Record',
+    '#description' => 'This is used to group a set of fields together allowing '
+      .'multiple records to be inserted into the same table per line of the data file',
+    '#options' => $groups,
+    '#default_value' => (preg_match('/(\d+|\w+)/', $form_state['values']['field_group'])) ? $form_state['values']['field_group'] : $priority,
+    '#ahah' => array(
+      'path' => 'admin/tripal/tripal_bulk_loader_template/edit_field_ahah',
+      'wrapper' => 'tripal_bulk_loader_template-edit_field',
+      'effect' => 'fade'
+    ),
+    '#required' => TRUE,
+  );
+
+  $form['edit_fields']['record_name'] = array(
+    '#type' => (preg_match('/NEW/', $form_state['values']['field_group'])) ? 'textfield' : 'hidden',
+    '#title' => 'Unique Record Name',
+    '#prefix' => '<div id="tripal_bulk_loader_template-edit_record">',
+    '#suffix' => '</div>',
+    '#default_value' => $form_state['values']['record_name'],
+  );
+
+  $form['edit_fields']['field_title'] = array(
+    '#type' => 'textfield',
+    '#title' => t('Human-readable Title for Field'),
+    '#default_value' => ($form_state['values']['field_title']) ? $form_state['values']['field_title'] : $template_field['title'],
+  );
+
+  // data file column
+  $form['edit_fields']['columns'] = array(
+    '#type' => 'fieldset',
+    '#title' => t('Data File Column'),
+    '#collapsible' => TRUE,
+    '#collapsed' => ($field_type == 'table field')? FALSE : TRUE,
+  );
+
+  /**
+  $form['edit_fields']['columns']['sheet_name'] = array(
+    '#type' => 'textfield',
+    '#title' => t('Worksheet'),
+    '#description' => t('Specify the name of the worksheet.'),
+    '#size' => 5,
+    '#default_value' => ($form_state['values']['sheet_name'])? $form_state['values']['sheet_name'] : $template_field['spreadsheet sheet'],
+  );
+  */
+
+  $form['edit_fields']['columns']['column_number'] = array(
+    '#type' => 'textfield',
+    '#title' => t('Column'),
+    '#description' => t('Specify the column in the data file that this field maps to where the first column is 1.'),
+    '#size' => 5,
+    '#default_value' => ($form_state['values']['column_number']) ? $form_state['values']['column_number'] : $template_field['spreadsheet column'],
+  );
+
+  $form['edit_fields']['columns']['column_exposed'] = array(
+    '#type' => 'checkbox',
+    '#title' => t('Allow Column to be set for each Bulk Loading Job'),
+    '#description' => t('Adds a textbox field to the Bulk Loader Page to allow users to set this value.'),
+    '#default_value' => ($form_state['values']['column_exposed']) ? $form_state['values']['column_exposed'] : $template_field['exposed'],
+  );
+
+  $form['edit_fields']['columns']['column_exposed_desc'] = array(
+    '#type' => 'textfield',
+    '#title' => t('Description for exposed field on bulk loading job'),
+    '#description' => t('This description should tell the user what column should be entered here.'),
+    '#default_value' => ($form_state['values']['column_exposed_desc']) ? $form_state['values']['column_exposed_desc'] : $template_field['exposed_description'],
+  );
+
+  // Global Value
+  $form['edit_fields']['constant'] = array(
+    '#type' => 'fieldset',
+    '#title' => t('Constant'),
+    '#collapsible' => TRUE,
+    '#collapsed' => ($field_type == 'constant')? FALSE : TRUE,
+  );
+
+  $form['edit_fields']['constant']['constant_value'] = array(
+    '#type' => 'textfield',
+    '#title' => t('Constant Value'),
+    '#description' => t('Specify the value you wish this field to have regardless of data file value.'),
+    '#default_value' => ($form_state['values']['constant_value']) ? $form_state['values']['constant_value'] : $template_field['constant value'],
+  );
+
+  $form['edit_fields']['constant']['constant_exposed'] = array(
+    '#type' => 'checkbox',
+    '#title' => t('Allow Constant to be set for each Bulk Loading Job'),
+    '#description' => t('Adds a textbox field to the Create Bulk Loader Form to allow users to set this value.'),
+    '#default_value' => ($form_state['values']['constant_exposed']) ? $form_state['values']['constant_exposed'] : $template_field['exposed'],
+  );
+
+  $form['edit_fields']['constant']['constant_validate'] = array(
+    '#type' => 'checkbox',
+    '#title' => t('Ensure value is in table'),
+    '#description' => t('Checks the database when a bulk loading job is created to ensure the value entered already exists in the database.'),
+    '#default_value' => ($form_state['values']['constant_validate']) ? $form_state['values']['constant_validate'] : $template_field['exposed_validate'],
+  );
+
+  // Foreign Key
+  $form['edit_fields']['foreign_key'] = array(
+    '#type' => 'fieldset',
+    '#title' => 'Foreign Key',
+    '#collapsible' => TRUE,
+    '#collapsed' => ($field_type == 'foreign key')? FALSE : TRUE,
+  );
+
+  $form['edit_fields']['foreign_key']['foreign_record'] = array(
+    '#type' => 'select',
+    '#title' => 'Record to refer to',
+    '#descripion' => 'Select the record that this foreign key shouold refer to. The record needs to already exist and be of the correct table.',
+    '#options' => $fk_options,
+  );
+
+  // Chado Field
+  $form['edit_fields']['chado'] = array(
+    '#type' => 'fieldset',
+    '#title' => t('Chado Field/Column Details'),
+    '#description' => t('Specify the Table/Field in chado that this field maps to.'),
+  );
+
+  $form['edit_fields']['chado']['chado_table'] = array(
+    '#type' => 'select',
+    '#title' => t('Chado Table'),
+    '#options' => $tables,
+    '#default_value' => $table,
+    '#ahah' => array(
+      'path' => 'admin/tripal/tripal_bulk_loader_template/edit_field_ahah',
+      'wrapper' => 'tripal_bulk_loader_template-edit_field',
+      'effect' => 'fade'
+      ),
+  );
+
+  $form['edit_fields']['chado']['chado_field'] = array(
+    '#type' => 'select',
+    '#title' => t('Chado Field/Column'),
+    '#options' => $chado_fields,
+    '#default_value' => ($form_state['values']['chado_field']) ? $form_state['values']['chado_field'] : $template_field['field'],
+    '#ahah' => array(
+      'path' => 'admin/tripal/tripal_bulk_loader_template/edit_field_ahah',
+      'wrapper' => 'tripal_bulk_loader_template-edit_field',
+      'effect' => 'fade'
+    ),
+  );
+
+  $form['edit_fields']['additional'] = array(
+    '#type' => 'fieldset',
+    '#title' => 'Additional Options',
+  );
+
+  $form['edit_fields']['additional']['required'] = array(
+    '#type' => 'checkbox',
+    '#title' => 'Make this file required',
+    '#default_value' => $template_field['required'],
+  );
+
+  $form['edit_fields']['additional']['regex_transform'] = array(
+    '#type' => 'fieldset',
+    '#title' => 'Transform Data File Value Rules',
+    '#collapsible' => TRUE,
+    '#collapsed' => (!$template_field['regex']['pattern']) ? TRUE : FALSE,
+  );
+
+  $transformation_msg = '<p>A transformation rule allows you to transform the original value '
+      .'(usually from a user submitted data file) into the form you would like it stored '
+      .'in the chado database. Each rule consists of a match pattern (a php regular expression '
+      .'which determines which replacement patterns are applied and captures regions of the '
+      .'original value) and a replacement pattern (a string which may contain capture references '
+      .'that describes what the new value should be). Each rule is applied to the result of the '
+      .'previous rule.<p>';
+  $form['edit_fields']['additional']['regex_transform']['regex_description'] = array(
+    '#type' => 'item',
+    '#value' => $transformation_msg,
+  );
+
+  $form['edit_fields']['additional']['regex_transform']['regex-data'] = array(
+    '#tree' => TRUE,
+  );
+  foreach ($template_field['regex']['pattern'] as $index => $pattern) {
+    $data_element = array(
+      'pattern' => array(
+        '#type' => 'item',
+        '#value' => $pattern,
+      ),
+      'replace' => array(
+        '#type' => 'item',
+        '#value' => $template_field['regex']['replace'][$index],
+      ),
+      'old_index' => array(
+        '#type' => 'hidden',
+        '#value' => $index,
+      ),
+      'new_index' => array(
+        '#type' => 'select',
+        '#options' => range(0, sizeof($template_field['regex']['pattern'])-1),
+        '#default_value' => $index,
+      ),
+      'id' => array(
+        '#type' => 'hidden',
+        '#value' => $index,
+      ),
+      'submit-delete' => array(
+        '#type' => 'submit',
+        '#value' => 'Delete Transformation',
+        '#name' => $index,
+      ),
+    );
+    $form['edit_fields']['additional']['regex_transform']['regex-data'][$index] = $data_element;
+  }
+
+  $form['edit_fields']['additional']['regex_transform']['submit-reorder_regex'] = array(
+    '#type' => 'submit',
+    '#value' => 'Save Transformation Rule Order'
+  );
+
+  $form['edit_fields']['additional']['regex_transform']['new_regex'] = array(
+    '#type' => 'fieldset',
+    '#title' => 'Add a new Transformation Rule',
+  );
+
+  $form['edit_fields']['additional']['regex_transform']['new_regex']['pattern'] = array(
+    '#type' => 'textfield',
+    '#title' => 'Match Pattern',
+    '#description' => 'You can use standard <b>php regular expressions</b> in this field to specify a '
+      .'pattern. Only if this pattern matches the value in the data file does the replacement '
+      .'pattern get applied to the value. To capture a section of your value for use in the '
+      .'replacement patten surround with round brackets. For example, <i>GI:(\d+)</i> will match '
+      .' NCBI gi numbers and will capture the numerical digits for use in the replacement pattern. '
+      .' To match and capture any value use <i>.*</i>',
+  );
+
+  $form['edit_fields']['additional']['regex_transform']['new_regex']['replace'] = array(
+    '#type' => 'textfield',
+    '#title' => 'Replacement Pattern',
+    '#description' => '<p>This pattern should contain the text you want to replace the match pattern '
+    .'mentioned above. It can include references of the form <b>\n</b> where n is the number of the '
+    .'capture in the match pattern. For example, \1 will be replaced with the text matched in your '
+    .'first set of round brackets.</p>',
+  );
+
+  if ($field_type == 'table field') {
+    $tab = '&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp';
+    $form['edit_fields']['additional']['regex_transform']['new_regex']['replace']['#description'] .= '<p>'
+      .'The following references are also available for data file fields: <b><#column:<i>number</i>#></b>. '
+      .'This allows you to substitute other data file values into the current field. For example, '
+      .'if you had the following line:<br />'
+      . $tab . 'SNP' . $tab . '15-Jan-2011' . $tab . '1' . $tab . '54' . $tab . 'Contig34355'
+      .'<br /> and your current field is for column #1 and you\'re inserting into the chado field '
+      .'feature.uniquename then you might want to add in the data to ensure your uniquename is '
+      .'unique. The Match Pattern is (.*) to select all the first column and the Replacement '
+      .'Pattern could be \1_<#column:2#> which would insert SNP_15-Jan-2011 into the database.</p>';
+  }
+
+  $form['edit_fields']['additional']['regex_transform']['new_regex']['submit-add_transform'] = array(
+    '#type' => 'submit',
+    '#value' => 'Add Transformation',
+  );
+
+  $form['edit_fields']['additional']['regex_transform']['test_regex'] = array(
+    '#type' => 'fieldset',
+    '#title' => 'Test Transformation Rules',
+  );
+
+  $form['edit_fields']['additional']['regex_transform']['test_regex']['test_string'] = array(
+    '#type' => 'textfield',
+    '#title' => 'Test Value',
+    '#description' => 'This should be a value that you expect the above transformation rules '
+      .'to be applied to.',
+    '#default_value' => $form_state['storage']['test_regex_test'],
+  );
+
+  $form['edit_fields']['additional']['regex_transform']['test_regex']['test_result'] = array(
+    '#type' => 'textfield',
+    '#title' => 'Test Result',
+    '#description' => 'This is the value that would be saved to the database after the above transformation '
+      .'riles were applied to the Test Value.',
+    '#default_value' => $form_state['storage']['test_regex_result'],
+  );
+
+  $form['edit_fields']['additional']['regex_transform']['test_regex']['submit-test'] = array(
+    '#type' => 'submit',
+    '#value' => 'Test Transformation Rules'
+  );
+
+  $form['edit_fields']['submit-edit_field'] = array(
+      '#type' => 'submit',
+      '#value' => 'Edit Field'
+  );
+
+  $form['edit_fields']['submit-cancel'] = array(
+      '#type' => 'submit',
+      '#value' => 'Cancel'
+  );
+
+  return $form;
+}
+
+/**
+ * Edit Field Form Submit
+ *
+ * @param $form
+ *   The form that was submitted
+ * @param $form_state
+ *   The values and storage for the form
+ */
+function tripal_bulk_loader_edit_template_field_form_submit($form, &$form_state) {
+
+  $op = $form_state['values'][ $form_state['clicked_button']['#name'] ];
+  //dpm($op, 'Operation Submitted');
+
+  //Clear Test
+  $form_state['storage']['test_regex_result'] = NULL;
+  $form_state['storage']['test_regex_test'] = NULL;
+
+  if (!$form_state['ahah_submission']) {
+    if ($op ==  'Edit Field') {
+
+      // If new record
+      if (preg_match('/NEW/', $form_state['values']['field_group'])) {
+        // add new record
+        $record_name = $form_state['values']['record_name'];
+        $priority = sizeof($form_state['storage']['template_array']) + 1;
+        $old_priority = $form_state['storage']['original_field']['priority'];
+        $field_index = $form_state['storage']['original_field']['field_index'];
+        $form_state['storage']['record2priority'][$record_name] = $priority;
+        $form_state['storage']['template_array'][$priority]['table'] = $form_state['values']['chado_table'];
+        $form_state['storage']['template_array'][$priority]['record_id'] = $record_name;
+
+      }
+      else {
+        $priority = $form_state['values']['field_group'];
+        $old_priority = $form_state['storage']['original_field']['priority'];
+        $field_index = $form_state['storage']['original_field']['field_index'];
+        $record_name = $form_state['storage']['record2priority'][$priority];
+      }
+
+      $field = $form_state['storage']['original_field'];
+      if ($form_state['values']['field_type'] == 'table field') {
+          $field['type'] = 'table field';
+          $field['title'] = $form_state['values']['field_title'];
+          $field['field'] = $form_state['values']['chado_field'];
+          $field['required'] = $form_state['values']['required'];
+          //$field['allowed values'] = empty by default;
+          $field['spreadsheet column'] = $form_state['values']['column_number'];
+          $field['exposed'] = $form_state['values']['column_exposed'];
+          $field['exposed_description'] = $form_state['values']['column_exposed_desc'];
+      }
+      elseif ($form_state['values']['field_type'] == 'constant') {
+          $field['type'] = 'constant';
+          $field['title'] = $form_state['values']['field_title'];
+          $field['field'] = $form_state['values']['chado_field'];
+          $field['required'] = $form_state['values']['required'];
+          //$field['allowed values'] = empty by default;
+          $field['constant value'] = $form_state['values']['constant_value'];
+          $field['exposed_validate'] = $form_state['values']['constant_validate'];
+          $field['exposed'] = $form_state['values']['constant_exposed'];
+      }
+      elseif ($form_state['values']['field_type'] == 'foreign key') {
+          $field['type'] = 'foreign key';
+          $field['title'] = $form_state['values']['field_title'];
+          $field['field'] = $form_state['values']['chado_field'];
+          $field['foreign key'] = $form_state['values']['foreign_record'];
+          $field['required'] = $form_state['values']['required'];
+      }
+
+      // Deal with any additional options
+
+      // if the record has changed...
+      $form_state['storage']['template_array'][$priority]['table'] = $form_state['values']['chado_table'];
+      if ($old_priority != $priority) {
+        $form_state['storage']['template_array'][$priority]['fields'][] = $field;
+        unset($form_state['storage']['template_array'][$old_priority]['fields'][$field_index]);
+
+        // if there are no fields left delete the old record
+        if (!$form_state['storage']['template_array'][$old_priority]['fields']) {
+          unset($form_state['storage']['template_array'][$old_priority]);
+        }
+      }
+      else {
+        $form_state['storage']['template_array'][$priority]['fields'][$field_index] = $field;
+      }
+
+      // Save Template
+      $form_state['storage']['template']->template_array = serialize($form_state['storage']['template_array']);
+      $success = drupal_write_record('tripal_bulk_loader_template', $form_state['storage']['template'], array('template_id'));
+
+      if ($success) {
+        drupal_set_message(t('Successfully Updated Field'));
+        drupal_set_message(t('Template Saved.'));
+
+        $path = explode('?', $form_state['storage']['referring URL']);
+        parse_str($path[1], $query);
+        $query['template_id'] = $form_state['storage']['template']->template_id;
+        drupal_goto($path[0], $query);
+      }
+      else {
+        drupal_set_message(t('Unable to Save Template!'), 'error');
+        watchdog('T_bulk_loader',
+          'Unable to save bulk loader template: %template',
+          array('%template' => print_r($form_state['storage']['template'], TRUE)),
+          WATCHDOG_ERROR
+        );
+      }
+
+    }
+    elseif ($op ==  'Cancel') {
+
+        $path = explode('?', $form_state['storage']['referring URL']);
+        parse_str($path[1], $query);
+        $query['template_id'] = $form_state['storage']['template']->template_id;
+        drupal_goto($path[0], $query);
+
+    }
+    elseif ($op == 'Add Transformation') {
+
+      // Add transformation rule to original field
+      $form_state['storage']['original_field']['regex']['pattern'][] = '/' . $form_state['values']['pattern'] . '/';
+      $form_state['storage']['original_field']['regex']['replace'][] = $form_state['values']['replace'];
+
+      // Add original field back into template
+      $priority = $form_state['storage']['original_field']['priority'];
+      $field_index = $form_state['storage']['original_field']['field_index'];
+      $form_state['storage']['template_array'][$priority]['fields'][$field_index] = $form_state['storage']['original_field'];
+
+      // Save Template
+      $form_state['storage']['template']->template_array = serialize($form_state['storage']['template_array']);
+      $success = drupal_write_record('tripal_bulk_loader_template', $form_state['storage']['template'], array('template_id'));
+
+      if ($success) {
+        drupal_set_message(t('Successfully Added Transformation Rule'));
+        drupal_set_message(t('Template Saved.'));
+      }
+      else {
+        drupal_set_message(t('Unable to Save Template!'), 'error');
+        watchdog('T_bulk_loader',
+          'Unable to save bulk loader template: %template',
+          array('%template' => print_r($form_state['storage']['template'], TRUE)),
+          WATCHDOG_ERROR
+        );
+      }
+    }
+    elseif ($op == 'Save Transformation Rule Order') {
+
+      // Generate new regex array
+      $new_regex = array();
+      $old_regex = $form_state['storage']['original_field']['regex'];
+      foreach ($form_state['values']['regex-data'] as $key => $element) {
+        $new_regex['pattern'][ $element['new_index'] ] = $old_regex['pattern'][ $element['old_index'] ];
+        $new_regex['replace'][ $element['new_index'] ] = $old_regex['replace'][ $element['old_index'] ];
+      }
+
+      // sort new regex arrays
+      asort($new_regex['pattern']);
+      asort($new_regex['replace']);
+
+      // Add back to original field
+      $form_state['storage']['original_field']['regex'] = $new_regex;
+      $priority = $form_state['storage']['original_field']['priority'];
+      $field_index = $form_state['storage']['original_field']['field_index'];
+      $form_state['storage']['template_array'][$priority]['fields'][$field_index] = $form_state['storage']['original_field'];
+
+      // Save Template
+      $form_state['storage']['template']->template_array = serialize($form_state['storage']['template_array']);
+      $success = drupal_write_record('tripal_bulk_loader_template', $form_state['storage']['template'], array('template_id'));
+
+      if ($success) {
+        drupal_set_message(t('Successfully Reordered Transformation Rules'));
+        drupal_set_message(t('Template Saved.'));
+      }
+      else {
+        drupal_set_message(t('Unable to Save Template!'), 'error');
+        watchdog('T_bulk_loader',
+          'Unable to save bulk loader template: %template',
+          array('%template' => print_r($form_state['storage']['template'], TRUE)),
+          WATCHDOG_ERROR
+        );
+      }
+    }
+    elseif ($op == 'Delete Transformation') {
+
+      // Unset regex rule
+      $index = $form_state['clicked_button']['#name'];
+      unset($form_state['storage']['original_field']['regex']['pattern'][$index]);
+      unset($form_state['storage']['original_field']['regex']['replace'][$index]);
+
+      $priority = $form_state['storage']['original_field']['priority'];
+      $field_index = $form_state['storage']['original_field']['field_index'];
+      $form_state['storage']['template_array'][$priority]['fields'][$field_index] = $form_state['storage']['original_field'];
+
+      // Save Template
+      $form_state['storage']['template']->template_array = serialize($form_state['storage']['template_array']);
+      $success = drupal_write_record('tripal_bulk_loader_template', $form_state['storage']['template'], array('template_id'));
+
+      if ($success) {
+        drupal_set_message(t('Successfully Reordered Transformation Rules'));
+        drupal_set_message(t('Template Saved.'));
+      }
+      else {
+        drupal_set_message(t('Unable to Save Template!'), 'error');
+        watchdog('T_bulk_loader',
+          'Unable to save bulk loader template: %template',
+          array('%template' => print_r($form_state['storage']['template'], TRUE)),
+          WATCHDOG_ERROR
+        );
+      }
+
+    }
+    elseif ($op == 'Test Transformation Rules') {
+
+      $patterns = $form_state['storage']['original_field']['regex']['pattern'];
+      $replaces = $form_state['storage']['original_field']['regex']['replace'];
+      $test_string = $form_state['values']['test_string'];
+      $form_state['storage']['test_regex_result'] = preg_replace($patterns, $replaces, $test_string);
+      $form_state['storage']['test_regex_test'] = $test_string;
+    }
+  }
+
+}
+
+/**
+ * @section
+ * AHAH Callbacks
+ */
+
+/**
+ * AHAH Function: Replace $form['add_fields'] in tripal_bulk_loader_add_template_field_form
+ *
+ * @return
+ *  JSON Data printed to the screen
+ */
+function tripal_bulk_loader_add_field_ahah() {
+
+  $form_state = array('storage' => NULL, 'submitted' => FALSE);
+  $form_build_id = filter_xss($_POST['form_build_id']);
+  $form = form_get_cache($form_build_id, $form_state);
+  $args = $form['#parameters'];
+  $form_id = array_shift($args);
+  $form_state['post'] = $form['#post'] = $_POST;
+
+  // Enable the submit/validate handlers to determine whether AHAH-submittted.
+  $form_state['ahah_submission'] = TRUE;
+
+  $form['#programmed'] = $form['#redirect'] = FALSE;
+  drupal_process_form($form_id, $form, $form_state);
+  $form = drupal_rebuild_form($form_id, $form_state, $args, $form_build_id);
+
+  $form_element = $form['add_fields'];
+  // Remove the wrapper so we don't double it up.
+  //unset($form_element['#prefix'], $form_element['#suffix']);
+
+  $output = theme('status_messages');
+  $output .= drupal_render($form_element);
+
+  // Final rendering callback.
+  print drupal_json(array('status' => TRUE, 'data' => $output));
+  exit();
+
+}
+
+/**
+ * AHAH Function: Replace $form['edit_fields'] in tripal_bulk_loader_edit_template_field_form
+ *
+ * @return
+ *  JSON Data printed to the screen
+ */
+function tripal_bulk_loader_edit_field_ahah() {
+
+  $form_state = array('storage' => NULL, 'submitted' => FALSE);
+  $form_build_id = filter_xss($_POST['form_build_id']);
+  $form = form_get_cache($form_build_id, $form_state);
+  $args = $form['#parameters'];
+  $form_id = array_shift($args);
+  $form_state['post'] = $form['#post'] = $_POST;
+
+  // Enable the submit/validate handlers to determine whether AHAH-submittted.
+  $form_state['ahah_submission'] = TRUE;
+
+  $form['#programmed'] = $form['#redirect'] = FALSE;
+  drupal_process_form($form_id, $form, $form_state);
+  $form = drupal_rebuild_form($form_id, $form_state, $args, $form_build_id);
+
+  $form_element = $form['edit_fields'];
+  // Remove the wrapper so we don't double it up.
+  unset($form_element['#prefix'], $form_element['#suffix']);
+
+  $output = theme('status_messages');
+  $output .= drupal_render($form_element);
+
+  // Final rendering callback.
+  print drupal_json(array('status' => TRUE, 'data' => $output));
+  exit();
+
+}

+ 11 - 0
tripal_bulk_loader/tripal_bulk_loader.coder_ignores.txt

@@ -0,0 +1,11 @@
+; The file should be formatted this way :
+; file:line:warning-type
+; where warning-type is one of security, style, sql, i18n, comment, etc.
+
+; all variables are filtered
+tripal_bulk_loader.admin.inc:398:security
+tripal_bulk_loader.constants.inc::260:security
+
+; doesn't need to be filtered b/c all variables set in code and not subjected to
+; user input
+tripal_bulk_loader.constants.inc:376:security

+ 9 - 8
tripal_bulk_loader/tripal_bulk_loader.constants.inc

@@ -143,7 +143,7 @@ function tripal_bulk_loader_set_constants_form($form_state, $node) {
       '#type' => 'item',
       '#value' => t('You have already added constants to this bulk loading job. Each '
         .'row in the following table represents a set of constants. Each set will be used '
-        .'to load your spreadsheet with the specified template resulting in the each record '
+        .'to load your data file with the specified template resulting in the each record '
         .'in the template to be loaded x number of times where there are x sets of '
         .'constants (rows in the following table).')
     );
@@ -160,15 +160,15 @@ function tripal_bulk_loader_set_constants_form($form_state, $node) {
           $group = $field['group_id'];
           $form['exposed_fields']['existing'][$group][$index] = array(
             '#type' => 'markup',
-            '#value' => $field['value'],
+            '#value' => filter_xss($field['value']),
           );
         }
       }
 
       $form['exposed_fields']['existing'][$group]['delete'] = array(
         '#type' => 'markup',
-        '#value' => l(t('Edit'), 'node/' . $node->nid . '/constants/' . $group . '/edit') . '<br />'  .
-          l(t('Delete'), 'node/' . $node->nid . '/constants/' . $group . '/delete'),
+        '#value' => filter_xss(l(t('Edit'), 'node/' . $node->nid . '/constants/' . $group . '/edit') . '  |  '  .
+          l(t('Delete'), 'node/' . $node->nid . '/constants/' . $group . '/delete')),
       );
 
     }
@@ -211,7 +211,7 @@ function tripal_bulk_loader_set_constants_form($form_state, $node) {
             $form['exposed_fields']['new'][$record_id . '-' . $field_id] = array(
               '#type' => 'textfield',
               '#title' => t('%title', array('%title' => $field['title']) ),
-              '#description' => t('Enter the case-sensitive value of this constant for your spreadsheet'),
+              '#description' => t('Enter the case-sensitive value of this constant for your data file'),
               '#default_value' => (isset($node->constants[$record_id][$field_id]['value'])) ? $node->constants[$record_id][$field_id]['value'] : $field['constant value'],
             );
           break;
@@ -364,6 +364,7 @@ function theme_tripal_bulk_loader_set_constants_form($form) {
       $i++;
     }
     //drupal_add_tabledrag('mytable', 'order', 'sibling', 'weight-group');
+    // @coder-ignore: no user input thus don't need to filter
     $form['exposed_fields']['existing'] = array(
       '#type' => 'markup',
       '#value' => theme('table', $header, $rows, array('id' => 'mytable')) . '<br />'
@@ -439,7 +440,7 @@ function tripal_bulk_loader_edit_constant_set_form($form_state, $node, $group_id
             $form[$record_id . '-' . $field_id] = array(
               '#type' => 'textfield',
               '#title' => t('%title', array('%title' => $field['title'])),
-              '#description' => t('Enter the case-sensitive value of this constant for your spreadsheet'),
+              '#description' => t('Enter the case-sensitive value of this constant for your data file'),
               '#default_value' => (isset($node->constants[$group_id][$record_id][$field_id]['value'])) ? $node->constants[$group_id][$record_id][$field_id]['value'] : $field['constant value'],
             );
           break;
@@ -509,7 +510,7 @@ function tripal_bulk_loader_edit_constant_set_form_submit($form, $form_state) {
         );
       }
     }
-    drupal_set_message('The constant set was successfully updated.');
+    drupal_set_message(t('The constant set was successfully updated.'));
 
   }
 
@@ -562,7 +563,7 @@ function tripal_bulk_loader_delete_constant_set_form_submit($form, $form_state)
   $nid = $form_state['values']['nid'];
   if ($nid && $form_state['values']['confirm']) {
     db_query("DELETE FROM {tripal_bulk_loader_constants} WHERE nid=%d AND group_id=%d", $nid, $group_id);
-    drupal_set_message('Constant set successfully deleted.');
+    drupal_set_message(t('Constant set successfully deleted.'));
   }
 
 }

+ 2 - 2
tripal_bulk_loader/tripal_bulk_loader.install

@@ -9,14 +9,14 @@
  * Implements hook_install
  */
 function tripal_bulk_loader_install() {
-   drupal_install_schema('tripal_bulk_loader');
+  drupal_install_schema('tripal_bulk_loader');
 }
 
 /**
  * Implements hook_uninstall
  */
 function tripal_bulk_loader_uninstall() {
-   drupal_uninstall_schema('tripal_bulk_loader');
+  drupal_uninstall_schema('tripal_bulk_loader');
 }
 
 /**

+ 163 - 33
tripal_bulk_loader/tripal_bulk_loader.loader.inc

@@ -14,6 +14,10 @@
 function tripal_bulk_loader_add_loader_job_form($form_state, $node) {
   $form = array();
 
+  if (($node->job_status == 'Loading...') AND (variable_get('tripal_bulk_loader_transactions',   'row') != 'none')) {
+    drupal_set_message("Job Progress and Loading Summary will only be updated at the end of each constant set.","warning");
+  }
+
   $form['nid'] = array(
     '#type' => 'hidden',
     '#value' => $node->nid,
@@ -135,13 +139,18 @@ function tripal_bulk_loader_load_data($nid) {
   $default_data = array();
   $field2column = array();
   $record2priority = array();
+  $tables = array();
 
   foreach ($node->template->template_array as $priority => $record_array) {
     if (!is_array($record_array)) {
       continue;
     }
 
-    //watchdog('T_bulk_loader','1)'.$record_array['record_id']." => \n<pre>".print_r($record_array,TRUE).'</pre>', array(), WATCHDOG_NOTICE);
+    // Add tables being inserted into to a list to be treated differently
+    // this is used to acquire locks on these tables
+    if (preg_match('/insert/', $record_array['mode'])) {
+      $tables[$record_array['table']] = $record_array['table'];
+    }
 
     foreach ($record_array['fields'] as $field_index => $field_array) {
 
@@ -235,7 +244,11 @@ function tripal_bulk_loader_load_data($nid) {
     //print "\nField to Column Mapping: ".print_r($field2column, TRUE)."\n";
 
     // Parse File adding records as we go ========================================================
+
+    // Open File
     $file_handle = fopen($node->file, 'r');
+
+    // Set defaults
     if (preg_match('/(t|true|1)/', $node->file_has_header)) {
       fgets($file_handle, 4096);
     }
@@ -244,8 +257,39 @@ function tripal_bulk_loader_load_data($nid) {
     $num_errors = 0;
     $interval = intval($total_lines * 0.10);
     if ($interval == 0) {
-       $interval = 1;
-     }
+      $interval = 1;
+    }
+
+    // Start Transaction
+    switch (variable_get('tripal_bulk_loader_transactions', 'row')) {
+      case "none":
+        break;
+      case "all":
+        tripal_db_start_transaction();
+        $transactions = TRUE;
+        $savepoint = "";
+        break;
+      case "row":
+        tripal_db_start_transaction();
+        $transactions = TRUE;
+        $savepoint = "last_row_complete";
+        break;
+    }
+
+    // Disable triggers
+    $triggers_disabled = FALSE;
+    if ($transactions AND variable_get('tripal_bulk_loader_disable_triggers', TRUE)) {
+      $triggers_disabled = TRUE;
+      chado_query("SET CONSTRAINTS ALL DEFERRED");
+    }
+
+    // Acquire Locks
+    $lockmode = variable_get('tripal_bulk_loader_lock', 'ROW EXCLUSIVE');
+    foreach ($tables as $table) {
+      chado_query("LOCK TABLE %s IN %s MODE", $table, $lockmode);
+    }
+
+    tripal_bulk_loader_progress_bar(0,$total_lines);
     while (!feof($file_handle)) {
 
       // Clear variables
@@ -267,7 +311,7 @@ function tripal_bulk_loader_load_data($nid) {
       if ($node->job_id and $num_lines % $interval == 0) {
         // percentage of lines processed for the current group
         $group_progress = round(($num_lines/$total_lines)*100);
-
+        tripal_bulk_loader_progress_bar($num_lines,$total_lines);
         // percentage of lines processed for all groups
         // <previous group index> * 100 + <current group progress>
         // --------------------------------------------------------
@@ -276,14 +320,6 @@ function tripal_bulk_loader_load_data($nid) {
         // and had a group percentage of 50% then the job progress would be
         // (2*100 + 50%) / 3 = 250%/3 = 83%
         $job_progress = round(((($group_index-1)*100)+$group_progress)/$total_num_groups);
-
-        /**
-          print "\nProgress Update:\n"
-            ."\t- ".$num_lines." lines have been processed for the current constant set.\n"
-            ."\t- ".$group_progress."% of the lines in the file have been processed for the current constant set.\n"
-            ."\t- ".$job_progress."% of the current job has been completed.\n";
-        */
-
         tripal_job_set_progress($node->job_id, $job_progress);
       }
 
@@ -293,11 +329,46 @@ function tripal_bulk_loader_load_data($nid) {
       foreach ($data_keys as $priority) {
         $status = process_data_array_for_line($priority, $data, $default_data, $field2column, $record2priority, $line, $nid, $num_lines, $group_index);
         if (!$status ) {
-          $loaded_without_errors = FALSE;
+          // Encountered an error
+          if ($transactions) {
+            tripal_db_rollback_transaction($savepoint);
+          }
+          $failed = TRUE;
+          break;
         }
       } // end of foreach table in default data array
 
+      if ($failed) {
+        break;
+      }
+      else {
+        // Row inserted successfully
+        // Set savepoint if supplied
+        if ($savepoint) {
+          if ($num_lines == 1) {
+            tripal_db_set_savepoint_transaction($savepoint);
+          }
+          else {
+            // Tell it to remove the previous savepoint of the same name
+            tripal_db_set_savepoint_transaction($savepoint, TRUE);
+          }
+        }
+      }
+
     } //end of foreach line of file
+
+    // END Transaction
+    if ($transactions) {
+      // end the transaction
+      tripal_db_commit_transaction();
+    }
+
+    if ($failed) {
+      $loaded_without_errors = FALSE;
+      break;
+    }
+
+    tripal_bulk_loader_progress_bar($total_lines,$total_lines);
   } //end of foreach constant set
 
   // check that data was inserted and update job_status
@@ -310,11 +381,11 @@ function tripal_bulk_loader_load_data($nid) {
 
   // set the status of the job (in the node not the tripal jobs)
   if ($loaded_without_errors) {
-      $status = 'Loading Completed Successfully';
-    }
-    else {
-      $status = 'Errors Encountered';
-      }
+    $status = 'Loading Completed Successfully';
+  }
+  else {
+    $status = 'Errors Encountered';
+  }
   db_query("UPDATE {tripal_bulk_loader} SET job_status='%s' WHERE nid=%d", $status, $nid);
 
 }
@@ -337,17 +408,17 @@ function process_data_array_for_line($priority, &$data, &$default_data, $field2c
   if ($table_data['need_further_processing']) {
     $values = tripal_bulk_loader_add_spreadsheetdata_to_values($values, $line, $field2column[$priority]);
     if (!$values) {
-      watchdog('T_bulk_loader', 'Line ' . $line_num . ' Spreadsheet Added:' . print_r($values, TRUE), array(), WATCHDOG_NOTICE);
+      //watchdog('T_bulk_loader', 'Line ' . $line_num . ' Data File Added:' . print_r($values, TRUE), array(), WATCHDOG_NOTICE);
     }
 
     $values = tripal_bulk_loader_add_foreignkey_to_values($values, $data, $record2priority);
     if (!$values) {
-      watchdog('T_bulk_loader', 'Line ' . $line_num . ' FK Added:<pre>' . print_r($values, TRUE) . print_r($data[$priority], TRUE) . '</pre>', array(), WATCHDOG_NOTICE);
+      //watchdog('T_bulk_loader', 'Line ' . $line_num . ' FK Added:<pre>' . print_r($values, TRUE) . print_r($data[$priority], TRUE) . '</pre>', array(), WATCHDOG_NOTICE);
     }
   }
   $values = tripal_bulk_loader_regex_tranform_values($values, $table_data, $line);
   if (!$values) {
-    watchdog('T_bulk_loader', 'Line ' . $line_num . ' Regex:<pre>' . print_r($values, TRUE) . print_r($table_data, TRUE) . '</pre>' . '</pre>', array(), WATCHDOG_NOTICE);
+    //watchdog('T_bulk_loader', 'Line ' . $line_num . ' Regex:<pre>' . print_r($values, TRUE) . print_r($table_data, TRUE) . '</pre>' . '</pre>', array(), WATCHDOG_NOTICE);
   }
 
   if (!$values) {
@@ -366,9 +437,9 @@ function process_data_array_for_line($priority, &$data, &$default_data, $field2c
       // a field is considered missing if it cannot be null and there is no default
       // value for it or it is of type 'serial'
       if ($def['not null'] == 1 and !array_key_exists($field, $insert_values) and !isset($def['default']) and strcmp($def['type'], serial)!=0) {
-         $msg = 'Line ' . $line_num . ' ' . $table_data['record_id'] . ' (' . $table_data['mode'] . ') Missing Database Required Value: ' . $table . '.' . $field;
-         watchdog('T_bulk_loader', $msg, array(), WATCHDOG_NOTICE);
-         $data[$priority]['error'] = TRUE;
+        $msg = 'Line ' . $line_num . ' ' . $table_data['record_id'] . ' (' . $table_data['mode'] . ') Missing Database Required Value: ' . $table . '.' . $field;
+        watchdog('T_bulk_loader', $msg, array(), WATCHDOG_NOTICE);
+        $data[$priority]['error'] = TRUE;
       }
     }
   } //end of if optional record
@@ -419,9 +490,9 @@ function process_data_array_for_line($priority, &$data, &$default_data, $field2c
 
 
   if (!preg_match('/select/', $table_data['mode'])) {
-    //watchdog('T_bulk_loader',$header.': Inserting:'.print_r($values, TRUE), array(), WATCHDOG_NOTICE);
-    if (variable_get('tripal_bulk_loader_prepare',TRUE)) {
-      $options = array('statement_name' => $priority);
+    // Use prepared statement?
+    if (variable_get('tripal_bulk_loader_prepare', TRUE)) {
+      $options = array('statement_name' => 'record_' . $priority);
       if ($line_num == 1 && $group_index == 1) {
         $options['prepare'] = TRUE;
       }
@@ -430,6 +501,11 @@ function process_data_array_for_line($priority, &$data, &$default_data, $field2c
       $options = array();
     }
 
+    // Skip tripal_core_chado_insert() built-in validation?
+    if (variable_get('tripal_bulk_loader_skip_validation', FALSE)) {
+      $options['skip_validation'] = TRUE;
+    }
+
     $record = tripal_core_chado_insert($table, $values, $options);
 
     if (!$record) {
@@ -482,6 +558,7 @@ function process_data_array_for_line($priority, &$data, &$default_data, $field2c
       $msg = 'Line ' . $line_num . ' ' . $table_data['record_id'] . ' (' . $table_data['mode'] . ') No Matching record in ' . $table . ' where values:' . print_r($values, TRUE);
       watchdog('T_bulk_loader', $msg, array(), WATCHDOG_WARNING);
       $data[$priority]['error'] = TRUE;
+      $no_errors = FALSE;
     }
   }
   return $no_errors;
@@ -564,8 +641,8 @@ function tripal_bulk_loader_regex_tranform_values($values, $table_data, $line) {
 
   foreach ($table_data['regex_transform'] as $field => $regex_array) {
     if (!is_array($regex_array['replace'])) {
-       continue;
-     }
+      continue;
+    }
 
     //print 'Match:'.print_r($regex_array['pattern'],TRUE)."\n";
     //print 'Replace:'.print_r($regex_array['replace'],TRUE)."\n";
@@ -609,8 +686,8 @@ function tripal_bulk_loader_flatten_array($values) {
     if (is_array($v)) {
       $vstr = array();
       foreach ($v as $vk => $vv) {
-        if (strlen($vv) > 20) {
-          $vstr[] = $vk . '=>' . substr($vv, 0, 20) . '...';
+        if (drupal_strlen($vv) > 20) {
+          $vstr[] = $vk . '=>' . drupal_substr($vv, 0, 20) . '...';
         }
         else {
           $vstr[] = $vk . '=>' . $vv;
@@ -618,11 +695,64 @@ function tripal_bulk_loader_flatten_array($values) {
       }
       $v = '{' . implode(',', $vstr) . '}';
     }
-    elseif (strlen($v) > 20) {
-      $v = substr($v, 0, 20) . '...';
+    elseif (drupal_strlen($v) > 20) {
+      $v = drupal_substr($v, 0, 20) . '...';
     }
     $flattened_values[] = $k . '=>' . $v;
   }
 
   return implode(', ', $flattened_values);
 }
+
+/**
+ * Used to display loader progress to the user
+ */
+function tripal_bulk_loader_progress_bar($current=0, $total=100, $size=50) {
+
+  // First iteration
+  if($current == 0) {
+    $new_bar = TRUE;
+    fputs(STDOUT,"Progress:\n");
+  }
+
+  //Percentage round off for a more clean, consistent look
+  $perc = round(($current/$total)*100,2);
+  // percent indicator must be four characters, if shorter, add some spaces
+  for($i=strlen($perc); $i<=4; $i++) {
+    $perc = ' '.$perc;
+  }
+
+  $total_size = $size + $i + 3 + 2;
+  // if it's not first go, remove the previous bar
+  if(!$new_bar) {
+    for($place = $total_size; $place > 0; $place--) {
+      // echo a backspace (hex:08) to remove the previous character
+      echo "\x08";
+    }
+  }
+
+  // output the progess bar as it should be
+  // Start with a border
+  echo '[';
+  for($place = 0; $place <= $size; $place++) {
+    // output "full" spaces if this portion is completed
+    if($place <= ($current / $total * $size)) {
+      echo '|';
+    }
+    else {
+      // Otherwise empty space
+      echo '-';
+    }
+  }
+  // End with a border
+  echo ']';
+
+  // end a bar with a percent indicator
+  echo " $perc%";
+
+  // if it's the end, add a new line
+  if($current == $total) {
+    echo "\n";
+  }
+
+}

+ 0 - 733
tripal_bulk_loader/tripal_bulk_loader.loader.inc.orig

@@ -1,733 +0,0 @@
-<?php
-
-/**
- * @file
- * @todo Add file header description
- */
-
-/**
- * Add Loader Job Form
- *
- * This form is meant to be included on the node page to allow users to submit/re-submit
- * loading jobs
- */
-function tripal_bulk_loader_add_loader_job_form($form_state, $node) {
-  $form = array();
-
-  $form['nid'] = array(
-    '#type' => 'hidden',
-    '#value' => $node->nid,
-  );
-
-  $form['file'] = array(
-    '#type' => 'hidden',
-    '#value' => $node->file
-  );
-
-  $form['job_id'] = array(
-    '#type' => 'hidden',
-    '#value' => $node->job_id,
-  );
-
-  $form['submit'] = array(
-    '#type' => 'submit',
-    '#value' => ($node->job_id) ? 'Re-Submit Job' : 'Submit Job',
-  );
-
-  $form['submit-cancel'] = array(
-    '#type' => ($node->job_id)? 'submit' : 'hidden',
-    '#value' => 'Cancel Job',
-  );
-
-  $form['submit-revert'] = array(
-    '#type' => ($node->job_id) ? 'submit' : 'hidden',
-    '#value' => 'Revert',
-  );
-
-  return $form;
-}
-
-/**
- * Add Loader Job Form (Submit)
- */
-function tripal_bulk_loader_add_loader_job_form_submit($form, $form_state) {
-  global $user;
-
-  if (preg_match('/Submit Job/', $form_state['values']['op'])) {
-    //Submit Tripal Job
-<<<<<<< HEAD
-    $job_args[1] = $form_state['values']['nid'];
-    if (is_readable($form_state['values']['file'])) {
-      $fname = basename($form_state['values']['file']);
-      $job_id = tripal_add_job("Bulk Loading Job: $fname", 'tripal_bulk_loader', 'tripal_bulk_loader_load_data', $job_args, $user->uid);
-
-      // add job_id to bulk_loader node
-      $success = db_query("UPDATE {tripal_bulk_loader} SET job_id=%d WHERE nid=%d", $job_id, $form_state['values']['nid']);
-
-      // change status
-      db_query("UPDATE {tripal_bulk_loader} SET job_status='%s' WHERE nid=%d", 'Submitted to Queue', $form_state['values']['nid']);
-    }
-    else {
-      drupal_set_message(t("Can not open %file. Job not scheduled.", array('%file' => $form_state['values']['file'])));
-    }
-  }
-  elseif (preg_match('/Re-Submit Job/', $form_state['values']['op'])) {
-=======
-		$job_args[1] = $form_state['values']['nid'];
-		if (is_readable($form_state['values']['file'])) {
-			$fname = basename($form_state['values']['file']);
-			$job_id = tripal_add_job("Bulk Loading Job: $fname",'tripal_bulk_loader', 'tripal_bulk_loader_load_data', $job_args, $user->uid);
-
-			// add job_id to bulk_loader node
-      $success = db_query("UPDATE {tripal_bulk_loader} SET job_id=%d WHERE nid=%d", $job_id, $form_state['values']['nid']);
-
-      // change status
-      db_query("UPDATE tripal_bulk_loader SET job_status='%s' WHERE nid=%d",'Submitted to Queue', $form_state['values']['nid']);
-		} else {
-			drupal_set_message("Can not open ".$form_state['values']['file'].". Job not scheduled.");
-		}
-  } elseif (preg_match('/Re-Submit Job/', $form_state['values']['op'])) {
->>>>>>> 6.x-0.4-dev
-    tripal_jobs_rerun($form_state['values']['job_id']);
-    db_query("UPDATE {tripal_bulk_loader} SET job_status='%s' WHERE nid=%d", 'Submitted to Queue', $form_state['values']['nid']);
-  }
-  elseif (preg_match('/Cancel Job/', $form_state['values']['op'])) {
-    db_query("UPDATE {tripal_bulk_loader} SET job_status='%s' WHERE nid=%d", 'Job Cancelled', $form_state['values']['nid']);
-    tripal_jobs_cancel($form_state['values']['job_id']);
-<<<<<<< HEAD
-  }
-  elseif (preg_match('/Revert/', $form_state['values']['op'])) {
-=======
-  } elseif (preg_match('/Revert/', $form_state['values']['op'])) {
->>>>>>> 6.x-0.4-dev
-
-    // Remove the records from the database that were already inserted
-    $resource = db_query('SELECT * FROM {tripal_bulk_loader_inserted} WHERE nid=%d ORDER BY tripal_bulk_loader_inserted_id DESC', $form_state['values']['nid']);
-    while ($r = db_fetch_object($resource)) {
-      $ids = preg_split('/,/', $r->ids_inserted);
-      db_query('DELETE FROM %s WHERE %s IN (%s)', $r->table_inserted_into, $r->table_primary_key, $r->ids_inserted);
-      $result = db_fetch_object(db_query('SELECT true as present FROM %s WHERE %s IN (%s)', $r->table_inserted_into, $r->table_primary_key, $r->ids_inserted));
-      if (!$result->present) {
-        drupal_set_message(t('Successfully Removed data Inserted into the %tableto table.', array('%tableto' => $r->table_inserted_into)));
-        db_query('DELETE FROM {tripal_bulk_loader_inserted} WHERE tripal_bulk_loader_inserted_id=%d', $r->tripal_bulk_loader_inserted_id);
-      }
-      else {
-        drupal_set_message(t('Unable to remove data Inserted into the %tableto table!', array('%tableto' => $r->table_inserted_into)), 'error');
-      }
-    }
-
-    // reset status
-    db_query("UPDATE {tripal_bulk_loader} SET job_status='%s' WHERE nid=%d", 'Reverted -Data Deleted', $form_state['values']['nid']);
-  }
-
-}
-
-/**
- * Tripal Bulk Loader
- *
- * This is the function that's run by tripal_launch_jobs to bulk load chado data.
- *
- * @param $nid
- *   The Node ID of the bulk loading job node to be loaded. All other needed data is expected to be
- *   in the node (ie: template ID and file)
- *
- * Note: Instead of returning a value this function updates the tripal_bulk_loader.status.
- *   Errors are thrown through watchdog and can be viewed at admin/reports/dblog.
- */
-function tripal_bulk_loader_load_data($nid) {
-
-  // ensure no timeout
-  set_time_limit(0);
-
-  // set the status of the job (in the node not the tripal jobs)
-  db_query("UPDATE {tripal_bulk_loader} SET job_status='%s' WHERE nid=%d", 'Loading...', $nid);
-
-
-<<<<<<< HEAD
-=======
-
->>>>>>> 6.x-0.4-dev
-  $node = node_load($nid);
-  print "Template: " . $node->template->name . " (" . $node->template_id . ")\n";
-
-  $total_lines = trim(`wc --lines < $node->file`);
-<<<<<<< HEAD
-  print "File: " . $node->file . " (" . $total_lines . " lines)\n";
-=======
-  print "File: ".$node->file." (".$total_lines." lines)\n";
->>>>>>> 6.x-0.4-dev
-
-  // Prep Work ==================================================================================
-  $loaded_without_errors = TRUE;
-
-  // Generate default values array
-  $default_data = array();
-  $field2column = array();
-  $record2priority = array();
-
-  foreach ($node->template->template_array as $priority => $record_array) {
-    if (!is_array($record_array)) {
-      continue;
-    }
-
-    //watchdog('T_bulk_loader','1)'.$record_array['record_id']." => \n<pre>".print_r($record_array,TRUE).'</pre>', array(), WATCHDOG_NOTICE);
-
-    foreach ($record_array['fields'] as $field_index => $field_array) {
-
-      $default_data[$priority]['table'] = $record_array['table'];
-      $default_data[$priority]['mode'] = ($record_array['mode']) ? $record_array['mode'] : 'insert_unique';
-      $default_data[$priority]['record_id'] = $record_array['record_id'];
-      $record2priority[$record_array['record_id']] = $priority;
-      $default_data[$priority]['required'][$field_array['field']] = $field_array['required'];
-
-      $one = $default_data[$priority];
-      if (isset($field_array['regex'])) {
-        $default_data[$priority]['regex_transform'][$field_array['field']] = $field_array['regex'];
-      }
-
-      $two = $default_data[$priority];
-
-      if (preg_match('/table field/', $field_array['type'])) {
-        $default_data[$priority]['values_array'][$field_array['field']] = '';
-        $default_data[$priority]['need_further_processing'] = TRUE;
-        $field2column[$priority][$field_array['field']] = $field_array['spreadsheet column'];
-
-<<<<<<< HEAD
-      }
-      elseif (preg_match('/constant/', $field_array['type'])) {
-        $default_data[$priority]['values_array'][$field_array['field']] = $field_array['constant value'];
-
-      }
-      elseif (preg_match('/foreign key/', $field_array['type'])) {
-=======
-      } elseif (preg_match('/constant/', $field_array['type'])) {
-        $default_data[$priority]['values_array'][$field_array['field']] = $field_array['constant value'];
-
-      } elseif (preg_match('/foreign key/', $field_array['type'])) {
->>>>>>> 6.x-0.4-dev
-        $default_data[$priority]['values_array'][$field_array['field']] = array();
-        $default_data[$priority]['values_array'][$field_array['field']]['foreign record'] = $field_array['foreign key'];
-        $default_data[$priority]['need_further_processing'] = TRUE;
-
-<<<<<<< HEAD
-      }
-      else {
-        print 'WARNING: Unsupported type: ' . $field_array['type'] . ' for ' . $table . '.' . $field_array['field'] . "!\n";
-=======
-      } else {
-        print 'WARNING: Unsupported type: '. $field_array['type'] . ' for ' . $table . '.' . $field_array['field']."!\n";
->>>>>>> 6.x-0.4-dev
-      }
-
-      $three = $default_data[$priority];
-      //watchdog('T_bulk_loader','A)'.$field_index.':<pre>Field Array =>'.print_r($field_array,TRUE)."Initial => \n".print_r($one, TRUE)."\nAfter Regex =>".print_r($two, TRUE)."Final =>\n".print_r($three,TRUE).'</pre>', array(), WATCHDOG_NOTICE);
-
-    } // end of foreach field
-    //watchdog('T_bulk_loader','2)'.$record_array['record_id'].':<pre>'.print_r($default_data[$priority], TRUE).'</pre>', array(), WATCHDOG_NOTICE);
-  } //end of foreach record
-
-  ///////////////////////////////////////////////
-  // For each set of constants
-  ///////////////////////////////////////////////
-  $original_default_data = $default_data;
-  $group_index = 0;
-  $total_num_groups = sizeof($node->constants);
-  foreach ($node->constants as $group_id => $set) {
-    // revert default data array for next set of constants
-    $default_data = $original_default_data;
-    $group_index++;
-
-    // Add constants
-    if (!empty($set)) {
-      print "Constants:\n";
-      foreach ($set as $priority => $record) {
-        foreach ($record as $field_id => $field) {
-
-<<<<<<< HEAD
-          print "\t- " . $field['chado_table'] . '.' . $field['chado_field'] . ' = ' . $field['value'] . "\n";
-=======
-          print "\t- ".$field['chado_table'].'.'.$field['chado_field'].' = '.$field['value']."\n";
->>>>>>> 6.x-0.4-dev
-
-          if ($default_data[$priority]['table'] == $field['chado_table']) {
-            if (isset($default_data[$priority]['values_array'][$field['chado_field']])) {
-              if (isset($field2column[$priority][$field['chado_field']])) {
-                $field2column[$priority][$field['chado_field']] = $field['value'];
-              }
-              else {
-                $default_data[$priority]['values_array'][$field['chado_field']] = $field['value'];
-              }
-            }
-            else {
-              print "ERROR: Template has changed after constants were assigned!\n";
-              watchdog('T_bulk_loader', 'Template has changed after constants were assigned', array(), WATCHDOG_NOTICE);
-              exit(1);
-            }
-          }
-          else {
-            print "ERROR: Template has changed after constants were assigned!\n";
-            watchdog('T_bulk_loader', 'Template has changed after constants were assigned', array(), WATCHDOG_NOTICE);
-            exit(1);
-          }
-        }
-      }
-    }
-
-    //print "Default Data:".print_r($default_data,TRUE)."\n";
-    //watchdog('T_bulk_loader','Default Data:<pre>'.print_r($default_data, TRUE).'</pre>', array(), WATCHDOG_NOTICE);
-
-    //print "\nDefault Values Array: ".print_r($default_data, TRUE)."\n";
-    //print "\nField to Column Mapping: ".print_r($field2column, TRUE)."\n";
-
-    // Parse File adding records as we go ========================================================
-    $file_handle = fopen($node->file, 'r');
-    if (preg_match('/(t|true|1)/', $node->file_has_header)) {
-      fgets($file_handle, 4096);
-    }
-    $num_records = 0;
-    $num_lines = 0;
-    $num_errors = 0;
-    $interval = intval($total_lines * 0.10);
-    if ($interval == 0) {
-       $interval = 1;
-     }
-    while (!feof($file_handle)) {
-
-      // Clear variables
-      // Was added to fix memory leak
-      unset($line);                     unset($raw_line);
-      unset($data);                     unset($data_keys);
-      unset($priority);                 unset($sql);
-      unset($result);
-
-      $raw_line = fgets($file_handle, 4096);
-      $raw_line = trim($raw_line);
-      if (empty($raw_line)) {
-        continue;
-      } // skips blank lines
-      $line = explode("\t", $raw_line);
-      $num_lines++;
-
-      // update the job status every 10% of lines processed for the current group
-      if ($node->job_id and $num_lines % $interval == 0) {
-        // percentage of lines processed for the current group
-        $group_progress = round(($num_lines/$total_lines)*100);
-
-        // percentage of lines processed for all groups
-        // <previous group index> * 100 + <current group progress>
-        // --------------------------------------------------------
-        //               <total number of groups>
-        // For example, if you were in the third group of 3 constant sets
-        // and had a group percentage of 50% then the job progress would be
-        // (2*100 + 50%) / 3 = 250%/3 = 83%
-        $job_progress = round(((($group_index-1)*100)+$group_progress)/$total_num_groups);
-
-        /**
-          print "\nProgress Update:\n"
-            ."\t- ".$num_lines." lines have been processed for the current constant set.\n"
-            ."\t- ".$group_progress."% of the lines in the file have been processed for the current constant set.\n"
-            ."\t- ".$job_progress."% of the current job has been completed.\n";
-        */
-
-<<<<<<< HEAD
-        tripal_job_set_progress($node->job_id, $job_progress);
-=======
-        tripal_job_set_progress($node->job_id,$job_progress);
->>>>>>> 6.x-0.4-dev
-      }
-
-      $data = $default_data;
-
-      $data_keys = array_keys($data);
-      foreach ($data_keys as $priority) {
-        $status = process_data_array_for_line($priority, $data, $default_data, $field2column, $record2priority, $line, $nid, $num_lines, $group_index);
-        if (!$status ) {
-          $loaded_without_errors = FALSE;
-        }
-      } // end of foreach table in default data array
-
-    } //end of foreach line of file
-  } //end of foreach constant set
-
-  // check that data was inserted and update job_status
-  $sql = 'SELECT count(*) as num_tables FROM {tripal_bulk_loader_inserted} WHERE nid=%d GROUP BY nid';
-  $result = db_fetch_object(db_query($sql, $nid));
-  if ($result->num_tables > 0) {
-    $node->job_status = 'Data Inserted';
-    drupal_write_record('node', $node, 'nid');
-  }
-
-  // set the status of the job (in the node not the tripal jobs)
-  if ($loaded_without_errors) {
-      $status = 'Loading Completed Successfully';
-    }
-    else {
-      $status = 'Errors Encountered';
-      }
-  db_query("UPDATE {tripal_bulk_loader} SET job_status='%s' WHERE nid=%d", $status, $nid);
-
-}
-
-/**
- *
- *
- */
-function process_data_array_for_line($priority, &$data, &$default_data, $field2column, $record2priority, $line, $nid, $line_num, $group_index) {
-  $table_data = $data[$priority];
-
-  $no_errors = TRUE;
-
-  $table = $table_data['table'];
-  $values = $table_data['values_array'];
-
-  //watchdog('T_bulk_loader','Original:<pre>'.print_r($table_data, TRUE).'</pre>', array(), WATCHDOG_NOTICE);
-
-  //print 'default values:'.print_r($values,TRUE)."\n";
-  if ($table_data['need_further_processing']) {
-    $values = tripal_bulk_loader_add_spreadsheetdata_to_values($values, $line, $field2column[$priority]);
-    if (!$values) {
-      watchdog('T_bulk_loader', 'Line ' . $line_num . ' Spreadsheet Added:' . print_r($values, TRUE), array(), WATCHDOG_NOTICE);
-    }
-
-    $values = tripal_bulk_loader_add_foreignkey_to_values($values, $data, $record2priority);
-    if (!$values) {
-      watchdog('T_bulk_loader', 'Line ' . $line_num . ' FK Added:<pre>' . print_r($values, TRUE) . print_r($data[$priority], TRUE) . '</pre>', array(), WATCHDOG_NOTICE);
-    }
-  }
-  $values = tripal_bulk_loader_regex_tranform_values($values, $table_data, $line);
-  if (!$values) {
-    watchdog('T_bulk_loader', 'Line ' . $line_num . ' Regex:<pre>' . print_r($values, TRUE) . print_r($table_data, TRUE) . '</pre>' . '</pre>', array(), WATCHDOG_NOTICE);
-  }
-
-  if (!$values) {
-<<<<<<< HEAD
-    $msg = 'Line ' . $line_num . ' ' . $table_data['record_id'] . ' (' . $table_data['mode'] . ') Aborted due to error in previous record. Values of current record:' . print_r($table_data['values_array'], TRUE);
-    watchdog('T_bulk_loader', $msg, array(), WATCHDOG_WARNING);
-    print "ERROR: " . $msg . "\n";
-=======
-    $msg = 'Line '.$line_num.' '.$table_data['record_id'].' ('.$table_data['mode'].') Aborted due to error in previous record. Values of current record:'.print_r($table_data['values_array'],TRUE);
-    watchdog('T_bulk_loader', $msg, array(), WATCHDOG_WARNING);
-    print "ERROR: ".$msg."\n";
->>>>>>> 6.x-0.4-dev
-    $data[$priority]['error'] = TRUE;
-    $no_errors = FALSE;
-  }
-
-<<<<<<< HEAD
-  $table_desc = module_invoke_all('chado_' . $table . '_schema');
-=======
-  $table_desc = module_invoke_all('chado_'.$table.'_schema');
->>>>>>> 6.x-0.4-dev
-  if (preg_match('/optional/', $table_array['mode'])) {
-    // Check all db required fields are set
-    $fields = $table_desc['fields'];
-    foreach ($fields as $field => $def) {
-      // a field is considered missing if it cannot be null and there is no default
-      // value for it or it is of type 'serial'
-<<<<<<< HEAD
-      if ($def['not null'] == 1 and !array_key_exists($field, $insert_values) and !isset($def['default']) and strcmp($def['type'], serial)!=0) {
-         $msg = 'Line ' . $line_num . ' ' . $table_data['record_id'] . ' (' . $table_data['mode'] . ') Missing Database Required Value: ' . $table . '.' . $field;
-=======
-      if($def['not null'] == 1 and !array_key_exists($field,$insert_values) and !isset($def['default']) and strcmp($def['type'],serial)!=0){
-         $msg = 'Line '.$line_num.' '.$table_data['record_id'].' ('.$table_data['mode'].') Missing Database Required Value: '.$table.'.'.$field;
->>>>>>> 6.x-0.4-dev
-         watchdog('T_bulk_loader', $msg, array(), WATCHDOG_NOTICE);
-         $data[$priority]['error'] = TRUE;
-      }
-    }
-  } //end of if optional record
-
-  // Check required fields are present
-  foreach ($table_data['required'] as $field => $required) {
-    if ($required) {
-      if (!isset($values[$field])) {
-<<<<<<< HEAD
-        $msg = 'Line ' . $line_num . ' ' . $table_data['record_id'] . ' (' . $table_data['mode'] . ') Missing Template Required Value: ' . $table . '.' . $field;
-=======
-        $msg = 'Line '.$line_num.' '.$table_data['record_id'].' ('.$table_data['mode'].') Missing Template Required Value: '.$table.'.'.$field;
->>>>>>> 6.x-0.4-dev
-        watchdog('T_bulk_loader', $msg, array(), WATCHDOG_NOTICE);
-        $data[$priority]['error'] = TRUE;
-      }
-    }
-  }
-
-  // add new values array into the data array
-  $data[$priority]['values_array'] = $values;
-
-  // check if it is already inserted
-  if ($table_data['inserted']) {
-    //watchdog('T_bulk_loader','Already Inserted:'.print_r($values,TRUE),array(),WATCHDOG_NOTICE);
-    return $no_errors;
-  }
-
-  // if there was an error already -> don't insert
-  if ($data[$priority]['error']) {
-    return $no_errors;
-  }
-
-  $header = '';
-  if (isset($values['feature_id'])) {
-    $header = $values['feature_id']['uniquename'] . ' ' . $table_data['record_id'];
-  }
-  else {
-    $header = $values['uniquename'] . ' ' . $table_data['record_id'];
-  }
-
-  // if insert unique then check to ensure unique
-  if (preg_match('/insert_unique/', $table_data['mode'])) {
-    $unique = tripal_core_chado_select($table, array_keys($table_desc['fields']), $values, array('has_record' => TRUE));
-    //print 'Unique?'.print_r(array('table' => $table, 'columns' => array_keys($table_desc['fields']), 'values' => $values),TRUE).' returns '.$unique."\n";
-    if ($unique > 0) {
-      //$default_data[$priority]['inserted'] = TRUE;
-      //watchdog('T_bulk_loader', $header.': Not unique ('.$unique.'):'.print_r($values,'values')."\n".print_r($data,TRUE),array(),WATCHDOG_NOTICE);;
-      return $no_errors;
-    }
-  }
-
-
-<<<<<<< HEAD
-  if (!preg_match('/select/', $table_data['mode'])) {
-=======
-  if (!preg_match('/select/',$table_data['mode'])) {
->>>>>>> 6.x-0.4-dev
-    //watchdog('T_bulk_loader',$header.': Inserting:'.print_r($values, TRUE), array(), WATCHDOG_NOTICE);
-    if (variable_get('tripal_bulk_loader_prepare',TRUE)) {
-      $options = array('statement_name' => $priority);
-      if ($line_num == 1 && $group_index == 1) {
-        $options['prepare'] = TRUE;
-      }
-    }
-    else {
-      $options = array();
-    }
-
-    $record = tripal_core_chado_insert($table, $values, $options);
-
-    if (!$record) {
-<<<<<<< HEAD
-      $msg = 'Line ' . $line_num . ' ' . $table_data['record_id'] . ' (' . $table_data['mode'] . ') Unable to insert record into ' . $table . ' where values:' . print_r($values, TRUE);
-      watchdog('T_bulk_loader', $msg, array(), WATCHDOG_ERROR);
-      print "ERROR: " . $msg . "\n";
-=======
-      $msg = 'Line '.$line_num.' '.$table_data['record_id'].' ('.$table_data['mode'].') Unable to insert record into '.$table.' where values:'.print_r($values,TRUE);
-      watchdog('T_bulk_loader', $msg, array(), WATCHDOG_ERROR);
-      print "ERROR: ".$msg."\n";
->>>>>>> 6.x-0.4-dev
-      $data[$priority]['error'] = TRUE;
-      $no_errors = FALSE;
-    }
-    else {
-      //add changes back to values array
-      $data[$priority]['values_array'] = $record;
-      $values = $record;
-
-      // if mode=insert_once then ensure we only insert it once
-      if (preg_match('/insert_once/', $table_data['mode'])) {
-        $default_data[$priority]['inserted'] = TRUE;
-      }
-
-      // add to tripal_bulk_loader_inserted
-      $insert_record = db_fetch_object(db_query(
-        "SELECT * FROM {tripal_bulk_loader_inserted} WHERE table_inserted_into='%s' AND nid=%d",
-        $table,
-        $nid
-      ));
-      if ($insert_record) {
-        $insert_record->ids_inserted .= ',' . $values[ $table_desc['primary key'][0] ];
-        drupal_write_record('tripal_bulk_loader_inserted', $insert_record, 'tripal_bulk_loader_inserted_id');
-        //print 'Update: '.print_r($insert_record,TRUE)."\n";
-        return $no_errors;
-      }
-      else {
-        $insert_record = array(
-          'nid' => $nid,
-          'table_inserted_into' => $table,
-          'table_primary_key' => $table_desc['primary key'][0],
-          'ids_inserted' => $values[ $table_desc['primary key'][0] ],
-        );
-        //print 'New: '.print_r($insert_record,TRUE)."\n";
-        $success = drupal_write_record('tripal_bulk_loader_inserted', $insert_record);
-        return $no_errors;
-      }//end of if insert record
-
-    } //end of if insert was successful
-  }
-  else {
-    $exists = tripal_core_chado_select($table, array_keys($table_desc['fields']), $values, array('has_record' => TRUE));
-    if (!$exists) {
-      // No record on select
-<<<<<<< HEAD
-      $msg = 'Line ' . $line_num . ' ' . $table_data['record_id'] . ' (' . $table_data['mode'] . ') No Matching record in ' . $table . ' where values:' . print_r($values, TRUE);
-=======
-      $msg = 'Line '.$line_num.' '.$table_data['record_id'].' ('.$table_data['mode'].') No Matching record in '.$table.' where values:'.print_r($values,TRUE);
->>>>>>> 6.x-0.4-dev
-      watchdog('T_bulk_loader', $msg, array(), WATCHDOG_WARNING);
-      $data[$priority]['error'] = TRUE;
-    }
-  }
-  return $no_errors;
-}
-
-/**
- * This function adds the file data to the values array
- *
- * @param $values
- *   The default values array -contains all constants
- * @param $line
- *   An array of values for the current line
- * @param $field2column
- *   An array mapping values fields to line columns
- * @return
- *   Supplemented values array
- */
-function tripal_bulk_loader_add_spreadsheetdata_to_values($values, $line, $field2column) {
-
-  foreach ($values as $field => $value) {
-<<<<<<< HEAD
-    if (is_array($value)) {
-      continue;
-    }
-
-    $column = $field2column[$field] - 1;
-    if ($column < 0) {
-      continue;
-    }
-
-    if (preg_match('/\S+/', $line[$column])) {
-=======
-    if (is_array($value)) { continue; }
-
-    $column = $field2column[$field] - 1;
-    if ($column < 0) { continue; }
-
-    if (preg_match('/\S+/',$line[$column])) {
->>>>>>> 6.x-0.4-dev
-      $values[$field] = $line[$column];
-    }
-    else {
-      unset($values[$field]);
-    }
-  }
-
-  return $values;
-}
-
-/**
- * Handles foreign keys in the values array.
- *
- * Specifically, if the value for a field is an array then it is assumed that the array contains
- * the name of the record whose values array should be substituted here. Thus the foreign
- * record is looked up and the values array is substituted in.
- *
- */
-function tripal_bulk_loader_add_foreignkey_to_values($values, $data, $record2priority) {
-
-  foreach ($values as $field => $value) {
-    if (is_array($value)) {
-      $foreign_record = $value['foreign record'];
-      $foreign_priority = $record2priority[$foreign_record];
-      $foreign_values = $data[$foreign_priority]['values_array'];
-
-      // add to current values array
-      $values[$field] = $foreign_values;
-    }
-  }
-
-  return $values;
-}
-
-/**
- * Uses a supplied regex to transform spreadsheet values
- *
- * @param $values
- *   The select/insert values array for the given table
- * @param $table_data
- *   The data array for the given table
- */
-function tripal_bulk_loader_regex_tranform_values($values, $table_data, $line) {
-
-  if (empty($table_data['regex_transform']) OR !is_array($table_data['regex_transform'])) {
-    return $values;
-  }
-
-<<<<<<< HEAD
-  //watchdog('T_bulk_loader','Regex Transformation:<pre>'.print_r($table_data['regex_transform'], TRUE).'</pre>', array(), WATCHDOG_NOTICE);
-
-  foreach ($table_data['regex_transform'] as $field => $regex_array) {
-    if (!is_array($regex_array['replace'])) {
-       continue;
-     }
-=======
-  if (empty($table_data['regex_transform']) OR !is_array($table_data['regex_transform'])) { return $values; }
-
-  //watchdog('T_bulk_loader','Regex Transformation:<pre>'.print_r($table_data['regex_transform'], TRUE).'</pre>', array(), WATCHDOG_NOTICE);
-
-  foreach ($table_data['regex_transform'] as $field => $regex_array) {
-    if (!is_array($regex_array['replace'])) { continue; }
->>>>>>> 6.x-0.4-dev
-
-    //print 'Match:'.print_r($regex_array['pattern'],TRUE)."\n";
-    //print 'Replace:'.print_r($regex_array['replace'],TRUE)."\n";
-    //print 'Was:'.$values[$field]."\n";
-
-    // Check for <#column:\d+#> notation
-    // if present replace with that column in the current line
-    foreach ($regex_array['replace'] as $key => $replace) {
-      if (preg_match_all('/<#column:(\d+)#>/', $replace, $matches)) {
-        foreach ($matches[1] as $k => $column_num) {
-          $replace = preg_replace('/' . $matches[0][$k] .'/', $line[$column_num-1], $replace);
-        }
-        $regex_array['replace'][$key] = $replace;
-      }
-    }
-
-    // do the full replacement
-    $old_value = $values[$field];
-    $new_value = preg_replace($regex_array['pattern'], $regex_array['replace'], $old_value);
-    $values[$field] = $new_value;
-
-    if ($values[$field] === '') {
-      unset($values[$field]);
-    }
-    //print 'Now:'.$values[$field]."\n";
-  }
-
-
-
-  return $values;
-}
-
-/**
- * Flattens an array up to two levels
- * Used for printing of arrays without taking up much space
- */
-function tripal_bulk_loader_flatten_array($values) {
-  $flattened_values = array();
-
-  foreach ($values as $k => $v) {
-    if (is_array($v)) {
-      $vstr = array();
-      foreach ($v as $vk => $vv) {
-        if (strlen($vv) > 20) {
-          $vstr[] = $vk . '=>' . substr($vv, 0, 20) . '...';
-        }
-        else {
-          $vstr[] = $vk . '=>' . $vv;
-        }
-      }
-      $v = '{' . implode(',', $vstr) . '}';
-    }
-    elseif (strlen($v) > 20) {
-      $v = substr($v, 0, 20) . '...';
-    }
-    $flattened_values[] = $k . '=>' . $v;
-  }
-
-<<<<<<< HEAD
-  return implode(', ', $flattened_values);
-}
-=======
-  return implode(', ',$flattened_values);
-}
->>>>>>> 6.x-0.4-dev

+ 132 - 139
tripal_bulk_loader/tripal_bulk_loader.module

@@ -2,6 +2,8 @@
 
 include('tripal_bulk_loader.loader.inc');
 include('tripal_bulk_loader.constants.inc');
+include('tripal_bulk_loader.admin.inc');
+include('tripal_bulk_loader.admin.templates.inc');
 
 /**
  * Implements hook_init
@@ -18,130 +20,140 @@ function tripal_bulk_loader_init() {
  */
 function tripal_bulk_loader_menu() {
   $items = array();
-   // Show all loaders
-   $items['tripal_bulk_loaders'] = array(
-     'title' => 'Tripal Bulk Loaders',
-     'description' => 'Tripal bulk loaders for loading tab-delimited file into chado database',
-     'page callback' => 'tripal_bulk_loader_list',
-     'access arguments' => array('access tripal_bulk_loader'),
-     'type' => MENU_NORMAL_ITEM,
-   );
-   // Bulk Loading Job Node
-   $items['node/%node/constants/%/edit'] = array(
-      'title' => 'Edit Constant Set',
-      'description' => 'Edit a group of constants associated with the current bulk loader',
-      'page callback' => 'drupal_get_form',
-      'page arguments' => array('tripal_bulk_loader_edit_constant_set_form', 1, 3),
-      'access arguments' => array('administer site configuration'),
-      'type' => MENU_CALLBACK,
-      'file' => 'tripal_bulk_loader.constants.inc',
-   );
-   $items['node/%node/constants/%/delete'] = array(
-      'title' => 'Delete Constant Set',
-      'description' => 'Delete a group of constants associated with the current bulk loader',
-      'page callback' => 'drupal_get_form',
-      'page arguments' => array('tripal_bulk_loader_delete_constant_set_form', 1, 3),
-      'access arguments' => array('administer site configuration'),
-      'type' => MENU_CALLBACK,
-      'file' => 'tripal_bulk_loader.constants.inc',
-   );
-
-   // Admin page to create the template
-   $items['admin/tripal/tripal_bulk_loader_template'] = array(
-      'title' => 'Bulk Loader Template',
-      'description' => 'Templates for loading tab-delimited data',
-      'page callback' => 'tripal_bulk_loader_admin_template',
-      'access arguments' => array('administer site configuration'),
-      'type' => MENU_NORMAL_ITEM,
-      'file' => 'tripal_bulk_loader.admin.inc',
+  // Show all loaders
+  $items['tripal_bulk_loaders'] = array(
+    'title' => 'Tripal Bulk Loaders',
+    'description' => 'Tripal bulk loaders for loading tab-delimited file into chado database',
+    'page callback' => 'tripal_bulk_loader_list',
+    'access arguments' => array('access tripal_bulk_loader'),
+    'type' => MENU_NORMAL_ITEM,
   );
-  // Create/Edit Template -------
-  $items['admin/tripal/tripal_bulk_loader_template/create'] = array(
-      'title' => 'Create Bulk Loader Template',
-      'description' => 'Create loader template for loading tab-delimited data',
-      'page callback' => 'drupal_get_form',
-      'page arguments' => array('tripal_bulk_loader_modify_template_base_form', 'create'),
-      'access arguments' => array('administer site configuration'),
-      'type' => MENU_NORMAL_ITEM,
-    'file' => 'tripal_bulk_loader.admin.inc',
+  // Bulk Loading Job Node
+  $items['node/%node/constants/%/edit'] = array(
+    'title' => 'Edit Constant Set',
+    'description' => 'Edit a group of constants associated with the current bulk loader',
+    'page callback' => 'drupal_get_form',
+    'page arguments' => array('tripal_bulk_loader_edit_constant_set_form', 1, 3),
+    'access arguments' => array('administer site configuration'),
+    'type' => MENU_CALLBACK,
   );
-  $items['admin/tripal/tripal_bulk_loader_template/edit'] = array(
-      'title' => 'Edit Bulk Loader Template',
-      'description' => 'Edit loader template for loading tab-delimited data',
-      'page callback' => 'drupal_get_form',
-      'page arguments' => array('tripal_bulk_loader_modify_template_base_form', 'edit'),
-      'access arguments' => array('administer site configuration'),
-      'type' => MENU_NORMAL_ITEM,
-      'file' => 'tripal_bulk_loader.admin.inc',
+  $items['node/%node/constants/%/delete'] = array(
+    'title' => 'Delete Constant Set',
+    'description' => 'Delete a group of constants associated with the current bulk loader',
+    'page callback' => 'drupal_get_form',
+    'page arguments' => array('tripal_bulk_loader_delete_constant_set_form', 1, 3),
+    'access arguments' => array('administer site configuration'),
+    'type' => MENU_CALLBACK,
+  );
+
+  // Admin pages -----------------
+  $items['admin/tripal/tripal_bulk_loader_template'] = array(
+    'title' => 'Bulk Loader',
+    'description' => 'Templates for loading tab-delimited data',
+    'page callback' => 'tripal_bulk_loader_admin_template',
+    'access arguments' => array('administer site configuration'),
+    'type' => MENU_NORMAL_ITEM,
+  );
+  $items['admin/tripal/tripal_bulk_loader_template/configure'] = array(
+    'title' => 'Configure',
+    'description' => 'Configuration of global options related to bulk loading jobs',
+    'page callback' => 'drupal_get_form',
+    'page arguments' => array('tripal_bulk_loader_configuration_form'),
+    'access arguments' => array('administer site configuration'),
+    'type' => MENU_NORMAL_ITEM,
+  );
+  $items['admin/tripal/tripal_bulk_loader_template/manage_templates'] = array(
+    'title' => 'Manage Templates',
+    'description' => 'Create/Update/Delete/Import/Export Templates',
+    'page callback' => 'tripal_bulk_loader_admin_manage_templates',
+    'access arguments' => array('administer site configuration'),
+    'type' => MENU_NORMAL_ITEM,
+  );
+  $items['admin/tripal/tripal_bulk_loader_template/jobs'] = array(
+    'title' => 'Jobs',
+    'description' => 'Listing of Bulk Loading Jobs',
+    'page callback' => 'tripal_bulk_loader_admin_jobs',
+    'access arguments' => array('administer site configuration'),
+    'type' => MENU_NORMAL_ITEM,
+  );
+
+  // Create/Edit Template --------
+  $items['admin/tripal/tripal_bulk_loader_template/manage_templates/create'] = array(
+    'title' => 'Create Template',
+    'description' => 'Create loader template for loading tab-delimited data',
+    'page callback' => 'drupal_get_form',
+    'page arguments' => array('tripal_bulk_loader_modify_template_base_form', 'create'),
+    'access arguments' => array('administer site configuration'),
+    'type' => MENU_NORMAL_ITEM,
+  );
+  $items['admin/tripal/tripal_bulk_loader_template/manage_templates/edit'] = array(
+    'title' => 'Edit Template',
+    'description' => 'Edit loader template for loading tab-delimited data',
+    'page callback' => 'drupal_get_form',
+    'page arguments' => array('tripal_bulk_loader_modify_template_base_form', 'edit'),
+    'access arguments' => array('administer site configuration'),
+    'type' => MENU_NORMAL_ITEM,
   );
   $items['admin/tripal/tripal_bulk_loader_template/edit_record'] = array(
-      'title' => 'Edit Template Record',
-      'description' => 'Edit a record in an existing tripal bulk loader template.',
-      'page callback' => 'drupal_get_form',
-      'page arguments' => array('tripal_bulk_loader_edit_template_record_form'),
-      'access arguments' => array('administer site configuration'),
-      'type' => MENU_CALLBACK,
-    'file' => 'tripal_bulk_loader.admin.inc',
+    'title' => 'Edit Template Record',
+    'description' => 'Edit a record in an existing tripal bulk loader template.',
+    'page callback' => 'drupal_get_form',
+    'page arguments' => array('tripal_bulk_loader_edit_template_record_form'),
+    'access arguments' => array('administer site configuration'),
+    'type' => MENU_CALLBACK,
   );
   $items['admin/tripal/tripal_bulk_loader_template/add_field'] = array(
-      'title' => 'Add Template Field',
-      'description' => 'Add a template field to an existing tripal bulk loader template.',
-      'page callback' => 'drupal_get_form',
-      'page arguments' => array('tripal_bulk_loader_add_template_field_form'),
-      'access arguments' => array('administer site configuration'),
-      'type' => MENU_CALLBACK,
-    'file' => 'tripal_bulk_loader.admin.inc',
+    'title' => 'Add Template Field',
+    'description' => 'Add a template field to an existing tripal bulk loader template.',
+    'page callback' => 'drupal_get_form',
+    'page arguments' => array('tripal_bulk_loader_add_template_field_form'),
+    'access arguments' => array('administer site configuration'),
+    'type' => MENU_CALLBACK,
   );
   $items['admin/tripal/tripal_bulk_loader_template/edit_field'] = array(
-      'title' => 'Edit Template Field',
-      'description' => 'Edit an existing field from a tripal bulk loader template.',
-      'page callback' => 'drupal_get_form',
-      'page arguments' => array('tripal_bulk_loader_edit_template_field_form'),
-      'access arguments' => array('administer site configuration'),
-      'type' => MENU_CALLBACK,
-    'file' => 'tripal_bulk_loader.admin.inc',
+    'title' => 'Edit Template Field',
+    'description' => 'Edit an existing field from a tripal bulk loader template.',
+    'page callback' => 'drupal_get_form',
+    'page arguments' => array('tripal_bulk_loader_edit_template_field_form'),
+    'access arguments' => array('administer site configuration'),
+    'type' => MENU_CALLBACK,
   );
   // Delete Template -----
-  $items['admin/tripal/tripal_bulk_loader_template/delete'] = array(
-      'title' => 'Delete Bulk Loader Template',
-      'description' => 'Delete bulk loader template',
-      'page callback' => 'drupal_get_form',
-      'page arguments' => array('tripal_bulk_loader_delete_template_base_form'),
-      'access arguments' => array('administer site configuration'),
-      'type' => MENU_NORMAL_ITEM,
-    'file' => 'tripal_bulk_loader.admin.inc',
+  $items['admin/tripal/tripal_bulk_loader_template/manage_templates/delete'] = array(
+    'title' => 'Delete Template',
+    'description' => 'Delete bulk loader template',
+    'page callback' => 'drupal_get_form',
+    'page arguments' => array('tripal_bulk_loader_delete_template_base_form'),
+    'access arguments' => array('administer site configuration'),
+    'type' => MENU_NORMAL_ITEM,
   );
   // Import/Export ---------
-  $items['admin/tripal/tripal_bulk_loader_template/import'] = array(
-      'title' => 'Import Bulk Loader Template',
-      'description' => 'Import Loaders',
-      'page callback' => 'drupal_get_form',
-      'page arguments' => array('tripal_bulk_loader_import_export_template_form', 'import'),
-      'access arguments' => array('administer site configuration'),
-      'type' => MENU_NORMAL_ITEM,
-      'file' => 'tripal_bulk_loader.admin.inc',
+  $items['admin/tripal/tripal_bulk_loader_template/manage_templates/import'] = array(
+    'title' => 'Import Template',
+    'description' => 'Import Loaders',
+    'page callback' => 'drupal_get_form',
+    'page arguments' => array('tripal_bulk_loader_import_export_template_form', 'import'),
+    'access arguments' => array('administer site configuration'),
+    'type' => MENU_NORMAL_ITEM,
   );
-  $items['admin/tripal/tripal_bulk_loader_template/export'] = array(
-      'title' => 'Export Bulk Loader Template',
-      'description' => 'Export Loaders',
-      'page callback' => 'drupal_get_form',
-      'page arguments' => array('tripal_bulk_loader_import_export_template_form', 'export'),
-      'access arguments' => array('administer site configuration'),
-      'type' => MENU_NORMAL_ITEM,
-      'file' => 'tripal_bulk_loader.admin.inc',
+  $items['admin/tripal/tripal_bulk_loader_template/manage_templates/export'] = array(
+    'title' => 'Export Template',
+    'description' => 'Export Loaders',
+    'page callback' => 'drupal_get_form',
+    'page arguments' => array('tripal_bulk_loader_import_export_template_form', 'export'),
+    'access arguments' => array('administer site configuration'),
+    'type' => MENU_NORMAL_ITEM,
   );
   // AHAH ---------
   $items['admin/tripal/tripal_bulk_loader_template/add_field_ahah'] = array(
-      'page callback' => 'tripal_bulk_loader_add_field_ahah',
-      'access arguments' => array('administer site configuration'),
-      'type' => MENU_CALLBACK,
-      'file' => 'tripal_bulk_loader.admin.inc',
+    'page callback' => 'tripal_bulk_loader_add_field_ahah',
+    'access arguments' => array('administer site configuration'),
+    'type' => MENU_CALLBACK,
   );
   $items['admin/tripal/tripal_bulk_loader_template/edit_field_ahah'] = array(
-      'page callback' => 'tripal_bulk_loader_edit_field_ahah',
-      'access arguments' => array('administer site configuration'),
-      'type' => MENU_CALLBACK,
-      'file' => 'tripal_bulk_loader.admin.inc',
+    'page callback' => 'tripal_bulk_loader_edit_field_ahah',
+    'access arguments' => array('administer site configuration'),
+    'type' => MENU_CALLBACK,
   );
 
   return $items;
@@ -181,8 +193,8 @@ function tripal_bulk_loader_theme() {
 function tripal_bulk_loader_access($op, $node, $account) {
   if ($op == 'create') {
     if (!user_access('create tripal_bulk_loader', $account)) {
-         return FALSE;
-      }
+      return FALSE;
+    }
   }
   if ($op == 'update') {
     if (!user_access('edit tripal_bulk_loader', $account)) {
@@ -214,35 +226,6 @@ function tripal_bulk_loader_perm() {
   );
 }
 
-/**
- * Creates a listing page for all bulk loading jobs
- */
-function tripal_bulk_loader_list() {
-  $num_results_per_page = 50;
-  $output = '';
-
-  $header = array('', 'Status', 'Loader', 'File');
-  $rows = array();
-
-  $query = 'SELECT * FROM {tripal_bulk_loader} l '
-    .'LEFT JOIN {node} n ON n.nid = l.nid '
-    .'LEFT JOIN {tripal_bulk_loader_template} t ON t.template_id = cast(l.template_id as integer)';
-  $resource = pager_query($query, $num_results_per_page, 0, NULL);
-  while ($r = db_fetch_object($resource)) {
-    $row = array(
-      l($r->title, 'node/' . $r->nid),
-      $r->job_status,
-      $r->name,
-      $r->file
-    );
-    $rows[] = $row;
-  }
-
-  $output .= theme('table', $header, $rows);
-  return $output;
-
-}
-
 //////////////////////////////////////////////////////////////////////////////////////////////
 // Node Functions
 //////////////////////////////////////////////////////////////////////////////////////////////
@@ -318,7 +301,7 @@ function tripal_bulk_loader_form($node, $form_state) {
   $form['loader']['file']= array(
     '#type'          => 'textfield',
     '#title'         => t('Data File'),
-    '#description'   => t('Please specify the data file to be loaded.'),
+    '#description'   => t('Please specify the data file to be loaded. This must be a tab-delimited text file with UNIX line endings.'),
     '#weight'        => -8,
     '#default_value' => $node->file
   );
@@ -416,7 +399,7 @@ function tripal_bulk_loader_insert($node) {
   drupal_write_record('node', $node, 'nid');
   drupal_write_record('node_revision', $node, 'nid');
 
-  drupal_set_message('After reviewing the details, please Submit this Job (by clicking the "Submit Job" button below). No data will be loaded until the submitted job is reached in the queue.');
+  drupal_set_message(t('After reviewing the details, please Submit this Job (by clicking the "Submit Job" button below). No data will be loaded until the submitted job is reached in the queue.'));
 
 }
 
@@ -494,3 +477,13 @@ function tripal_bulk_loader_job_describe_args($callback, $args) {
 
 }
 
+/**
+ * Implements hook_coder_ignore().
+ * Defines the path to the file (tripal_bulk_loader.coder_ignores.txt) where ignore rules for coder are stored
+ */
+function tripal_bulk_loader_coder_ignore() {
+  return array(
+    'path' => drupal_get_path('module', 'tripal_bulk_loader'),
+    'line prefix' => drupal_get_path('module', 'tripal_bulk_loader'),
+  );
+}

+ 0 - 647
tripal_bulk_loader/tripal_bulk_loader.module.orig

@@ -1,647 +0,0 @@
-<?php
-
-include('tripal_bulk_loader.loader.inc');
-include('tripal_bulk_loader.constants.inc');
-
-/**
- * Implements hook_init
- * Used to add stylesheets and javascript files to the header
- */
-function tripal_bulk_loader_init() {
-  // Add javascript and style sheet
-  drupal_add_css(drupal_get_path('theme', 'tripal') . '/css/tripal_bulk_loader.css');
-  drupal_add_js(drupal_get_path('theme', 'tripal') . '/js/tripal_bulk_loader.js');
-}
-
-/**
- * Implements hook_menu
- */
-function tripal_bulk_loader_menu() {
-  $items = array();
-   // Show all loaders
-   $items['tripal_bulk_loaders'] = array(
-     'title' => 'Tripal Bulk Loaders',
-     'description' => 'Tripal bulk loaders for loading tab-delimited file into chado database',
-     'page callback' => 'tripal_bulk_loader_list',
-     'access arguments' => array('access tripal_bulk_loader'),
-     'type' => MENU_NORMAL_ITEM,
-   );
-   // Bulk Loading Job Node
-   $items['node/%node/constants/%/edit'] = array(
-      'title' => 'Edit Constant Set',
-      'description' => 'Edit a group of constants associated with the current bulk loader',
-      'page callback' => 'drupal_get_form',
-      'page arguments' => array('tripal_bulk_loader_edit_constant_set_form', 1, 3),
-      'access arguments' => array('administer site configuration'),
-      'type' => MENU_CALLBACK,
-<<<<<<< HEAD
-      'file' => 'tripal_bulk_loader.constants.inc',
-=======
-		  'file' => 'tripal_bulk_loader.constants.inc',
->>>>>>> 6.x-0.4-dev
-   );
-   $items['node/%node/constants/%/delete'] = array(
-      'title' => 'Delete Constant Set',
-      'description' => 'Delete a group of constants associated with the current bulk loader',
-      'page callback' => 'drupal_get_form',
-      'page arguments' => array('tripal_bulk_loader_delete_constant_set_form', 1, 3),
-      'access arguments' => array('administer site configuration'),
-      'type' => MENU_CALLBACK,
-<<<<<<< HEAD
-      'file' => 'tripal_bulk_loader.constants.inc',
-=======
-		  'file' => 'tripal_bulk_loader.constants.inc',
->>>>>>> 6.x-0.4-dev
-   );
-
-   // Admin page to create the template
-   $items['admin/tripal/tripal_bulk_loader_template'] = array(
-      'title' => 'Bulk Loader Template',
-      'description' => 'Templates for loading tab-delimited data',
-      'page callback' => 'tripal_bulk_loader_admin_template',
-      'access arguments' => array('administer site configuration'),
-      'type' => MENU_NORMAL_ITEM,
-<<<<<<< HEAD
-      'file' => 'tripal_bulk_loader.admin.inc',
-  );
-  // Create/Edit Template -------
-=======
-		  'file' => 'tripal_bulk_loader.admin.inc',
-	);
-   $items['admin/tripal/tripal_bulk_loader_template/configure'] = array(
-      'title' => 'Configuration',
-      'description' => 'Configure the Tripal Bulk Loader Module',
-    	'page callback' => 'drupal_get_form',
-    	'page arguments' => array('tripal_bulk_loader_configuration_form'),
-      'access arguments' => array('administer site configuration'),
-      'type' => MENU_NORMAL_ITEM,
-		  'file' => 'tripal_bulk_loader.admin.inc',
-	);
-
-	// Create/Edit Template -------
->>>>>>> 6.x-0.4-dev
-  $items['admin/tripal/tripal_bulk_loader_template/create'] = array(
-      'title' => 'Create Bulk Loader Template',
-      'description' => 'Create loader template for loading tab-delimited data',
-      'page callback' => 'drupal_get_form',
-      'page arguments' => array('tripal_bulk_loader_modify_template_base_form', 'create'),
-      'access arguments' => array('administer site configuration'),
-      'type' => MENU_NORMAL_ITEM,
-<<<<<<< HEAD
-    'file' => 'tripal_bulk_loader.admin.inc',
-=======
-		'file' => 'tripal_bulk_loader.admin.inc',
->>>>>>> 6.x-0.4-dev
-  );
-  $items['admin/tripal/tripal_bulk_loader_template/edit'] = array(
-      'title' => 'Edit Bulk Loader Template',
-      'description' => 'Edit loader template for loading tab-delimited data',
-      'page callback' => 'drupal_get_form',
-      'page arguments' => array('tripal_bulk_loader_modify_template_base_form', 'edit'),
-      'access arguments' => array('administer site configuration'),
-      'type' => MENU_NORMAL_ITEM,
-<<<<<<< HEAD
-      'file' => 'tripal_bulk_loader.admin.inc',
-=======
-		  'file' => 'tripal_bulk_loader.admin.inc',
->>>>>>> 6.x-0.4-dev
-  );
-  $items['admin/tripal/tripal_bulk_loader_template/edit_record'] = array(
-      'title' => 'Edit Template Record',
-      'description' => 'Edit a record in an existing tripal bulk loader template.',
-      'page callback' => 'drupal_get_form',
-      'page arguments' => array('tripal_bulk_loader_edit_template_record_form'),
-      'access arguments' => array('administer site configuration'),
-      'type' => MENU_CALLBACK,
-<<<<<<< HEAD
-    'file' => 'tripal_bulk_loader.admin.inc',
-  );
-  $items['admin/tripal/tripal_bulk_loader_template/add_field'] = array(
-=======
-		'file' => 'tripal_bulk_loader.admin.inc',
-	);
-	$items['admin/tripal/tripal_bulk_loader_template/add_field'] = array(
->>>>>>> 6.x-0.4-dev
-      'title' => 'Add Template Field',
-      'description' => 'Add a template field to an existing tripal bulk loader template.',
-      'page callback' => 'drupal_get_form',
-      'page arguments' => array('tripal_bulk_loader_add_template_field_form'),
-      'access arguments' => array('administer site configuration'),
-      'type' => MENU_CALLBACK,
-<<<<<<< HEAD
-    'file' => 'tripal_bulk_loader.admin.inc',
-  );
-  $items['admin/tripal/tripal_bulk_loader_template/edit_field'] = array(
-=======
-		'file' => 'tripal_bulk_loader.admin.inc',
-	);
-	$items['admin/tripal/tripal_bulk_loader_template/edit_field'] = array(
->>>>>>> 6.x-0.4-dev
-      'title' => 'Edit Template Field',
-      'description' => 'Edit an existing field from a tripal bulk loader template.',
-      'page callback' => 'drupal_get_form',
-      'page arguments' => array('tripal_bulk_loader_edit_template_field_form'),
-      'access arguments' => array('administer site configuration'),
-      'type' => MENU_CALLBACK,
-<<<<<<< HEAD
-    'file' => 'tripal_bulk_loader.admin.inc',
-  );
-  // Delete Template -----
-  $items['admin/tripal/tripal_bulk_loader_template/delete'] = array(
-=======
-		'file' => 'tripal_bulk_loader.admin.inc',
-	);
-	// Delete Template -----
-	$items['admin/tripal/tripal_bulk_loader_template/delete'] = array(
->>>>>>> 6.x-0.4-dev
-      'title' => 'Delete Bulk Loader Template',
-      'description' => 'Delete bulk loader template',
-      'page callback' => 'drupal_get_form',
-      'page arguments' => array('tripal_bulk_loader_delete_template_base_form'),
-      'access arguments' => array('administer site configuration'),
-      'type' => MENU_NORMAL_ITEM,
-<<<<<<< HEAD
-    'file' => 'tripal_bulk_loader.admin.inc',
-  );
-  // Import/Export ---------
-=======
-		'file' => 'tripal_bulk_loader.admin.inc',
-	);
-	// Import/Export ---------
->>>>>>> 6.x-0.4-dev
-  $items['admin/tripal/tripal_bulk_loader_template/import'] = array(
-      'title' => 'Import Bulk Loader Template',
-      'description' => 'Import Loaders',
-      'page callback' => 'drupal_get_form',
-      'page arguments' => array('tripal_bulk_loader_import_export_template_form', 'import'),
-      'access arguments' => array('administer site configuration'),
-      'type' => MENU_NORMAL_ITEM,
-<<<<<<< HEAD
-      'file' => 'tripal_bulk_loader.admin.inc',
-=======
-		  'file' => 'tripal_bulk_loader.admin.inc',
->>>>>>> 6.x-0.4-dev
-  );
-  $items['admin/tripal/tripal_bulk_loader_template/export'] = array(
-      'title' => 'Export Bulk Loader Template',
-      'description' => 'Export Loaders',
-      'page callback' => 'drupal_get_form',
-      'page arguments' => array('tripal_bulk_loader_import_export_template_form', 'export'),
-      'access arguments' => array('administer site configuration'),
-      'type' => MENU_NORMAL_ITEM,
-<<<<<<< HEAD
-      'file' => 'tripal_bulk_loader.admin.inc',
-  );
-  // AHAH ---------
-  $items['admin/tripal/tripal_bulk_loader_template/add_field_ahah'] = array(
-      'page callback' => 'tripal_bulk_loader_add_field_ahah',
-      'access arguments' => array('administer site configuration'),
-      'type' => MENU_CALLBACK,
-      'file' => 'tripal_bulk_loader.admin.inc',
-  );
-  $items['admin/tripal/tripal_bulk_loader_template/edit_field_ahah'] = array(
-      'page callback' => 'tripal_bulk_loader_edit_field_ahah',
-      'access arguments' => array('administer site configuration'),
-      'type' => MENU_CALLBACK,
-      'file' => 'tripal_bulk_loader.admin.inc',
-  );
-=======
-		  'file' => 'tripal_bulk_loader.admin.inc',
-  );
-	// AHAH ---------
-	$items['admin/tripal/tripal_bulk_loader_template/add_field_ahah'] = array(
-      'page callback' => 'tripal_bulk_loader_add_field_ahah',
-      'access arguments' => array('administer site configuration'),
-      'type' => MENU_CALLBACK,
-		  'file' => 'tripal_bulk_loader.admin.inc',
-	);
-	$items['admin/tripal/tripal_bulk_loader_template/edit_field_ahah'] = array(
-      'page callback' => 'tripal_bulk_loader_edit_field_ahah',
-      'access arguments' => array('administer site configuration'),
-      'type' => MENU_CALLBACK,
-		  'file' => 'tripal_bulk_loader.admin.inc',
-	);
->>>>>>> 6.x-0.4-dev
-
-  return $items;
-}
-
-
-/**
- * Implements hook_theme
- */
-function tripal_bulk_loader_theme() {
-  return array(
-    'tripal_bulk_loader_set_constants_form' => array(
-      'arguments' => array('form' => NULL),
-    ),
-    'tripal_bulk_loader_template' => array(
-      'arguments' => array('template_id' => NULL),
-      'template' => 'tripal_bulk_loader_template'
-    ),
-    'tripal_bulk_loader_modify_template_base_form' => array(
-      'arguments' => array('form' => NULL),
-      'template' => 'tripal_bulk_loader_modify_template_base_form',
-    ),
-    'tripal_bulk_loader_edit_template_field_form' => array(
-      'arguments' => array('form' => NULL),
-      'template' => 'tripal_bulk_loader_edit_template_field_form',
-    ),
-    'tripal_bulk_loader_add_template_field_form' => array(
-      'arguments' => array('form' => NULL),
-      'template' => 'tripal_bulk_loader_add_template_field_form',
-    ),
-  );
-}
-
-/**
- *  Implements hook_access
- */
-function tripal_bulk_loader_access($op, $node, $account) {
-  if ($op == 'create') {
-    if (!user_access('create tripal_bulk_loader', $account)) {
-         return FALSE;
-      }
-  }
-  if ($op == 'update') {
-    if (!user_access('edit tripal_bulk_loader', $account)) {
-      return FALSE;
-    }
-  }
-  if ($op == 'delete') {
-    if (!user_access('delete tripal_bulk_loader', $account)) {
-      return FALSE;
-    }
-  }
-  if ($op == 'view') {
-    if (!user_access('access tripal_bulk_loader', $account)) {
-      return FALSE;
-    }
-  }
-  return NULL;
-}
-
-/**
- * Implements hook_perm
- */
-function tripal_bulk_loader_perm() {
-  return array(
-      'access tripal_bulk_loader',
-      'create tripal_bulk_loader',
-      'delete tripal_bulk_loader',
-      'edit tripal_bulk_loader',
-  );
-}
-
-/**
- * Creates a listing page for all bulk loading jobs
- */
-function tripal_bulk_loader_list() {
-  $num_results_per_page = 50;
-  $output = '';
-
-<<<<<<< HEAD
-  $header = array('', 'Status', 'Loader', 'File');
-=======
-  $header = array('','Status','Loader','File');
->>>>>>> 6.x-0.4-dev
-  $rows = array();
-
-  $query = 'SELECT * FROM {tripal_bulk_loader} l '
-    .'LEFT JOIN {node} n ON n.nid = l.nid '
-    .'LEFT JOIN {tripal_bulk_loader_template} t ON t.template_id = cast(l.template_id as integer)';
-  $resource = pager_query($query, $num_results_per_page, 0, NULL);
-  while ($r = db_fetch_object($resource)) {
-    $row = array(
-      l($r->title, 'node/' . $r->nid),
-      $r->job_status,
-      $r->name,
-      $r->file
-    );
-    $rows[] = $row;
-  }
-
-  $output .= theme('table', $header, $rows);
-  return $output;
-
-}
-
-//////////////////////////////////////////////////////////////////////////////////////////////
-// Node Functions
-//////////////////////////////////////////////////////////////////////////////////////////////
-
-/**
- * Implements hook_node_info
- */
-function tripal_bulk_loader_node_info() {
-  $nodes = array();
-  $nodes['tripal_bulk_loader'] = array(
-      'name' => t('Bulk Loading Job'),
-      'module' => 'tripal_bulk_loader',
-      'description' => t('A bulk loader for inserting tab-delimited data into chado database'),
-      'has_title' => TRUE,
-      'has_body' => FALSE,
-      'locked' => TRUE
-  );
-  return $nodes;
-}
-
-/**
- * Implements node_form
- * Used to gather the extra details stored with a Bulk Loading Job Node
- */
-function tripal_bulk_loader_form($node, $form_state) {
-  $form = array();
-
-  if (isset($form_state['values'])) {
-    $node = $form_state['values'] + (array)$node;
-    $node = (object) $node;
-  }
-
-  $sql = "SELECT * FROM {tripal_bulk_loader_template}";
-  $results = db_query($sql);
-  $templates = array();
-  while ($template = db_fetch_object ($results)) {
-    $templates [$template->template_id] = $template->name;
-  }
-
-  if (!$templates) {
-    $form['label'] = array(
-    '#type' => 'item',
-      '#description' => t("Loader template needs to be created before any bulk loader can be added. Go to 'Tripal Management > Bulk Loader Template' to create the template."),
-      '#weight'        => -10,
-    );
-
-    return $form;
-  }
-
-  $form['loader'] = array(
-    '#type' => 'fieldset',
-    '#title' => t('Basic Details'),
-  );
-
-  $form['loader']['loader_name'] = array(
-    '#type'          => 'textfield',
-    '#title'         => t('Loading Job Name'),
-    '#weight'        => -10,
-    '#required'      => TRUE,
-    '#default_value' => $node->loader_name
-  );
-
-  $form['loader']['template_id'] = array(
-    '#type' => 'select',
-    '#title' => t('Template'),
-    '#description'   => t('Please specify a template for this loader'),
-    '#options'       => $templates,
-    '#weight'        => -9,
-    '#required'      => TRUE,
-    '#default_value' => $node->template_id,
-  );
-
-  $form['loader']['file']= array(
-    '#type'          => 'textfield',
-    '#title'         => t('Data File'),
-    '#description'   => t('Please specify the data file to be loaded.'),
-    '#weight'        => -8,
-    '#default_value' => $node->file
-  );
-
-  $form['loader']['has_header'] = array(
-    '#type' => 'radios',
-    '#title' => t('File has a Header'),
-    '#options' => array( 1 => 'Yes', 2 => 'No'),
-    '#weight' => -7,
-    '#default_value' => $node->file_has_header,
-  );
-
-  return $form;
-}
-
-
-/**
- * Implements node_load
- */
-function tripal_bulk_loader_load($node) {
-  $sql = "SELECT * FROM {tripal_bulk_loader} WHERE nid = %d";
-  $node = db_fetch_object(db_query($sql, $node->nid));
-
-<<<<<<< HEAD
-  $node->title = 'Bulk Loading Job: ' . $node->loader_name;
-
-  // Add the loader template
-  $sql = "SELECT * FROM {tripal_bulk_loader_template} WHERE template_id=%d";
-  $results = db_fetch_object(db_query($sql, $node->template_id));
-  $template = unserialize($results->template_array);
-  $node->template = $results;
-  $node->template->template_array = $template;
-=======
-	$node->title = 'Bulk Loading Job: '.$node->loader_name;
-
-	// Add the loader template
-	$sql = "SELECT * FROM {tripal_bulk_loader_template} WHERE template_id=%d";
-	$results = db_fetch_object(db_query($sql, $node->template_id));
-	$template = unserialize($results->template_array);
-	$node->template = $results;
-	$node->template->template_array = $template;
->>>>>>> 6.x-0.4-dev
-
-  // Add inserted records
-  $sql = 'SELECT * FROM {tripal_bulk_loader_inserted} WHERE nid=%d';
-  $resource = db_query($sql, $node->nid);
-  while ($r = db_fetch_object($resource)) {
-<<<<<<< HEAD
-    $r->num_inserted = sizeof(preg_split('/,/', $r->ids_inserted));
-=======
-    $r->num_inserted = sizeof(preg_split('/,/',$r->ids_inserted));
->>>>>>> 6.x-0.4-dev
-    $node->inserted_records->{$r->table_inserted_into} = $r;
-  }
-
-  // Add exposed field list
-  $node->exposed_fields = array();
-  if ($template) {
-    foreach ($template as $record_id => $record) {
-      foreach ($record['fields'] as $field_id => $field) {
-        if ($field['exposed']) {
-          $node->exposed_fields[] = array(
-            'record_id' => $record_id,
-            'field_id' => $field_id,
-            'title' => $field['title'],
-          );
-        }
-      }
-    }
-
-    if (empty($node->exposed_fields)) {
-      $node->exposed_fields[] = array();
-    }
-  }
-
-
-  // Add constants
-  $sql = 'SELECT * FROM {tripal_bulk_loader_constants} WHERE nid=%d ORDER BY group_id, record_id, field_id';
-  $resource = db_query($sql, $node->nid);
-  while ($r = db_fetch_object($resource)) {
-    $node->constants[$r->group_id][$r->record_id][$r->field_id] = array(
-      'constant_id' => $r->constant_id,
-      'group_id' => $r->group_id,
-<<<<<<< HEAD
-      'chado_table' => $r->chado_table,
-      'chado_field' => $r->chado_field,
-      'record_id' => $r->record_id,
-      'field_id' => $r->field_id,
-      'value' => $r->value
-=======
-      'chado_table'=>$r->chado_table,
-      'chado_field'=>$r->chado_field,
-      'record_id'=>$r->record_id,
-      'field_id'=>$r->field_id,
-      'value'=>$r->value
->>>>>>> 6.x-0.4-dev
-    );
-  }
-  if (!$node->constants) {
-    $node->constants[] = array();
-  }
-
-<<<<<<< HEAD
-  return $node;
-=======
-	return $node;
->>>>>>> 6.x-0.4-dev
-}
-
-/**
- * Implements node_insert
- * Insert the data from the node form on Create content
- */
-<<<<<<< HEAD
-function tripal_bulk_loader_insert($node) {
-=======
-function tripal_bulk_loader_insert ($node) {
->>>>>>> 6.x-0.4-dev
-
-  // Insert into tripal_bulk_loader
-  $sql = "INSERT INTO {tripal_bulk_loader} (nid, loader_name, template_id, file, file_has_header, job_status) VALUES (%d, '%s', %d, '%s', %d, '%s')";
-  db_query($sql, $node->nid, $node->loader_name, $node->template_id, $node->file, $node->has_header, 'Initialized');
-
-<<<<<<< HEAD
-  // Update title
-  $node->title =$node->loader_name;
-  drupal_write_record('node', $node, 'nid');
-  drupal_write_record('node_revision', $node, 'nid');
-=======
-	// Update title
-	$node->title =$node->loader_name;
-	drupal_write_record('node',$node,'nid');
-	drupal_write_record('node_revision',$node,'nid');
->>>>>>> 6.x-0.4-dev
-
-  drupal_set_message('After reviewing the details, please Submit this Job (by clicking the "Submit Job" button below). No data will be loaded until the submitted job is reached in the queue.');
-
-}
-
-/**
- * Implements node_delete
- * Deletes the data when the delete button on the node form is clicked
- */
-function tripal_bulk_loader_delete($node) {
-  $sql = "DELETE FROM {tripal_bulk_loader} WHERE nid = %d";
-  db_query($sql, $node->nid);
-}
-
-/**
- * Implements node_update
- * Updates the data submitted by the node form on edit
- */
-<<<<<<< HEAD
-function tripal_bulk_loader_update($node) {
-
-  // Update tripal_bulk_loader
-  $sql = "UPDATE {tripal_bulk_loader} SET nid = %d, loader_name = '%s', template_id = %d, file = '%s', file_has_header = '%s' WHERE nid = %d";
-  db_query($sql, $node->nid, $node->loader_name, $node->template_id, $node->file, $node->has_header, $node->nid);
-
-  // Add a job if the user want to load the data
-  global $user;
-  if ($node->job) {
-    $job_args[0] =$node->loader_name;
-    $job_args[1] = $node->template_id;
-    $job_args[2] = $node->file;
-    if (is_readable($node->file)) {
-      $fname = preg_replace("/.*\/(.*)/", "$1", $node->file);
-      tripal_add_job("Bulk Load: $fname", 'tripal_bulk_loader', 'tripal_bulk_loader_load_data', $job_args, $user->uid);
-    }
-    else {
-      drupal_set_message(t("Can not open %file. Job not scheduled.", array('%file' => $node->file)));
-    }
-  }
-=======
-function tripal_bulk_loader_update ($node) {
-
-  // Update tripal_bulk_loader
-	$sql = "UPDATE {tripal_bulk_loader} SET nid = %d, loader_name = '%s', template_id = %d, file = '%s', file_has_header = '%s' WHERE nid = %d";
-	db_query($sql, $node->nid, $node->loader_name, $node->template_id, $node->file, $node->has_header, $node->nid);
-
-	// Add a job if the user want to load the data
-	global $user;
-	if($node->job) {
-		$job_args[0] =$node->loader_name;
-		$job_args[1] = $node->template_id;
-		$job_args[2] = $node->file;
-		if (is_readable($node->file)) {
-			$fname = preg_replace("/.*\/(.*)/", "$1", $node->file);
-			tripal_add_job("Bulk Load: $fname",'tripal_bulk_loader', 'tripal_bulk_loader_load_data', $job_args, $user->uid);
-		} else {
-			drupal_set_message("Can not open $node->file. Job not scheduled.");
-		}
-	}
->>>>>>> 6.x-0.4-dev
-
-}
-
-///////////////////////////////////////////////////////////
-
-/**
- * Preprocessor function for the tripal_bulk_loader template
- */
-function tripal_bulk_loader_preprocess_tripal_bulk_loader_template(&$variables) {
-
-  $sql = "SELECT * FROM {tripal_bulk_loader_template} WHERE template_id=%d";
-  $template = db_fetch_object(db_query($sql, $variables['template_id']));
-  $template->template_array = unserialize($template->template_array);
-  $variables['template'] = $template;
-
-<<<<<<< HEAD
-=======
-	$sql = "SELECT * FROM {tripal_bulk_loader_template} WHERE template_id=%d";
-	$template = db_fetch_object(db_query($sql, $variables['template_id']));
-	$template->template_array = unserialize($template->template_array);
-	$variables['template'] = $template;
-
->>>>>>> 6.x-0.4-dev
-}
-
-/**
- * Implements hook_job_describe_args()
- * Specifically to make viewing past tripal jobs more readable for jobs registered by this module
- *
- * @params $callback
- *   The callback passed into tripal_add_job()
- * @param $args
- *   The arguements passed into tripal_add_job()
- * @return
- *   An array where keys are the human readable headers describing each arguement
- *   and the value is the aguement passed in after formatting
- */
-function tripal_bulk_loader_job_describe_args($callback, $args) {
-
-  $new_args = array();
-  if ($callback == 'tripal_bulk_loader_load_data') {
-    //1st arg is the nid for a bulk loader node
-    $node = node_load($args[0]);
-    $new_args['Bulk Loading Job'] = l($node->title, 'node/' . $args[0]);
-    return $new_args;
-  }
-
-}
-

+ 2 - 2
tripal_contact/tripal_contact.api.inc

@@ -5,9 +5,9 @@
  * @todo Add file header description
  */
 
-/****************************************************************************
+/**
  * @section Chado Table Descriptions
- ****************************************************************************/
+ */
 
  /**
  * Implements hook_chado_contact_schema()

+ 9 - 9
tripal_contact/tripal_contact.module

@@ -3,20 +3,20 @@
 /**
  *  @file
  * This file contains the basic functions needed for this drupal module.
- * The drupal tripal_contact module maps directly to the chado X module. 
+ * The drupal tripal_contact module maps directly to the chado X module.
  *
- * For documentation regarding the Chado X module: 
+ * For documentation regarding the Chado X module:
  * @see http://gmod.org/wiki/Chado_General_Module
  */
 
 /**
  * @defgroup tripal_contact Contact Module
  * @{
- * Currently this module only provides support for integration with Drupal 
- * views and some support for querying using the Tripal Core API. 
+ * Currently this module only provides support for integration with Drupal
+ * views and some support for querying using the Tripal Core API.
  *
- * This module needs further development to support full management of 
- * contact information within Chado, and full definitions for foreign 
+ * This module needs further development to support full management of
+ * contact information within Chado, and full definitions for foreign
  * key relationships in Chado.
  * @}
  * @ingroup tripal_modules
@@ -31,9 +31,9 @@ require('tripal_contact.api.inc');
  *  views integration code is
  *
  * @ingroup tripal_contact
- */ 
+ */
 function tripal_contact_views_api() {
-   return array(
+  return array(
       'api' => 2.0,
-   );
+  );
 }

+ 12 - 12
tripal_contact/tripal_contact.views.inc

@@ -6,17 +6,17 @@
  *  chado/tripal_contact tables. Supplementary functions can be found in
  *  ./views/
  *
- *  Documentation on views integration can be found at 
+ *  Documentation on views integration can be found at
  *  http://views2.logrus.com/doc/html/index.html.
  */
- 
+
 /*************************************************************************
  * Implements hook_views_data()
  * Purpose: Describe chado/tripal tables & fields to views
  *
  * @return: a data array which follows the structure outlined in the
  *   views2 documentation for this hook. Essentially, it's an array of table
- *   definitions keyed by chado/tripal table name. Each table definition 
+ *   definitions keyed by chado/tripal table name. Each table definition
  *   includes basic details about the table, fields in that table and
  *   relationships between that table and others (joins)
  *
@@ -26,14 +26,14 @@ function tripal_contact_views_data()  {
   $data = array();
 
   if (module_exists('tripal_views')) {
-    
+
     // Base Table: contact
     $table_name = 'contact';
     if (!tripal_views_is_integrated($tablename, 10)) {
       $table_integration_array = tripal_views_get_integration_array_for_chado_table($tablename, TRUE);
       tripal_views_integration_add_entry($table_integration_array);
     }
-      
+
     // Additional tables
     $tables = array(
       'contact_relationship',
@@ -45,14 +45,14 @@ function tripal_contact_views_data()  {
       }
     }
   }
-    
+
   return $data;
 }
 
 /*************************************************************************
  * Implements hook_views_handlers()
  * Purpose: Register all custom handlers with views
- *   where a handler describes either "the type of field", 
+ *   where a handler describes either "the type of field",
  *   "how a field should be filtered", "how a field should be sorted"
  *
  * @return: An array of handler definitions
@@ -60,12 +60,12 @@ function tripal_contact_views_data()  {
  * @ingroup tripal_contact
  */
 function tripal_contact_views_handlers() {
- return array(
+  return array(
    'info' => array(
      'path' => drupal_get_path('module', 'tripal_contact') . '/views/handlers',
-   ),
+  ),
    'handlers' => array(
 
-   ),
- );
-}
+  ),
+  );
+}

+ 159 - 65
tripal_core/tripal_core.api.inc

@@ -71,6 +71,16 @@ require_once "tripal_core.schema.api.inc";
  *  The name of the chado table for inserting
  * @param $values
  *  An associative array containing the values for inserting.
+ * @param $options
+ *  An array of options such as:
+ *    -prepare: TRUE or FALSE. Whether or not to prepare the current statement.
+ *       statement_name must also be supplied.
+ *    -statement_name: the name of the prepared statement to use. If prepare is TRUE,
+ *       this indicates the name of the prepared statement to created; otherwise,
+ *       it indicates the name of the already prepared statement to use.
+ *    -skip_validation: TRUE or FALSE. If TRUE will skip all the validation steps and
+ *       just try to insert as is. This is much faster but results in unhandled
+ *       non user-friendly errors if the insert fails.
  *
  * @return
  *  On success this function returns TRUE. On failure, it returns FALSE.
@@ -102,13 +112,14 @@ require_once "tripal_core.schema.api.inc";
  *
  * @ingroup tripal_chado_api
  */
-function tripal_core_chado_insert($table, $values) {
+function tripal_core_chado_insert($table, $values, $options = array()) {
   $insert_values = array();
   $chado_db = tripal_db_persistent_chado();
 
   // Determine plan of action
   if ($options['statement_name']) {
     $prepared = TRUE;
+    $connection = tripal_db_persistent_chado();
     if ($options['prepare']) {
       $build_sql = TRUE;
     }
@@ -120,6 +131,13 @@ function tripal_core_chado_insert($table, $values) {
     $build_sql = TRUE;
   }
 
+  if (array_key_exists('skip_validation', $options)) {
+    $validate = !$options['skip_validation'];
+  }
+  else {
+    $validate = TRUE;
+  }
+
   // get the table description
   $table_desc = module_invoke_all('chado_' . $table . '_schema');
   if (empty($table_desc)) {
@@ -148,48 +166,50 @@ function tripal_core_chado_insert($table, $values) {
     }
   }
 
-  // check for violation of any unique constraints
-  $ukeys = $table_desc['unique keys'];
-  $ukselect_cols = array();
-  $ukselect_vals = array();
-  if ($ukeys) {
-    foreach ($ukeys as $name => $fields) {
-      foreach ($fields as $index => $field) {
-        // build the arrays for performing a select that will check the contraint
-        array_push($ukselect_cols, $field);
-        $ukselect_vals[$field] = $insert_values[$field];
+  if ($validate) {
+
+    // check for violation of any unique constraints
+    $ukeys = $table_desc['unique keys'];
+    $ukselect_cols = array();
+    $ukselect_vals = array();
+    if ($ukeys) {
+      foreach ($ukeys as $name => $fields) {
+        foreach ($fields as $index => $field) {
+          // build the arrays for performing a select that will check the contraint
+          array_push($ukselect_cols, $field);
+          $ukselect_vals[$field] = $insert_values[$field];
+        }
+        // now check the constraint
+        if (tripal_core_chado_select($table, $ukselect_cols, $ukselect_vals)) {
+          watchdog('tripal_core', "tripal_core_chado_insert: Cannot insert duplicate record into $table table: " . print_r($values, 1), array(), 'WATCHDOG_ERROR');
+          return FALSE;
+        }
       }
-      // now check the constraint
-      if (tripal_core_chado_select($table, $ukselect_cols, $ukselect_vals)) {
-        watchdog('tripal_core', "tripal_core_chado_insert: Cannot insert duplicate record into $table table: " . print_r($values, 1), array(), 'WATCHDOG_ERROR');
+    }
+
+    // if trying to insert a field that is the primary key, make sure it also is unique
+    $pkey = $table_desc['primary key'][0];
+    if ($insert_values[$pkey]) {
+      if (tripal_core_chado_select($table, array($pkey), array($pkey => $insert_values[$pkey]))) {
+        watchdog('tripal_core', "tripal_core_chado_insert: Cannot insert duplicate primary key into $table table: " . print_r($values, 1), array(), 'WATCHDOG_ERROR');
         return FALSE;
       }
     }
-  }
 
-  // if trying to insert a field that is the primary key, make sure it also is unique
-  $pkey = $table_desc['primary key'][0];
-  if ($insert_values[$pkey]) {
-    if (tripal_core_chado_select($table, array($pkey), array($pkey => $insert_values[$pkey]))) {
-      watchdog('tripal_core', "tripal_core_chado_insert: Cannot insert duplicate primary key into $table table: " . print_r($values, 1), array(), 'WATCHDOG_ERROR');
-      return FALSE;
+    // make sure required fields have a value
+    if (!is_array($table_desc['fields'])) {
+      $table_desc['fields'] = array();
+      watchdog('tripal_core', "tripal_core_chado_insert: %table not defined in tripal schema api", array('%table' => $table), 'WATCHDOG WARNING');
     }
-  }
-
-  // make sure required fields have a value
-  $fields = $table_desc['fields'];
-  if (!is_array($fields)) {
-    $fields = array();
-    watchdog('tripal_core', "tripal_core_chado_insert: %table not defined in tripal schema api", array('%table' => $table), 'WATCHDOG WARNING');
-  }
-  foreach ($fields as $field => $def) {
-    // a field is considered missing if it cannot be NULL and there is no default
-    // value for it or it is of type 'serial'
-    if ($def['not NULL'] == 1 and !array_key_exists($field, $insert_values) and !isset($def['default']) and strcmp($def['type'], serial) != 0) {
-      watchdog('tripal_core', "tripal_core_chado_insert: Field $table.$field cannot be NULL: " . print_r($values, 1), array(), 'WATCHDOG_ERROR');
-      return FALSE;
+    foreach ($table_desc['fields'] as $field => $def) {
+      // a field is considered missing if it cannot be NULL and there is no default
+      // value for it or it is of type 'serial'
+      if ($def['not NULL'] == 1 and !array_key_exists($field, $insert_values) and !isset($def['default']) and strcmp($def['type'], serial) != 0) {
+        watchdog('tripal_core', "tripal_core_chado_insert: Field $table.$field cannot be NULL: " . print_r($values, 1), array(), 'WATCHDOG_ERROR');
+        return FALSE;
+      }
     }
-  }
+  } //end of validation
 
   // Now build the insert SQL statement
   $ifields = array(); //contains the names of the fields
@@ -198,17 +218,18 @@ function tripal_core_chado_insert($table, $values) {
   $iplaceholders = array(); // contains $1/$2 placeholders for the prepare query
   $idatatypes = array(); //contains the data type of the fields (int, text, etc.)
   $i = 1;
-  foreach ($insert_values as $field => $value){
+  foreach ($insert_values as $field => $value) {
     $ifields[] = $field;
     $ivalues[] = $value;
-    $iplaceholders[] = '$'.$i;
+    $iplaceholders[] = '$' . $i;
     $i++;
-    if(strcmp($value,'__NULL__')==0){
+    if (strcmp($value, '__NULL__')==0) {
       $itypes[] = "NULL";
       $idatatypes[] = "NULL";
     }
-    elseif(strcmp($fields[$field]['type'],'serial')==0 or
-      strcmp($fields[$field]['type'],'int')==0){
+    elseif (strcasecmp($table_desc['fields'][$field]['type'], 'serial')==0 OR
+      strcasecmp($table_desc['fields'][$field]['type'], 'int')==0 OR
+      strcasecmp($table_desc['fields'][$field]['type'], 'integer')==0) {
       $itypes[] = "%d";
       $idatatypes[] = 'int';
     }
@@ -222,17 +243,15 @@ function tripal_core_chado_insert($table, $values) {
     // prepare the statement
     if ($prepared) {
       $prepare_sql = "PREPARE " . $options['statement_name'] . " (" . implode(', ', $idatatypes) . ") AS INSERT INTO {$table} (" . implode(", ", $ifields) . ") VALUES (" . implode(", ", $iplaceholders) . ")";
-
-      $previous_db = tripal_db_set_active('chado');
-      $status = db_query($prepare_sql);
-      tripal_db_set_active($previous_db);
+      $status = chado_query($prepare_sql);
 
       if (!$status) {
-        watchdog('tripal_core',"tripal_core_chado_insert: not able to prepare '%name' statement for: %sql", array('%name' => $options['statement_name'], '%sql' => $sql), 'WATCHDOG ERROR');
+        watchdog('tripal_core', "tripal_core_chado_insert: not able to prepare '%name' statement for: %sql", array('%name' => $options['statement_name'], '%sql' => $sql), 'WATCHDOG ERROR');
         return FALSE;
-       }
-    } else {
-      $sql = "INSERT INTO {$table} (" . implode(", ",$ifields) . ") VALUES (". implode(", ",$itypes) .")";
+      }
+    }
+    else {
+      $sql = "INSERT INTO {$table} (" . implode(", ", $ifields) . ") VALUES (" . implode(", ", $itypes) . ")";
     }
   }
 
@@ -240,16 +259,14 @@ function tripal_core_chado_insert($table, $values) {
   if ($prepared) {
 
     $sql = "EXECUTE " . $options['statement_name'] . "(" . implode(", ", $itypes) . ")";
+    $result = chado_query($sql, $ivalues);
 
-    $previous_db = tripal_db_set_active('chado');
-    $result = db_query($sql, $ivalues);
-    tripal_db_set_active($previous_db);
     if ($result) {
       // add primary keys to values before return
       $primary_key = array();
       if (!is_array($table_desc['primary key'])) {
         $table_desc['primary key'] = array();
-        watchdog('tripal_core',"tripal_core_chado_insert: %table not defined in tripal schema api", array('%table' => $table), 'WATCHDOG WARNING');
+        watchdog('tripal_core', "tripal_core_chado_insert: %table not defined in tripal schema api", array('%table' => $table), 'WATCHDOG WARNING');
       }
       foreach ($table_desc['primary key'] as $field) {
         $value = db_last_insert_id($table, $field);
@@ -258,7 +275,7 @@ function tripal_core_chado_insert($table, $values) {
       return $values;
     }
     else {
-      watchdog('tripal_core',"tripal_core_chado_insert: not able to execute prepared statement '%name' with values: %values", array('%name' => $options['statement_name'], '%values' => print_r($values,1)), 'WATCHDOG ERROR');
+      watchdog('tripal_core', "tripal_core_chado_insert: not able to execute prepared statement '%name' with values: %values", array('%name' => $options['statement_name'], '%values' => print_r($values, TRUE)), 'WATCHDOG ERROR');
       return FALSE;
     }
   }
@@ -972,6 +989,7 @@ function tripal_core_generate_chado_var($table, $values, $base_options = array()
     }
 
     //if criteria then remove from query
+    // @coder-ignore: only module designers can populate $criteria -not security risk
     $success = drupal_eval('<?php return ' . $criteria . '; ?>');
 //    watchdog('tripal_core',
 //      'Evaluating criteria (%criteria) for field %field in tripal_core_generate_chado_var for %table evaluated to %success',
@@ -1007,6 +1025,7 @@ function tripal_core_generate_chado_var($table, $values, $base_options = array()
           break;
         }
         //if criteria then remove from query
+        // @coder-ignore: only module designers can populate $criteria -not security risk
         $success = drupal_eval('<?php return ' . $criteria . '; ?>');
 //        watchdog('tripal_core',
 //          'Evaluating criteria (%criteria) for field %field of $type in tripal_core_generate_chado_var for %table evaluated to %success',
@@ -1037,6 +1056,7 @@ function tripal_core_generate_chado_var($table, $values, $base_options = array()
       if (db_table_exists('chado_' . $table)) {
         // that has a foreign key to this one ($table_desc['primary key'][0]
         // and to the node table (nid)
+        // @coder-ignore: acting on chado schema rather then drupal schema therefore, table prefixing does not apply
         $sql = "SELECT %s, nid FROM chado_%s WHERE %s=%d";
         $mapping = db_fetch_object(db_query(
           $sql,
@@ -1058,6 +1078,7 @@ function tripal_core_generate_chado_var($table, $values, $base_options = array()
         }
         $criteria = preg_replace('/&gt;field_value&lt; /', $object->{$field_name}, $criteria);
         //if criteria then remove from query
+        // @coder-ignore: only module designers can populate $criteria -not security risk
         $success = drupal_eval('<?php return ' . $criteria . '; ?>');
 //      watchdog('tripal_core',
 //        'Evaluating criteria (%criteria) for field %field in tripal_core_generate_chado_var for   %table evaluated to %success',
@@ -1238,10 +1259,11 @@ function tripal_core_expand_chado_vars($object, $type, $to_expand, $table_option
             $table_options
           );
           if ($foreign_object) {
-            // in the case where the a foreign key relationships exists more
+            // in the case where the foreign key relationships exists more
             // than once with the same table we want to alter the
             // array structure
             if (count($foreign_table_desc['foreign keys'][$base_table]['columns']) > 1) {
+              $object->{$foreign_table} = new stdClass();
               $object->{$foreign_table}->{$left} = $foreign_object;
               $object->expanded = $to_expand;
             }
@@ -1406,10 +1428,17 @@ function tripal_core_exclude_field_from_feature_by_default() {
 }
 
 /**
- *  Use this function instead of db_query() to avoid switching databases
- *  when making query to the chado database
+ * Use this function instead of db_query() to avoid switching databases
+ * when making query to the chado database
+ *
+ * Will use a chado persistent connection if it already exists
+ *
+ * @param $sql
+ *   The sql statement to execute
  */
 function chado_query($sql) {
+  global $active_db;
+
   $args = func_get_args();
   array_shift($args);
   $sql = db_prefix_tables($sql);
@@ -1418,9 +1447,22 @@ function chado_query($sql) {
   }
   _db_query_callback($args, TRUE);
   $sql = preg_replace_callback(DB_QUERY_REGEXP, '_db_query_callback', $sql);
-  $previous_db = tripal_db_set_active('chado');
-  $results = _db_query($sql);
-  tripal_db_set_active($previous_db);
+
+  // Execute the query on the chado database/schema
+  // Use the persistent chado connection if it already exists
+  $persistent_connection = variable_get('tripal_perisistent_chado', NULL);
+  if ($persistent_connection) {
+    $previously_active_db = $active_db;
+    $active_db = $persistent_connection;
+    $results = _db_query($sql);
+    $active_db = $previously_active_db;
+  }
+  else {
+    $previous_db = tripal_db_set_active('chado');
+    $results = _db_query($sql);
+    tripal_db_set_active($previous_db);
+  }
+
   return $results;
 }
 
@@ -1860,21 +1902,23 @@ function tripal_db_set_active($dbname) {
  * @return
  *   A postgresql connection object which can be used by pg_prepare, pg_execute, etc.
  */
-function tripal_db_persistent_chado () {
+function tripal_db_persistent_chado() {
   global $db_url;
 
   // get connection if it already exists
-  $connection = variable_get('tripal_perisistent_chado',NULL);
+  $connection = variable_get('tripal_perisistent_chado', NULL);
 
   if ($connection) {
     return $connection;
 
   // Otherwise we need to set it
-  } else {
+  }
+  else {
     if (is_array($db_url) && isset($db_url['chado'])) {
       $connection = db_connect($db_url['chado']);
       variable_set('tripal_perisistent_chado', $connection);
-    } else {
+    }
+    else {
       $connection = db_connect($db_url);
       variable_set('tripal_perisistent_chado', $connection);
     }
@@ -1887,10 +1931,59 @@ function tripal_db_persistent_chado () {
 /**
  * Release a persistent chado connection
  */
-function tripal_db_release_persistent_chado () {
+function tripal_db_release_persistent_chado() {
   variable_del('tripal_perisistent_chado');
 }
 
+/**
+ * Start a transaction block. Ensures the use of a persistent chado connection
+ */
+function tripal_db_start_transaction() {
+  $connection = tripal_db_persistent_chado();
+  chado_query("BEGIN");
+}
+
+/**
+ * Set a savepoint to roll the current transaction back to if an error is encountered
+ */
+function tripal_db_set_savepoint_transaction($savepoint, $release = FALSE) {
+  // Postgresql requires a savepoint of the same name to be unset before re-use
+  if ($release) {
+    chado_query("RELEASE SAVEPOINT %s", $savepoint);
+  }
+  chado_query("SAVEPOINT %s", $savepoint);
+}
+
+/**
+ * Commit changes made during the current transaction
+ */
+function tripal_db_commit_transaction() {
+  chado_query("COMMIT");
+}
+
+/**
+ * Rollback changes.
+ *
+ * If $savepoint is NULL then rollback to the beginning of the transaction,
+ * Otherwise, rollback to the point at which the named $savepoint was created
+ *
+ * @param $savepoint
+ *   The name of the saved point in the transaction to rollback to
+ */
+function tripal_db_rollback_transaction($savepoint = NULL, $commit = TRUE) {
+
+  if ($savepoint) {
+    chado_query("ROLLBACK TO SAVEPOINT %s", $savepoint);
+  }
+  else {
+    chado_query("ROLLBACK");
+  }
+
+  if ($commit) {
+    tripal_db_commit_transaction();
+  }
+
+}
 
 /**
  * Purpose: Get max rank for a given set of criteria
@@ -2061,6 +2154,7 @@ function tripal_get_chado_custom_schema($table) {
 function tripal_core_chado_schema_exists() {
 
   // This is postgresql-specific code to check the existence of the chado schema
+  // @coder-ignore: acting on pg_catalog schema rather then drupal schema therefore, table prefixing does not apply
   $sql = "SELECT nspname FROM pg_catalog.pg_namespace WHERE nspname = 'chado'";
   if (db_fetch_object(db_query($sql))) {
     return TRUE;

+ 9 - 12
tripal_core/tripal_core.coder_ignores.txt

@@ -2,20 +2,17 @@
 ; file:line:warning-type
 ; where warning-type is one of security, style, sql, i18n, comment, etc.
 
-; This select statement is acting upon the pg_catalog schema rather then the Drupal
-; schema and thus the curly brackets ({}) are not needed.
-tripal_core.schema.api.inc:54:sql
-tripal_core.schema.api.inc:59:sql
-tripal_core.api.inc:1953:sql
-
 ; This query selects from a non-drupal schema where the database prefixes are not
 ; applied and thus the curcly brackets ({}) are not needed
-tripal_core.api.inc:971:sql
+tripal_core.schema.api.inc:55:sql
+tripal_core.schema.api.inc:61:sql
+tripal_core.api.inc:1060:sql
+tripal_core.api.inc:2153:sql
 
 ; Only module designers can create the criteria evaluated by drupal_eval since it
-; is designed in a hook. Since module designers can already write php code to act on 
-; the database and the criteria is never subject to user input, this is not a security 
+; is designed in a hook. Since module designers can already write php code to act on
+; the database and the criteria is never subject to user input, this is not a security
 ; risk.
-tripal_core.api.inc:906:security
-tripal_core.api.inc:941:security
-tripal_core.api.inc:992:security
+tripal_core.api.inc:993:security
+tripal_core.api.inc:1029:security
+tripal_core.api.inc:1082:security

+ 2 - 0
tripal_core/tripal_core.schema.api.inc

@@ -51,11 +51,13 @@
 function tripal_core_get_chado_tables($include_custom = NULL) {
   if (is_array($db_url) AND array_key_exists('chado', $db_url)) {
     $previous_db = tripal_db_set_active('chado');
+    // @coder-ignore: acting on pg_catalog schema rather then drupal schema therefore, table prefixing does not apply
     $sql = 'SELECT tablename FROM pg_tables';
     $resource = db_query($sql);
     tripal_db_set_active($previous_db);
   }
   else {
+    // @coder-ignore: acting on pg_catalog schema rather then drupal schema therefore, table prefixing does not apply
     $sql = "SELECT tablename FROM pg_tables WHERE schemaname='chado'";
     $resource = db_query($sql);
   }

+ 1 - 5
tripal_cv/tripal_cv.coder_ignores.txt

@@ -4,8 +4,4 @@
 
 ; This query selects from a non-drupal schema where the database prefixes are not
 ; applied and thus the curcly brackets ({}) are not needed
-tripal_cv.module:1059:sql
-
-; Need to use POST since this is part of a JS callback
-tripal_cv.module:407:security
-tripal_cv.module:813:security
+tripal_cv.module:1062:sql

+ 3 - 2
tripal_cv/tripal_cv.module

@@ -404,7 +404,7 @@ function tripal_cv_select_form() {
 function tripal_ajax_cv_edit() {
 
   // get the database id, build the form and then return the JSON object
-  $cvid = $_POST['cvid'];
+  $cvid = filter_xss($_POST['cvid']);
   $form = drupal_get_form('tripal_cv_edit_form', $cvid);
   drupal_json(array('status' => TRUE, 'data' => $form));
 
@@ -810,7 +810,7 @@ function tripal_cv_add_cvterm_callback() {
 
   // Retrieve the form from the cache
   $form_state = array('storage' => NULL);
-  $form_build_id = $_POST['form_build_id'];
+  $form_build_id = filter_xss($_POST['form_build_id']);
   $form = form_get_cache($form_build_id, $form_state);
 
   // Preparing to process the form
@@ -1056,6 +1056,7 @@ function tripal_cv_update_cvtermpath($cvid = NULL, $job_id = NULL) {
   print "\nUpdating cvtermpath for $cv->name...\n";
 
   // now fill the cvtermpath table
+  // @coder-ignore: using a function rather then tablename therefore table prefixing doesn't apply
   $sql = "SELECT * FROM fill_cvtermpath('%s')";
   db_query($sql, $cv->name);
   tripal_db_set_active($previous_db);

+ 1 - 1
tripal_cv/tripal_cv.views.inc

@@ -64,7 +64,7 @@ function tripal_cv_views_data() {
     );
     foreach ($tables as $tablename) {
       if (!tripal_views_is_integrated($tablename, 10)) {
-        $table_integration_array = tripal_views_get_integration_array_for_chado_table($tablename,FALSE);
+        $table_integration_array = tripal_views_get_integration_array_for_chado_table($tablename, FALSE);
         tripal_views_integration_add_entry($table_integration_array);
       }
     }

+ 73 - 74
tripal_db/tripal_db.api.inc

@@ -298,86 +298,85 @@ function tripal_db_chado_dbxref_schema() {
   return $description;
 }
 /**
-* Adds a new database to the Chado DB table and returns the DB object.
-*
-* @param $dbname
-*   The name of the database. This name is usually used as the prefix for
-*   CV term accessions
-* @param $description
-*   Optional. A description of the database.  By default no description is required.
-* @param $url
-*   Optional. The URL for the database
-* @param $urlprefix
-*   Optional. The URL that is to be used as a prefix when constructing a link to
-*   a database term
-* @param $update
-*   Optional. 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.
-*
-* @ingroup tripal_db_api
-*/
+ * Adds a new database to the Chado DB table and returns the DB object.
+ *
+ * @param $dbname
+ *   The name of the database. This name is usually used as the prefix for
+ *   CV term accessions
+ * @param $description
+ *   Optional. A description of the database.  By default no description is required.
+ * @param $url
+ *   Optional. The URL for the database
+ * @param $urlprefix
+ *   Optional. The URL that is to be used as a prefix when constructing a link to
+ *   a database term
+ * @param $update
+ *   Optional. 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.
+ *
+ * @ingroup tripal_db_api
+ */
 function tripal_db_add_db($dbname, $description='', $url='', $urlprefix='', $update=0) {
 
+  $values = array(
+    'name' => $dbname,
+    'description' => $description,
+    'url' => $url,
+    'urlprefix' => $urlprefix
+  );
 
-   $values = array(
-      'name' => $dbname,
-      'description' => $description,
-      'url' => $url,
-      'urlprefix' => $urlprefix
-   );
-
-   $db_sql = "SELECT * FROM {db} WHERE name ='%s'";
-   $db = db_fetch_object(db_query($db_sql, $dbname));
-   if (!$db) {
-      if (!tripal_core_chado_insert('db', $values)) {
-         watchdog('tripal_db', "Cannot create db '$dbname'.", NULL, WATCHDOG_WARNING);
-         return 0;
-      }
-      $db = tripal_core_chado_select('db', array('*'), $values);
-   }
-   elseif ($update) {
-      $match = array('db_id' => $db->db_id);
-      if (!tripal_core_chado_update('db', $match, $values)) {
-         watchdog('tripal_db', "Cannot update db '$dbname'.", NULL, WATCHDOG_WARNING);
-         return 0;
-      }
-      $db = tripal_core_chado_select('db', array('*'), $values);
-   }
-   else {
-      return $db;
-   }
+  $db_sql = "SELECT * FROM {db} WHERE name ='%s'";
+  $db = db_fetch_object(db_query($db_sql, $dbname));
+  if (!$db) {
+    if (!tripal_core_chado_insert('db', $values)) {
+      watchdog('tripal_db', "Cannot create db '$dbname'.", NULL, WATCHDOG_WARNING);
+      return 0;
+    }
+    $db = tripal_core_chado_select('db', array('*'), $values);
+  }
+  elseif ($update) {
+    $match = array('db_id' => $db->db_id);
+    if (!tripal_core_chado_update('db', $match, $values)) {
+      watchdog('tripal_db', "Cannot update db '$dbname'.", NULL, WATCHDOG_WARNING);
+      return 0;
+    }
+    $db = tripal_core_chado_select('db', array('*'), $values);
+  }
+  else {
+    return $db;
+  }
 }
 /**
-*
-* @ingroup tripal_db_api
-*/
+ *
+ * @ingroup tripal_db_api
+ */
 function tripal_db_add_dbxref($db_id, $accession, $version='', $description='') {
 
-   // check to see if the dbxref exists if not, add it
-   $dbxsql = "
-      SELECT DBX.dbxref_id, DBX.db_id, DBX.description, DBX.version, DBX.accession,
-         DB.name as db_name
-      FROM {dbxref} DBX
-         INNER JOIN db DB on DB.db_id = DBX.db_id
-      WHERE DBX.db_id = %d and DBX.accession = '%s'
-   ";
-   $dbxref = db_fetch_object(db_query($dbxsql, $db_id, $accession));
-   if (!$dbxref) {
-      $sql = "
-         INSERT INTO {dbxref} (db_id, accession, version, description)
-         VALUES (%d,'%s','%s','%s')
-      ";
-      if (!db_query($sql, $db_id, $accession, $version, $description)) {
-         watchdog('tripal_cv', "Failed to insert the dbxref record $accession", NULL, WATCHDOG_WARNING);
-         return 0;
-      }
-      print "Added Dbxref accession: $accession\n";
-      $dbxref = db_fetch_object(db_query($dbxsql, $db_id, $accession));
-   }
-   return $dbxref;
+  // check to see if the dbxref exists if not, add it
+  $dbxsql = "
+    SELECT DBX.dbxref_id, DBX.db_id, DBX.description, DBX.version, DBX.accession,
+       DB.name as db_name
+    FROM {dbxref} DBX
+       INNER JOIN db DB on DB.db_id = DBX.db_id
+    WHERE DBX.db_id = %d and DBX.accession = '%s'
+  ";
+  $dbxref = db_fetch_object(db_query($dbxsql, $db_id, $accession));
+  if (!$dbxref) {
+    $sql = "
+       INSERT INTO {dbxref} (db_id, accession, version, description)
+       VALUES (%d,'%s','%s','%s')
+    ";
+    if (!db_query($sql, $db_id, $accession, $version, $description)) {
+      watchdog('tripal_cv', "Failed to insert the dbxref record $accession", NULL, WATCHDOG_WARNING);
+      return 0;
+    }
+    print "Added Dbxref accession: $accession\n";
+    $dbxref = db_fetch_object(db_query($dbxsql, $db_id, $accession));
+  }
+  return $dbxref;
 
 }

+ 21 - 21
tripal_db/tripal_db.install

@@ -6,22 +6,22 @@
  */
 
 /**
-*  Implementation of hook_install();
-*
-* @ingroup tripal_db
-*/
+ * Implementation of hook_install().
+ *
+ * @ingroup tripal_db
+ */
 function tripal_db_install() {
 
-   // create the module's data directory
-   tripal_create_moddir('tripal_db');
+  // create the module's data directory
+  tripal_create_moddir('tripal_db');
 
 }
 
 /**
-* Implementation of hook_uninstall()
-*
-* @ingroup tripal_db
-*/
+ * Implementation of hook_uninstall().
+ *
+ * @ingroup tripal_db
+ */
 function tripal_db_uninstall() {
 
 }
@@ -33,15 +33,15 @@ function tripal_db_uninstall() {
  * @ingroup tripal_db
  */
 function tripal_db_requirements($phase) {
-   $requirements = array();
-   if ($phase == 'install') {
-      if (!function_exists('tripal_create_moddir')) {
-         $requirements ['tripal_db'] = array(
-            'title' => "tripal_db",
-            'value' => "Required modules must be installed first before Tripal DB module can be installed. Please try again.",
-            'severity' => REQUIREMENT_ERROR,
-         );
-      }
-   }
-   return $requirements;
+  $requirements = array();
+  if ($phase == 'install') {
+    if (!function_exists('tripal_create_moddir')) {
+      $requirements ['tripal_db'] = array(
+        'title' => "tripal_db",
+        'value' => "Required modules must be installed first before Tripal DB module can be installed. Please try again.",
+        'severity' => REQUIREMENT_ERROR,
+      );
+    }
+  }
+  return $requirements;
 }

+ 238 - 239
tripal_db/tripal_db.module

@@ -8,69 +8,69 @@ require_once "tripal_db.api.inc";
  */
 
 /**
-*
-* @ingroup tripal_db
-*/
+ *
+ * @ingroup tripal_db
+ */
 function tripal_db_init() {
 
-   // add the tripal_db JS and CSS
-   drupal_add_css(drupal_get_path('theme', 'tripal') . '/css/tripal_db.css');
-   drupal_add_js(drupal_get_path('theme', 'tripal') . '/js/tripal_db.js');
+  // add the tripal_db JS and CSS
+  drupal_add_css(drupal_get_path('theme', 'tripal') . '/css/tripal_db.css');
+  drupal_add_js(drupal_get_path('theme', 'tripal') . '/js/tripal_db.js');
 }
 /**
-*
-* @ingroup tripal_db
-*/
+ *
+ * @ingroup tripal_db
+ */
 function tripal_db_menu() {
-   $items = array();
-
-   $items['admin/tripal/tripal_db'] = array(
-     'title' => 'Databases',
-     'description' => 'Basic Description of Tripal DB Module Functionality',
-     'page callback' => 'tripal_db_module_description_page',
-     'access arguments' => array('administer site configuration'),
-     'type' => MENU_NORMAL_ITEM,
-   );
-
-   $items['admin/tripal/tripal_db/edit_db'] = array(
-     'title' => 'Update/Delete Database References',
-     'description' => 'Manage Databases ',
-     'page callback' => 'tripal_db_admin_page',
-     'access arguments' => array('administer site configuration'),
-     'type' => MENU_NORMAL_ITEM,
-   );
-
-   $items['admin/tripal/tripal_db/add_db'] = array(
-     'title' => 'Add a Database',
-     'page callback' => 'drupal_get_form',
-     'page arguments' => array('tripal_db_form'),
-     'access arguments' => array('access administration pages'),
-     'type' => MENU_NORMAL_ITEM,
-   );
-   $items['admin/tripal/tripal_db/edit/js'] = array(
-     'title' => 'Edit Databases',
-     'page callback' => 'tripal_ajax_db_edit',
-     'access arguments' => array('access administration pages'),
-     'type' => MENU_CALLBACK,
-   );
-
-   return $items;
+  $items = array();
+
+  $items['admin/tripal/tripal_db'] = array(
+    'title' => 'Databases',
+    'description' => 'Basic Description of Tripal DB Module Functionality',
+    'page callback' => 'tripal_db_module_description_page',
+    'access arguments' => array('administer site configuration'),
+    'type' => MENU_NORMAL_ITEM,
+  );
+
+  $items['admin/tripal/tripal_db/edit_db'] = array(
+    'title' => 'Update/Delete Database References',
+    'description' => 'Manage Databases ',
+    'page callback' => 'tripal_db_admin_page',
+    'access arguments' => array('administer site configuration'),
+    'type' => MENU_NORMAL_ITEM,
+  );
+
+  $items['admin/tripal/tripal_db/add_db'] = array(
+    'title' => 'Add a Database',
+    'page callback' => 'drupal_get_form',
+    'page arguments' => array('tripal_db_form'),
+    'access arguments' => array('access administration pages'),
+    'type' => MENU_NORMAL_ITEM,
+  );
+  $items['admin/tripal/tripal_db/edit/js'] = array(
+    'title' => 'Edit Databases',
+    'page callback' => 'tripal_ajax_db_edit',
+    'access arguments' => array('access administration pages'),
+    'type' => MENU_CALLBACK,
+  );
+
+  return $items;
 }
 
 /**
-*  Set the permission types that the chado module uses.  Essentially we
-*  want permissionis that protect creation, editing and deleting of chado
-*  data objects
-*
-* @ingroup tripal_db
-*/
+ *  Set the permission types that the chado module uses.  Essentially we
+ *  want permissionis that protect creation, editing and deleting of chado
+ *  data objects
+ *
+ * @ingroup tripal_db
+ */
 function tripal_db_perm() {
-   return array(
-      'access chado_db content',
-      'create chado_db content',
-      'delete chado_db content',
-      'edit chado_db content',
-   );
+  return array(
+    'access chado_db content',
+    'create chado_db content',
+    'delete chado_db content',
+    'edit chado_db content',
+  );
 }
 
 /**
@@ -137,22 +137,22 @@ function tripal_db_module_description_page() {
 }
 
 /**
-*
-*
-* @ingroup tripal_db
-*/
+ *
+ *
+ * @ingroup tripal_db
+ */
 function tripal_db_admin_page() {
-   $add_url = url("admin/tripal/tripal_db/add_db");
-   $output = "<a href=\"$add_url\">Add a new external database</a>";
-   $output .= drupal_get_form('tripal_db_select_form');
-   $output .= '<div id="db-edit-div">Please select a database above to view or edit</div>';
-   return $output;
+  $add_url = url("admin/tripal/tripal_db/add_db");
+  $output = "<a href=\"$add_url\">Add a new external database</a>";
+  $output .= drupal_get_form('tripal_db_select_form');
+  $output .= '<div id="db-edit-div">Please select a database above to view or edit</div>';
+  return $output;
 }
 /**
-*
-*
-* @ingroup tripal_db
-*/
+ *
+ *
+ * @ingroup tripal_db
+ */
 function tripal_db_select_form() {
 
   $previous_db = tripal_db_set_active('chado');  // use chado database
@@ -162,206 +162,205 @@ function tripal_db_select_form() {
   tripal_db_set_active($previous_db); // use drupal database
 
   $dbs = array();
-   $dbs[] = '';
+  $dbs[] = '';
   while ($db = db_fetch_object($results)) {
     $dbs[$db->db_id] = $db->name;
   }
 
   $form['dbid'] = array(
-      '#title' => t('External Database Name'),
-      '#type' => 'select',
-      '#options' => $dbs,
-      '#ahah' => array(
-         'path' => 'admin/tripal/tripal_db/edit/js',
-         'wrapper' => 'db-edit-div',
-         'effect' => 'fade',
-         'event' => 'change',
-         'method' => 'replace',
-      ),
+    '#title' => t('External Database Name'),
+    '#type' => 'select',
+    '#options' => $dbs,
+    '#ahah' => array(
+      'path' => 'admin/tripal/tripal_db/edit/js',
+      'wrapper' => 'db-edit-div',
+      'effect' => 'fade',
+      'event' => 'change',
+      'method' => 'replace',
+    ),
   );
 
-   return $form;
+  return $form;
 }
 /**
-*
-* @ingroup tripal_db
-*/
+ *
+ * @ingroup tripal_db
+ */
 function tripal_ajax_db_edit() {
-   // get the database id, build the form and then return the JSON object
-   $dbid = $_POST['dbid'];
-   $form = drupal_get_form('tripal_db_form', $dbid);
-   drupal_json(array('status' => TRUE, 'data' => $form));
+  // get the database id, build the form and then return the JSON object
+  $dbid = filter_xss($_POST['dbid']);
+  $form = drupal_get_form('tripal_db_form', $dbid);
+  drupal_json(array('status' => TRUE, 'data' => $form));
 }
 /**
-*
-* @ingroup tripal_db
-*/
+ *
+ * @ingroup tripal_db
+ */
 function tripal_db_form(&$form_state = NULL, $dbid = NULL) {
 
-   // get this requested database
-   if ($dbid) {
-      $sql = "SELECT * FROM {db} WHERE db_id = %d ";
-      $previous_db = tripal_db_set_active('chado');
-      $db = db_fetch_object(db_query($sql, $dbid));
-      tripal_db_set_active($previous_db);
+  // get this requested database
+  if ($dbid) {
+    $sql = "SELECT * FROM {db} WHERE db_id = %d ";
+    $previous_db = tripal_db_set_active('chado');
+    $db = db_fetch_object(db_query($sql, $dbid));
+    tripal_db_set_active($previous_db);
+
+
+    // set the default values.  If there is a value set in the
+    // form_state then let's use that, otherwise, we'll pull
+    // the values from the database
+    $default_db = $form_state['values']['name'];
+    $default_desc = $form_state['values']['description'];
+    $default_url = $form_state['values']['url'];
+    $default_urlprefix = $form_state['values']['urlprefix'];
+    if (!$default_db) {
+      $default_db = $db->name;
+    }
+    if (!$default_desc) {
+      $default_desc = $db->description;
+    }
+    if (!$default_url) {
+      $default_url = $db->url;
+    }
+    if (!$default_urlprefix) {
+      $default_urlprefix = $db->urlprefix;
+    }
+    $action = 'Update';
+  }
+  else {
+    $action = 'Add';
+  }
 
+  $form['dbid'] = array(
+    '#type' => 'hidden',
+    '#value' => $dbid
+  );
 
-      // set the default values.  If there is a value set in the
-      // form_state then let's use that, otherwise, we'll pull
-      // the values from the database
-      $default_db = $form_state['values']['name'];
-      $default_desc = $form_state['values']['description'];
-      $default_url = $form_state['values']['url'];
-      $default_urlprefix = $form_state['values']['urlprefix'];
-      if (!$default_db) {
-         $default_db = $db->name;
-      }
-      if (!$default_desc) {
-         $default_desc = $db->description;
-      }
-      if (!$default_url) {
-         $default_url = $db->url;
-      }
-      if (!$default_urlprefix) {
-         $default_urlprefix = $db->urlprefix;
-      }
-      $action = 'Update';
-   }
-   else {
-      $action = 'Add';
-   }
-
-   $form['dbid'] = array(
-      '#type' => 'hidden',
-      '#value' => $dbid
-   );
-
-   $form['name']= array(
-      '#type'          => 'textfield',
-      '#title'         => t("Database Name"),
-      '#description'   => t('Please enter the name for this external database.'),
-      '#required'      => TRUE,
-      '#default_value' => $default_db,
-      '#weight'        => 1
-   );
-
-   $form['description']= array(
-      '#type'          => 'textarea',
-      '#title'         => t('Description'),
-      '#description'   => t('Please enter a description for this database'),
-      '#default_value' => $default_desc,
-      '#weight'        => 2
-   );
-   $form['url']= array(
-      '#type'          => 'textfield',
-      '#title'         => t('URL'),
-      '#description'   => t('Please enter the web address for this database.'),
-      '#default_value' => $default_url,
-      '#weight'        => 3
-   );
-   $form['urlprefix']= array(
-      '#type'          => 'textfield',
-      '#title'         => t('URL prefix'),
-      '#description'   => t('Tripal can provide links to external databases when accession numbers or unique identifiers are known.  Typically, a database will provide a unique web address for each accession and the accession usually is the last component of the page address.  Please enter the web address, minus the accession number for this database.  When an accession number is present, Tripal will combine this web address with the accession and provide a link to the external site.'),
-      '#default_value' => $default_urlprefix,
-      '#weight'        => 4
-   );
-
-
-   if (strcmp($action, 'Update')==0) {
-      $form['update'] = array(
-        '#type'         => 'submit',
-        '#value'        => t('Update'),
-        '#weight'       => 5,
-        '#executes_submit_callback' => TRUE,
-      );
-      $form['delete'] = array(
-        '#type'         => 'submit',
-        '#value'        => t('Delete'),
-        '#weight'       => 6,
-        '#executes_submit_callback' => TRUE,
-      );
-   }
-   else {
-      $form['add'] = array(
-        '#type'         => 'submit',
-        '#value'        => t('Add'),
-        '#weight'       => 5,
-        '#executes_submit_callback' => TRUE,
-      );
-   }
-   $form['#redirect'] = 'admin/tripal/tripal_db';
-
-
-   return $form;
+  $form['name']= array(
+    '#type'          => 'textfield',
+    '#title'         => t("Database Name"),
+    '#description'   => t('Please enter the name for this external database.'),
+    '#required'      => TRUE,
+    '#default_value' => $default_db,
+    '#weight'        => 1
+  );
+
+  $form['description']= array(
+    '#type'          => 'textarea',
+    '#title'         => t('Description'),
+    '#description'   => t('Please enter a description for this database'),
+    '#default_value' => $default_desc,
+    '#weight'        => 2
+  );
+  $form['url']= array(
+    '#type'          => 'textfield',
+    '#title'         => t('URL'),
+    '#description'   => t('Please enter the web address for this database.'),
+    '#default_value' => $default_url,
+    '#weight'        => 3
+  );
+  $form['urlprefix']= array(
+    '#type'          => 'textfield',
+    '#title'         => t('URL prefix'),
+    '#description'   => t('Tripal can provide links to external databases when accession numbers or unique identifiers are known.  Typically, a database will provide a unique web address for each accession and the accession usually is the last component of the page address.  Please enter the web address, minus the accession number for this database.  When an accession number is present, Tripal will combine this web address with the accession and provide a link to the external site.'),
+    '#default_value' => $default_urlprefix,
+    '#weight'        => 4
+  );
+
+
+  if (strcmp($action, 'Update')==0) {
+    $form['update'] = array(
+      '#type'         => 'submit',
+      '#value'        => t('Update'),
+      '#weight'       => 5,
+      '#executes_submit_callback' => TRUE,
+    );
+    $form['delete'] = array(
+      '#type'         => 'submit',
+      '#value'        => t('Delete'),
+      '#weight'       => 6,
+      '#executes_submit_callback' => TRUE,
+    );
+  }
+  else {
+    $form['add'] = array(
+      '#type'         => 'submit',
+      '#value'        => t('Add'),
+      '#weight'       => 5,
+      '#executes_submit_callback' => TRUE,
+    );
+  }
+  $form['#redirect'] = 'admin/tripal/tripal_db';
+
+
+  return $form;
 }
 /**
-*
-* @ingroup tripal_db
-*/
+ *
+ * @ingroup tripal_db
+ */
 function tripal_db_form_submit($form, &$form_state) {
 
-   $name =  $form_state['values']['name'];
-   $desc =  $form_state['values']['description'];
-   $url  =  $form_state['values']['url'];
-   $urlp =  $form_state['values']['urlprefix'];
-   $dbid =  $form_state['values']['dbid'];
-   $op   =  $form_state['values']['op'];
-
-   if ($dbid) {
-      if (strcmp($op, 'Update')==0) {
-         $sql = "
-            UPDATE {db} SET
-              name = '%s',
-              description = '%s',
-              url = '%s',
-              urlprefix = '%s'
-            WHERE db_id = %d
-         ";
-         $previous_db = tripal_db_set_active('chado');
-         $db = db_query($sql, $name, $desc, $url, $urlp, $dbid);
-         tripal_db_set_active($previous_db);
-         if ($db) {
-           drupal_set_message("External database updated");
-         }
-         else {
-           drupal_set_message("Failed to update external database.");
-         }
+  $name =  $form_state['values']['name'];
+  $desc =  $form_state['values']['description'];
+  $url  =  $form_state['values']['url'];
+  $urlp =  $form_state['values']['urlprefix'];
+  $dbid =  $form_state['values']['dbid'];
+  $op   =  $form_state['values']['op'];
+
+  if ($dbid) {
+    if (strcmp($op, 'Update')==0) {
+      $sql = "
+        UPDATE {db} SET
+          name = '%s',
+          description = '%s',
+          url = '%s',
+          urlprefix = '%s'
+        WHERE db_id = %d
+      ";
+      $previous_db = tripal_db_set_active('chado');
+      $db = db_query($sql, $name, $desc, $url, $urlp, $dbid);
+      tripal_db_set_active($previous_db);
+      if ($db) {
+        drupal_set_message(t("External database updated"));
       }
-      if (strcmp($op, 'Delete')==0) {
-         $sql = "
-            DELETE FROM {db}
-            WHERE db_id = %d
-         ";
-         $previous_db = tripal_db_set_active('chado');
-         $db = db_query($sql, $dbid);
-         tripal_db_set_active($previous_db);
-         if ($db) {
-           drupal_set_message("External database deleted");
-         }
-         else {
-           drupal_set_message("Failed to delete external database.");
-         }
+      else {
+        drupal_set_message(t("Failed to update external database."));
       }
-   }
-   else {
+    }
+    if (strcmp($op, 'Delete')==0) {
       $sql = "
-         INSERT INTO {db}
-          (name,description,url,urlprefix)
-         VALUES
-          ('%s','%s','%s','%s')
-      ";
+        DELETE FROM {db}
+        WHERE db_id = %d
+        ";
       $previous_db = tripal_db_set_active('chado');
-      $db = db_query($sql, $name, $desc, $url, $urlp);
+      $db = db_query($sql, $dbid);
       tripal_db_set_active($previous_db);
       if ($db) {
-        drupal_set_message("External database added");
+        drupal_set_message(t("External database deleted"));
       }
       else {
-        drupal_set_message("Failed to add external database.");
+        drupal_set_message(t("Failed to delete external database."));
       }
-   }
+    }
+  }
+  else {
+    $sql = "
+          INSERT INTO {db}
+          (name,description,url,urlprefix)
+          VALUES
+          ('%s','%s','%s','%s')
+          ";
+    $previous_db = tripal_db_set_active('chado');
+    $db = db_query($sql, $name, $desc, $url, $urlp);
+    tripal_db_set_active($previous_db);
+    if ($db) {
+      drupal_set_message(t("External database added"));
+    }
+    else {
+      drupal_set_message(t("Failed to add external database."));
+    }
+  }
 
-   return '';
+  return '';
 }
-

+ 2 - 2
tripal_db/tripal_db.views.inc

@@ -38,7 +38,7 @@ function tripal_db_views_data()  {
     );
     foreach ($tables as $tablename) {
       if (!tripal_views_is_integrated($tablename, 10)) {
-        $table_integration_array = tripal_views_get_integration_array_for_chado_table($tablename,TRUE);
+        $table_integration_array = tripal_views_get_integration_array_for_chado_table($tablename, TRUE);
         tripal_views_integration_add_entry($table_integration_array);
       }
     }
@@ -49,7 +49,7 @@ function tripal_db_views_data()  {
     );
     foreach ($tables as $tablename) {
       if (!tripal_views_is_integrated($tablename, 10)) {
-        $table_integration_array = tripal_views_get_integration_array_for_chado_table($tablename,FALSE);
+        $table_integration_array = tripal_views_get_integration_array_for_chado_table($tablename, FALSE);
         tripal_views_integration_add_entry($table_integration_array);
       }
     }

+ 665 - 644
tripal_feature/fasta_loader.php

@@ -1,5 +1,11 @@
 <?php
 
+/**
+ * @file
+ * @todo Add file header description
+ */
+
+
 /**
  * @defgroup fasta_loader FASTA Feature Loader
  * @{
@@ -7,264 +13,264 @@
  * @}
  * @ingroup tripal_feature
  */
- 
+
 /**
  *
  *
  * @ingroup fasta_loader
  */
-function tripal_feature_fasta_load_form (){
-
-   $form['fasta_file']= array(
-      '#type'          => 'textfield',
-      '#title'         => t('FASTA File'),
-      '#description'   => t('Please enter the full system path for the FASTA file, or a path within the Drupal
-                             installation (e.g. /sites/default/files/xyz.obo).  The path must be accessible to the
-                             server on which this Drupal instance is running.'),
-      '#required' => TRUE,
-   );
-
-   // get the list of organisms
-   $sql = "SELECT * FROM {organism} ORDER BY genus, species";
-   $previous_db = tripal_db_set_active('chado');  // use chado database
-   $org_rset = db_query($sql);
-   tripal_db_set_active($previous_db);  // now use drupal database
-   $organisms = array();
-   $organisms[''] = '';
-   while($organism = db_fetch_object($org_rset)){
-      $organisms[$organism->organism_id] = "$organism->genus $organism->species ($organism->common_name)";
-   }
-   $form['organism_id'] = array (
-     '#title'       => t('Organism'),
-     '#type'        => t('select'),
-     '#description' => t("Choose the organism to which these sequences are associated "),
-     '#required'    => TRUE,
-     '#options'     => $organisms,
-   );
-
-   $form['seqtype']= array(
-      '#type' => 'textfield',
-      '#title' => t('Sequence Type'),
-      '#required' => TRUE,
-      '#description' => t('Please enter the Sequence Ontology term that describes the sequences in the FASTA file.'),
-   );
-
-
-   // get the list of organisms
-   $sql = "SELECT L.library_id, L.name, CVT.name as type
-           FROM {library} L
-              INNER JOIN {cvterm} CVT ON L.type_id = CVT.cvterm_id
-           ORDER BY name";
-   $previous_db = tripal_db_set_active('chado');  // use chado database
-   $lib_rset = db_query($sql);
-   tripal_db_set_active($previous_db);  // now use drupal database
-   $libraries = array();
-   $libraries[''] = '';
-   while($library = db_fetch_object($lib_rset)){
-      $libraries[$library->library_id] = "$library->name ($library->type)";
-   }
-//   $form['library_id'] = array (
-//     '#title'       => t('Library'),
-//     '#type'        => t('select'),
-//     '#description' => t("Choose the library to which these sequences are associated "),
-//     '#required'    => FALSE,
-//     '#options'     => $libraries,
-//     '#weight'      => 5,
-//   );
-   $form['method']= array(
-      '#type' => 'radios',
-      '#title' => 'Method',
-      '#required' => TRUE,
-      '#options' => array(
-         t('Insert only'),
-         t('Update only'),
-         t('Insert and update'),
-      ),
-      '#description' => t('Select how features in the FASTA file are handled.  
-         Select "Insert only" to insert the new features. If a feature already 
-         exists with the same name or unique name and type then it is skipped.
-         Select "Update only" to only update featues that already exist in the
-         database.  Select "Insert and Update" to insert features that do
-         not exist and upate those that do.'),
-      '#default_value' => 2,
-   );
-
-$form['match_type']= array(
-      '#type' => 'radios',
-      '#title' => 'Name Match Type',
-      '#required' => TRUE,
-      '#options' => array(
-         t('Name'),
-         t('Unique name'),
-      ),
-      '#description' => t('Feature data is stored in Chado with both a human-readable
-        name and a unique name. If the features in your FASTA file are identified using
-        a human-readable name then select the "Name" button. If your features are
-        identified using the unique name then select the "Unique name" button.  If you 
-        loaded your features first using the GFF loader then the unique name of each
-        features were indicated by the "ID=" attribute and the name by the "Name=" attribute.
-        By default, the FASTA loader will use the first word (character string
-        before the first space) as  the name for your feature. If 
-        this does not uniquely identify your feature consider specifying a regular expression in the advanced section below. 
-        Additionally, you may import both a name and a unique name for each sequence using the advanced options. 
-        When updating a sequence, the value selected here will be used to identify the sequence in the 
-        database in combination with any regular expression provided below.'),
-      '#default_value' => 1,
-   );
-
-   $form['analysis'] = array(
-      '#type' => 'fieldset',
-      '#title' => t('Analysis Used to Derive Features'),
-      '#collapsed' => TRUE
-   ); 
-   $form['analysis']['desc'] = array(
-      '#type' => 'markup',
-      '#value' => t("Why specify an analysis for a data load?  All data comes 
-         from some place, even if downloaded from Genbank. By specifying
-         analysis details for all data uploads, it allows an end user to reproduce the
-         data set, but at least indicates the source of the data."), 
-   );
-
-   // get the list of organisms
-   $sql = "SELECT * FROM {analysis} ORDER BY name";
-   $previous_db = tripal_db_set_active('chado');  // use chado database
-   $org_rset = db_query($sql);
-   tripal_db_set_active($previous_db);  // now use drupal database
-   $analyses = array();
-   $analyses[''] = '';
-   while($analysis = db_fetch_object($org_rset)){
-      $analyses[$analysis->analysis_id] = "$analysis->name ($analysis->program $analysis->programversion, $analysis->sourcename)";
-   }
-   $form['analysis']['analysis_id'] = array (
-     '#title'       => t('Analysis'),
-     '#type'        => t('select'),
-     '#description' => t("Choose the analysis to which these features are associated "),
-     '#required'    => TRUE,
-     '#options'     => $analyses,
-   );
-
-   // Advanced Options
-   $form['advanced'] = array(
-      '#type' => 'fieldset',
-      '#title' => t('Advanced Options'),
-      '#collapsed' => TRUE
-   );
-   $form['advanced']['re_help']= array(
-      '#type' => 'item',
-      '#value' => t('A regular expression is an advanced method for extracting information from a string of text.  
-                     Your FASTA file may contain both a human-readable name and a unique name for each sequence.  
-                     If you want to import
-                     both the name and unique name for all sequences, then you must provide regular expressions 
-                     so that the loader knows how to separate them.  
-                     Otherwise the name and uniquename will be the same.  
-                     By default, this loader will use the first word in the definition 
-                     lines of the FASTA file
-                     as the name or unique name of the feature.'),
-   );
-   $form['advanced']['re_name']= array(
-      '#type' => 'textfield',
-      '#title' => t('Regular expression for the name'),
-      '#required' => FALSE,
-      '#description' => t('Enter the regular expression that will extract the 
-         feature name from the FASTA definition line. For example, for a 
-         defintion line with a name and unique name separated by a bar \'|\' (>seqname|uniquename), 
-         the regular expression for the name would be, "^(.*?)\|.*$".'),
-   );  
-   $form['advanced']['re_uname']= array(
-      '#type' => 'textfield',
-      '#title' => t('Regular expression for the unique name'),
-      '#required' => FALSE,
-      '#description' => t('Enter the regular expression that will extract the 
-         feature name from the FASTA definition line. For example, for a 
-         defintion line with a name and unique name separated by a bar \'|\' (>seqname|uniquename), 
-         the regular expression for the unique name would be "^.*?\|(.*)$").'),
-   );   
- 
-
-   // Advanced database cross-reference optoins
-   $form['advanced']['db'] = array(
-      '#type' => 'fieldset',
-      '#title' => t('External Database Reference'),
-      '#weight'=> 6,
-      '#collapsed' => TRUE
-   );
-   $form['advanced']['db']['re_accession']= array(
-      '#type' => 'textfield',
-      '#title' => t('Regular expression for the accession'),
-      '#required' => FALSE,
-      '#description' => t('Enter the regular expression that will extract the accession for the external database for each feature from the FASTA definition line.'),
-      '#weight' => 2
-   ); 
+function tripal_feature_fasta_load_form( ) {
+
+  $form['fasta_file']= array(
+    '#type'          => 'textfield',
+    '#title'         => t('FASTA File'),
+    '#description'   => t('Please enter the full system path for the FASTA file, or a path within the Drupal
+                           installation (e.g. /sites/default/files/xyz.obo).  The path must be accessible to the
+                           server on which this Drupal instance is running.'),
+    '#required' => TRUE,
+  );
+
+  // get the list of organisms
+  $sql = "SELECT * FROM {organism} ORDER BY genus, species";
+  $previous_db = tripal_db_set_active('chado');  // use chado database
+  $org_rset = db_query($sql);
+  tripal_db_set_active($previous_db);  // now use drupal database
+  $organisms = array();
+  $organisms[''] = '';
+  while ($organism = db_fetch_object($org_rset)) {
+    $organisms[$organism->organism_id] = "$organism->genus $organism->species ($organism->common_name)";
+  }
+  $form['organism_id'] = array(
+   '#title'       => t('Organism'),
+   '#type'        => t('select'),
+   '#description' => t("Choose the organism to which these sequences are associated"),
+   '#required'    => TRUE,
+   '#options'     => $organisms,
+  );
+
+  $form['seqtype']= array(
+    '#type' => 'textfield',
+    '#title' => t('Sequence Type'),
+    '#required' => TRUE,
+    '#description' => t('Please enter the Sequence Ontology term that describes the sequences in the FASTA file.'),
+  );
+
+
+  // get the list of organisms
+  $sql = "SELECT L.library_id, L.name, CVT.name as type
+         FROM {library} L
+            INNER JOIN {cvterm} CVT ON L.type_id = CVT.cvterm_id
+         ORDER BY name";
+  $previous_db = tripal_db_set_active('chado');  // use chado database
+  $lib_rset = db_query($sql);
+  tripal_db_set_active($previous_db);  // now use drupal database
+  $libraries = array();
+  $libraries[''] = '';
+  while ($library = db_fetch_object($lib_rset)) {
+    $libraries[$library->library_id] = "$library->name ($library->type)";
+  }
+  //   $form['library_id'] = array (
+  //     '#title'       => t('Library'),
+  //     '#type'        => t('select'),
+  //     '#description' => t("Choose the library to which these sequences are associated "),
+  //     '#required'    => FALSE,
+  //     '#options'     => $libraries,
+  //     '#weight'      => 5,
+  //   );
+  $form['method']= array(
+    '#type' => 'radios',
+    '#title' => 'Method',
+    '#required' => TRUE,
+    '#options' => array(
+      t('Insert only'),
+      t('Update only'),
+      t('Insert and update'),
+    ),
+    '#description' => t('Select how features in the FASTA file are handled.
+       Select "Insert only" to insert the new features. If a feature already
+       exists with the same name or unique name and type then it is skipped.
+       Select "Update only" to only update featues that already exist in the
+       database.  Select "Insert and Update" to insert features that do
+       not exist and upate those that do.'),
+    '#default_value' => 2,
+  );
+
+  $form['match_type']= array(
+    '#type' => 'radios',
+    '#title' => 'Name Match Type',
+    '#required' => TRUE,
+    '#options' => array(
+      t('Name'),
+      t('Unique name'),
+    ),
+    '#description' => t('Feature data is stored in Chado with both a human-readable
+      name and a unique name. If the features in your FASTA file are identified using
+      a human-readable name then select the "Name" button. If your features are
+      identified using the unique name then select the "Unique name" button.  If you
+      loaded your features first using the GFF loader then the unique name of each
+      features were indicated by the "ID=" attribute and the name by the "Name=" attribute.
+      By default, the FASTA loader will use the first word (character string
+      before the first space) as  the name for your feature. If
+      this does not uniquely identify your feature consider specifying a regular expression in the advanced section below.
+      Additionally, you may import both a name and a unique name for each sequence using the advanced options.
+      When updating a sequence, the value selected here will be used to identify the sequence in the
+      database in combination with any regular expression provided below.'),
+    '#default_value' => 1,
+  );
+
+  $form['analysis'] = array(
+    '#type' => 'fieldset',
+    '#title' => t('Analysis Used to Derive Features'),
+    '#collapsed' => TRUE
+  );
+  $form['analysis']['desc'] = array(
+    '#type' => 'markup',
+    '#value' => t("Why specify an analysis for a data load?  All data comes
+       from some place, even if downloaded from Genbank. By specifying
+       analysis details for all data uploads, it allows an end user to reproduce the
+       data set, but at least indicates the source of the data."),
+  );
+
+  // get the list of organisms
+  $sql = "SELECT * FROM {analysis} ORDER BY name";
+  $previous_db = tripal_db_set_active('chado');  // use chado database
+  $org_rset = db_query($sql);
+  tripal_db_set_active($previous_db);  // now use drupal database
+  $analyses = array();
+  $analyses[''] = '';
+  while ($analysis = db_fetch_object($org_rset)) {
+    $analyses[$analysis->analysis_id] = "$analysis->name ($analysis->program $analysis->programversion, $analysis->sourcename)";
+  }
+  $form['analysis']['analysis_id'] = array(
+    '#title'       => t('Analysis'),
+    '#type'        => t('select'),
+    '#description' => t("Choose the analysis to which these features are associated"),
+    '#required'    => TRUE,
+    '#options'     => $analyses,
+  );
+
+  // Advanced Options
+  $form['advanced'] = array(
+    '#type' => 'fieldset',
+    '#title' => t('Advanced Options'),
+    '#collapsed' => TRUE
+  );
+  $form['advanced']['re_help']= array(
+    '#type' => 'item',
+    '#value' => t('A regular expression is an advanced method for extracting information from a string of text.
+                   Your FASTA file may contain both a human-readable name and a unique name for each sequence.
+                   If you want to import
+                   both the name and unique name for all sequences, then you must provide regular expressions
+                   so that the loader knows how to separate them.
+                   Otherwise the name and uniquename will be the same.
+                   By default, this loader will use the first word in the definition
+                   lines of the FASTA file
+                   as the name or unique name of the feature.'),
+  );
+  $form['advanced']['re_name']= array(
+    '#type' => 'textfield',
+    '#title' => t('Regular expression for the name'),
+    '#required' => FALSE,
+    '#description' => t('Enter the regular expression that will extract the
+       feature name from the FASTA definition line. For example, for a
+       defintion line with a name and unique name separated by a bar \'|\' (>seqname|uniquename),
+       the regular expression for the name would be, "^(.*?)\|.*$".'),
+  );
+  $form['advanced']['re_uname']= array(
+    '#type' => 'textfield',
+    '#title' => t('Regular expression for the unique name'),
+    '#required' => FALSE,
+    '#description' => t('Enter the regular expression that will extract the
+       feature name from the FASTA definition line. For example, for a
+       defintion line with a name and unique name separated by a bar \'|\' (>seqname|uniquename),
+       the regular expression for the unique name would be "^.*?\|(.*)$").'),
+  );
+
+
+  // Advanced database cross-reference optoins
+  $form['advanced']['db'] = array(
+    '#type' => 'fieldset',
+    '#title' => t('External Database Reference'),
+    '#weight' => 6,
+    '#collapsed' => TRUE
+  );
+  $form['advanced']['db']['re_accession']= array(
+    '#type' => 'textfield',
+    '#title' => t('Regular expression for the accession'),
+    '#required' => FALSE,
+    '#description' => t('Enter the regular expression that will extract the accession for the external database for each feature from the FASTA definition line.'),
+    '#weight' => 2
+  );
 
   // get the list of databases
-   $sql = "SELECT * FROM {db} ORDER BY name";
-   $previous_db = tripal_db_set_active('chado');  // use chado database
-   $db_rset = db_query($sql);
-   tripal_db_set_active($previous_db);  // now use drupal database
-   $dbs = array();
-   $dbs[''] = '';
-   while($db = db_fetch_object($db_rset)){
-      $dbs[$db->db_id] = "$db->name";
-   }
-   $form['advanced']['db']['db_id'] = array (
-     '#title'       => t('External Database'),
-     '#type'        => t('select'),
-     '#description' => t("Plese choose an external database for which these sequences have a cross reference."),
-     '#required'    => FALSE,
-     '#options'     => $dbs,
-     '#weight'      => 1,
-   );
-
-   $form['advanced']['relationship'] = array(
-      '#type' => 'fieldset',
-      '#title' => t('Relationships'),
-      '#weight'=> 6,
-      '#collapsed' => TRUE
-   );
-   $rels = array();
-   $rels[''] = '';
-   $rels['part_of'] = 'part of';
-   $rels['derives_from'] = 'produced by';
-
-
-   // Advanced references options
-   $form['advanced']['relationship']['rel_type']= array(
-     '#title'       => t('Relationship Type'),
-     '#type'        => t('select'),
-     '#description' => t("Use this option to create associations, or relationships between the 
-                          features of this FASTA file and existing features in the database. For 
-                          example, to associate a FASTA file of peptides to existing genes or transcript sequence, 
-                          select the type 'produced by'. For a CDS sequences select the type 'part of'"),
-     '#required'    => FALSE,
-     '#options'     => $rels,
-     '#weight'      => 5,
-   );
-   $form['advanced']['relationship']['re_subject']= array(
-      '#type' => 'textfield',
-      '#title' => t('Regular expression for the parent'),
-      '#required' => FALSE,
-      '#description' => t('Enter the regular expression that will extract the unique 
-                           name needed to identify the existing sequence for which the 
-                           relationship type selected above will apply.'),
-      '#weight' => 6
-   ); 
-   $form['advanced']['relationship']['parent_type']= array(
-      '#type' => 'textfield',
-      '#title' => t('Parent Type'),
-      '#required' => FALSE,
-      '#description' => t('Please enter the Sequence Ontology term for the parent.  For example
-                           if the FASTA file being loaded is a set of proteins that are 
-                           products of genes, then use the SO term \'gene\' or \'transcript\' or equivalent. However,
-                           this type must match the type for already loaded features.'),
-      '#weight' => 7
-   );
-
-   $form['button'] = array(
-      '#type' => 'submit',
-      '#value' => t('Import FASTA file'),
-      '#weight' => 10,
-   );
-   return $form;   
+  $sql = "SELECT * FROM {db} ORDER BY name";
+  $previous_db = tripal_db_set_active('chado');  // use chado database
+  $db_rset = db_query($sql);
+  tripal_db_set_active($previous_db);  // now use drupal database
+  $dbs = array();
+  $dbs[''] = '';
+  while ($db = db_fetch_object($db_rset)) {
+    $dbs[$db->db_id] = "$db->name";
+  }
+  $form['advanced']['db']['db_id'] = array(
+   '#title'       => t('External Database'),
+   '#type'        => t('select'),
+   '#description' => t("Plese choose an external database for which these sequences have a cross reference."),
+   '#required'    => FALSE,
+   '#options'     => $dbs,
+   '#weight'      => 1,
+  );
+
+  $form['advanced']['relationship'] = array(
+    '#type' => 'fieldset',
+    '#title' => t('Relationships'),
+    '#weight' => 6,
+    '#collapsed' => TRUE
+  );
+  $rels = array();
+  $rels[''] = '';
+  $rels['part_of'] = 'part of';
+  $rels['derives_from'] = 'produced by';
+
+
+  // Advanced references options
+  $form['advanced']['relationship']['rel_type']= array(
+   '#title'       => t('Relationship Type'),
+   '#type'        => t('select'),
+   '#description' => t("Use this option to create associations, or relationships between the
+                        features of this FASTA file and existing features in the database. For
+                        example, to associate a FASTA file of peptides to existing genes or transcript sequence,
+                        select the type 'produced by'. For a CDS sequences select the type 'part of'"),
+   '#required'    => FALSE,
+   '#options'     => $rels,
+   '#weight'      => 5,
+  );
+  $form['advanced']['relationship']['re_subject']= array(
+    '#type' => 'textfield',
+    '#title' => t('Regular expression for the parent'),
+    '#required' => FALSE,
+    '#description' => t('Enter the regular expression that will extract the unique
+                         name needed to identify the existing sequence for which the
+                         relationship type selected above will apply.'),
+    '#weight' => 6
+  );
+  $form['advanced']['relationship']['parent_type']= array(
+    '#type' => 'textfield',
+    '#title' => t('Parent Type'),
+    '#required' => FALSE,
+    '#description' => t('Please enter the Sequence Ontology term for the parent.  For example
+                         if the FASTA file being loaded is a set of proteins that are
+                         products of genes, then use the SO term \'gene\' or \'transcript\' or equivalent. However,
+                         this type must match the type for already loaded features.'),
+    '#weight' => 7
+  );
+
+  $form['button'] = array(
+    '#type' => 'submit',
+    '#value' => t('Import FASTA file'),
+    '#weight' => 10,
+  );
+  return $form;
 }
 
 /**
@@ -272,98 +278,98 @@ $form['match_type']= array(
  *
  * @ingroup fasta_loader
  */
-function tripal_feature_fasta_load_form_validate($form, &$form_state){
-   $fasta_file = trim($form_state['values']['fasta_file']);
-   $organism_id  = $form_state['values']['organism_id'];
-   $type         = trim($form_state['values']['seqtype']);
-   $method       = trim($form_state['values']['method']);
-   $match_type   = trim($form_state['values']['match_type']);
-   $library_id   = $form_state['values']['library_id'];
-   $re_name      = trim($form_state['values']['re_name']);
-   $re_uname     = trim($form_state['values']['re_uname']);
-   $re_accession = trim($form_state['values']['re_accession']);
-   $db_id        = $form_state['values']['db_id'];
-   $rel_type     = $form_state['values']['rel_type'];
-   $re_subject   = trim($form_state['values']['re_subject']);
-   $parent_type   = trim($form_state['values']['parent_type']);
-
-   if($method == 0){
-      $method = 'Insert only';
-   }
-   if($method == 1){
-      $method = 'Update only';
-   }
-   if($method == 2){
-      $method = 'Insert and update';
-   }
-
-   if($match_type == 0){
-      $match_type = 'Name';
-   }
-
-   if($match_type == 1){
-      $match_type = 'Unique name';
-   }
-
-
-   if ($re_name and !$re_uname and strcmp($match_type,'Unique name')==0){
-      form_set_error('re_uname',t("You must provide a regular expression to identify the sequence unique name"));     
-   }
-
-   if (!$re_name and $re_uname and strcmp($match_type,'Name')==0){
-      form_set_error('re_name',t("You must provide a regular expression to identify the sequence name"));     
-   }
-
-   // check to see if the file is located local to Drupal
-   $dfile = $_SERVER['DOCUMENT_ROOT'] . base_path() . $fasta_file; 
-   if(!file_exists($dfile)){
-      // if not local to Drupal, the file must be someplace else, just use
-      // the full path provided
-      $dfile = $fasta_file;
-   }
-   if(!file_exists($dfile)){
-      form_set_error('fasta_file',t("Cannot find the file on the system. Check that the file exists or that the web server has permissions to read the file."));
-   }
-
-   // make sure if a relationship is specified that all fields are provided.
-   if(($rel_type or $parent_type) and !$re_subject){
-      form_set_error('re_subject',t("Please provide a regular expression for the parent"));
-   }
-   if(($rel_type or $re_subject) and !$parent_type){
-      form_set_error('parent_type',t("Please provide a SO term for the parent"));
-   }
-   if(($parent_type or $re_subject) and !$rel_type){
-      form_set_error('rel_type',t("Please select a relationship type"));
-   }
-
-
-   // make sure if a database is specified that all fields are provided
-   if($db_id and !$re_accession){
-      form_set_error('re_accession',t("Please provide a regular expression for the accession"));
-   }
-   if($re_accession and !$db_id){
-      form_set_error('db_id',t("Please select a database"));
-   }
-
-   // check to make sure the types exists
-   $cvtermsql = "SELECT CVT.cvterm_id
-                 FROM {cvterm} CVT
-                    INNER JOIN {cv} CV on CVT.cv_id = CV.cv_id
-                    LEFT JOIN {cvtermsynonym} CVTS on CVTS.cvterm_id = CVT.cvterm_id
-                 WHERE cv.name = '%s' and (CVT.name = '%s' or CVTS.synonym = '%s')";
-   $cvterm = db_fetch_object(db_query($cvtermsql,'sequence',$type,$type));
-   if(!$cvterm){
-      form_set_error('type',t("The Sequence Ontology (SO) term selected for the sequence type is not available in the database. Please check spelling or select another."));
-   }
-   if($rel_type){
-      $cvterm = db_fetch_object(db_query($cvtermsql,'sequence',$parent_type,$parent_type));
-      if(!$cvterm){
-         form_set_error('parent_type',t("The Sequence Ontology (SO) term selected for the parent relationship is not available in the database. Please check spelling or select another."));
-      }
-   }
-
-   // check to make sure the 'relationship' and 'sequence' ontologies are loaded
-   $form_state['storage']['dfile'] = $dfile;
+function tripal_feature_fasta_load_form_validate($form, &$form_state) {
+  $fasta_file = trim($form_state['values']['fasta_file']);
+  $organism_id  = $form_state['values']['organism_id'];
+  $type         = trim($form_state['values']['seqtype']);
+  $method       = trim($form_state['values']['method']);
+  $match_type   = trim($form_state['values']['match_type']);
+  $library_id   = $form_state['values']['library_id'];
+  $re_name      = trim($form_state['values']['re_name']);
+  $re_uname     = trim($form_state['values']['re_uname']);
+  $re_accession = trim($form_state['values']['re_accession']);
+  $db_id        = $form_state['values']['db_id'];
+  $rel_type     = $form_state['values']['rel_type'];
+  $re_subject   = trim($form_state['values']['re_subject']);
+  $parent_type   = trim($form_state['values']['parent_type']);
+
+  if ($method == 0) {
+    $method = 'Insert only';
+  }
+  if ($method == 1) {
+    $method = 'Update only';
+  }
+  if ($method == 2) {
+    $method = 'Insert and update';
+  }
+
+  if ($match_type == 0) {
+    $match_type = 'Name';
+  }
+
+  if ($match_type == 1) {
+    $match_type = 'Unique name';
+  }
+
+
+  if ($re_name and !$re_uname and strcmp($match_type, 'Unique name')==0) {
+    form_set_error('re_uname', t("You must provide a regular expression to identify the sequence unique name"));
+  }
+
+  if (!$re_name and $re_uname and strcmp($match_type, 'Name')==0) {
+    form_set_error('re_name', t("You must provide a regular expression to identify the sequence name"));
+  }
+
+  // check to see if the file is located local to Drupal
+  $dfile = $_SERVER['DOCUMENT_ROOT'] . base_path() . $fasta_file;
+  if (!file_exists($dfile)) {
+    // if not local to Drupal, the file must be someplace else, just use
+    // the full path provided
+    $dfile = $fasta_file;
+  }
+  if (!file_exists($dfile)) {
+    form_set_error('fasta_file', t("Cannot find the file on the system. Check that the file exists or that the web server has permissions to read the file."));
+  }
+
+  // make sure if a relationship is specified that all fields are provided.
+  if (($rel_type or $parent_type) and !$re_subject) {
+    form_set_error('re_subject', t("Please provide a regular expression for the parent"));
+  }
+  if (($rel_type or $re_subject) and !$parent_type) {
+    form_set_error('parent_type', t("Please provide a SO term for the parent"));
+  }
+  if (($parent_type or $re_subject) and !$rel_type) {
+    form_set_error('rel_type', t("Please select a relationship type"));
+  }
+
+
+  // make sure if a database is specified that all fields are provided
+  if ($db_id and !$re_accession) {
+    form_set_error('re_accession', t("Please provide a regular expression for the accession"));
+  }
+  if ($re_accession and !$db_id) {
+    form_set_error('db_id', t("Please select a database"));
+  }
+
+  // check to make sure the types exists
+  $cvtermsql = "SELECT CVT.cvterm_id
+               FROM {cvterm} CVT
+                  INNER JOIN {cv} CV on CVT.cv_id = CV.cv_id
+                  LEFT JOIN {cvtermsynonym} CVTS on CVTS.cvterm_id = CVT.cvterm_id
+               WHERE cv.name = '%s' and (CVT.name = '%s' or CVTS.synonym = '%s')";
+  $cvterm = db_fetch_object(db_query($cvtermsql, 'sequence', $type, $type));
+  if (!$cvterm) {
+    form_set_error('type', t("The Sequence Ontology (SO) term selected for the sequence type is not available in the database. Please check spelling or select another."));
+  }
+  if ($rel_type) {
+    $cvterm = db_fetch_object(db_query($cvtermsql, 'sequence', $parent_type, $parent_type));
+    if (!$cvterm) {
+      form_set_error('parent_type', t("The Sequence Ontology (SO) term selected for the parent relationship is not available in the database. Please check spelling or select another."));
+    }
+  }
+
+  // check to make sure the 'relationship' and 'sequence' ontologies are loaded
+  $form_state['storage']['dfile'] = $dfile;
 }
 
 /**
@@ -371,48 +377,48 @@ function tripal_feature_fasta_load_form_validate($form, &$form_state){
  *
  * @ingroup fasta_loader
  */
-function tripal_feature_fasta_load_form_submit ($form, &$form_state){
-   global $user;
-
-   $dfile        = $form_state['storage']['dfile'];
-   $organism_id  = $form_state['values']['organism_id'];
-   $type         = trim($form_state['values']['seqtype']);
-   $method       = trim($form_state['values']['method']);
-   $match_type   = trim($form_state['values']['match_type']);
-   $library_id   = $form_state['values']['library_id'];
-   $re_name      = trim($form_state['values']['re_name']);
-   $re_uname     = trim($form_state['values']['re_uname']);
-   $re_accession = trim($form_state['values']['re_accession']);
-   $db_id        = $form_state['values']['db_id'];
-   $rel_type     = $form_state['values']['rel_type'];
-   $re_subject   = trim($form_state['values']['re_subject']);
-   $parent_type   = trim($form_state['values']['parent_type']);
-   $analysis_id = $form_state['values']['analysis_id'];
-
-   if($method == 0){
-      $method = 'Insert only';
-   }
-   if($method == 1){
-      $method = 'Update only';
-   }
-   if($method == 2){
-      $method = 'Insert and update';
-   }
-
-   if($match_type == 0){
-      $match_type = 'Name';
-   }
-
-   if($match_type == 1){
-      $match_type = 'Unique name';
-   }
-
-   $args = array($dfile,$organism_id,$type,$library_id,$re_name,$re_uname,
-            $re_accession,$db_id,$rel_type,$re_subject,$parent_type,$method,
-            $user->uid,$analysis_id,$match_type);
-
-   tripal_add_job("Import FASTA file: $dfile",'tripal_feature',
-      'tripal_feature_load_fasta',$args,$user->uid);
+function tripal_feature_fasta_load_form_submit($form, &$form_state) {
+  global $user;
+
+  $dfile        = $form_state['storage']['dfile'];
+  $organism_id  = $form_state['values']['organism_id'];
+  $type         = trim($form_state['values']['seqtype']);
+  $method       = trim($form_state['values']['method']);
+  $match_type   = trim($form_state['values']['match_type']);
+  $library_id   = $form_state['values']['library_id'];
+  $re_name      = trim($form_state['values']['re_name']);
+  $re_uname     = trim($form_state['values']['re_uname']);
+  $re_accession = trim($form_state['values']['re_accession']);
+  $db_id        = $form_state['values']['db_id'];
+  $rel_type     = $form_state['values']['rel_type'];
+  $re_subject   = trim($form_state['values']['re_subject']);
+  $parent_type   = trim($form_state['values']['parent_type']);
+  $analysis_id = $form_state['values']['analysis_id'];
+
+  if ($method == 0) {
+    $method = 'Insert only';
+  }
+  if ($method == 1) {
+    $method = 'Update only';
+  }
+  if ($method == 2) {
+    $method = 'Insert and update';
+  }
+
+  if ($match_type == 0) {
+    $match_type = 'Name';
+  }
+
+  if ($match_type == 1) {
+    $match_type = 'Unique name';
+  }
+
+  $args = array($dfile, $organism_id, $type, $library_id, $re_name, $re_uname,
+          $re_accession, $db_id, $rel_type, $re_subject, $parent_type, $method,
+          $user->uid, $analysis_id, $match_type);
+
+  tripal_add_job("Import FASTA file: $dfile", 'tripal_feature',
+    'tripal_feature_load_fasta', $args, $user->uid);
 }
 
 /**
@@ -421,94 +427,95 @@ function tripal_feature_fasta_load_form_submit ($form, &$form_state){
  * @ingroup fasta_loader
  */
 function tripal_feature_load_fasta($dfile, $organism_id, $type,
-   $library_id, $re_name, $re_uname, $re_accession, $db_id, $rel_type,
-   $re_subject, $parent_type, $method, $uid, $analysis_id, 
-   $match_type,$job = NULL)
-{
-
-   print "Opening FASTA file $dfile\n";
-
-    
-   $lines = file($dfile,FILE_SKIP_EMPTY_LINES);
-   $i = 0;
-
-   $name = '';
-   $uname = '';
-   $residues = '';
-   $num_lines = sizeof($lines);
-   $interval = intval($num_lines * 0.01);
-   if($interval == 0){
-      $interval = 1;
-   }
-
-   foreach ($lines as $line_num => $line) {
-      $i++;  // update the line count     
-
-      // update the job status every 1% features
-      if($job and $i % $interval == 0){
-         tripal_job_set_progress($job,intval(($i/$num_lines)*100));
+  $library_id, $re_name, $re_uname, $re_accession, $db_id, $rel_type,
+  $re_subject, $parent_type, $method, $uid, $analysis_id,
+  $match_type, $job = NULL) {
+
+  print "Opening FASTA file $dfile\n";
+
+
+  $lines = file($dfile, FILE_SKIP_EMPTY_LINES);
+  $i = 0;
+
+  $name = '';
+  $uname = '';
+  $residues = '';
+  $num_lines = sizeof($lines);
+  $interval = intval($num_lines * 0.01);
+  if ($interval == 0) {
+    $interval = 1;
+  }
+
+  foreach ($lines as $line_num => $line) {
+    $i++;  // update the line count
+
+    // update the job status every 1% features
+    if ($job and $i % $interval == 0) {
+      tripal_job_set_progress($job, intval(($i/$num_lines)*100));
+    }
+
+    // if we encounter a definition line then get the name, uniquename,
+    // accession and relationship subject from the definition line
+    if (preg_match('/^>/', $line)) {
+      // if we have a feature name then we are starting a new sequence
+      // so let's handle the previous one before moving on
+      if ($name or $uname) {
+        tripal_feature_fasta_loader_handle_feature($name, $uname, $db_id,
+          $accession, $subject, $rel_type, $parent_type, $analysis_id, $organism_id, $type,
+          $source, $residues, $method, $re_name, $match_type);
+        $residues = '';
+        $name = '';
+        $uname = '';
       }
 
-      // if we encounter a definition line then get the name, uniquename, 
-      // accession and relationship subject from the definition line
-      if(preg_match('/^>/',$line)){
-         // if we have a feature name then we are starting a new sequence
-         // so let's handle the previous one before moving on
-         if($name or $uname){
-           tripal_feature_fasta_loader_handle_feature($name,$uname,$db_id,
-              $accession,$subject,$rel_type,$parent_type,$analysis_id,$organism_id,$type,
-              $source,$residues,$method,$re_name,$match_type);
-           $residues = '';
-           $name = '';
-           $uname = '';
-         }
-
-         $line = preg_replace("/^>/",'',$line);
-         // get the feature name
-         if($re_name){
-            if(!preg_match("/$re_name/",$line,$matches)){
-               print "WARNING: Regular expression for the feature name finds nothing\n";
-            }
-            $name = trim($matches[1]);
-         } else {
-            // if the match_type is name and no regular expression was provided
-            // then use the first word as the name, otherwise we don't set the name
-            if(strcmp($match_type,'Name')==0){
-               preg_match("/^\s*(.*?)[\s\|].*$/",$line,$matches);
-               $name = trim($matches[1]);
-            }
-         } 
-         // get the feature unique name
-         if($re_uname){
-            if(!preg_match("/$re_uname/",$line,$matches)){
-               print "WARNING: Regular expression for the feature unique name finds nothing\n";
-            }
-            $uname = trim($matches[1]);
-         } else {
-            // if the match_type is name and no regular expression was provided
-            // then use the first word as the name, otherwise, we don't set the unqiuename
-            if(strcmp($match_type,'Unique name')==0){
-               preg_match("/^\s*(.*?)[\s\|].*$/",$line,$matches);
-               $uname = trim($matches[1]);
-            }
-         } 
-         // get the accession    
-         preg_match("/$re_accession/",$line,$matches);
-         $accession = trim($matches[1]);
-
-         // get the relationship subject
-         preg_match("/$re_subject/",$line,$matches);
-         $subject = trim($matches[1]);
+      $line = preg_replace("/^>/", '', $line);
+      // get the feature name
+      if ($re_name) {
+        if (!preg_match("/$re_name/", $line, $matches)) {
+          print "WARNING: Regular expression for the feature name finds nothing\n";
+        }
+        $name = trim($matches[1]);
+      }
+      else {
+        // if the match_type is name and no regular expression was provided
+        // then use the first word as the name, otherwise we don't set the name
+        if (strcmp($match_type, 'Name')==0) {
+          preg_match("/^\s*(.*?)[\s\|].*$/", $line, $matches);
+          $name = trim($matches[1]);
+        }
+      }
+      // get the feature unique name
+      if ($re_uname) {
+        if (!preg_match("/$re_uname/", $line, $matches)) {
+          print "WARNING: Regular expression for the feature unique name finds nothing\n";
+        }
+        $uname = trim($matches[1]);
       }
       else {
-         $residues .= trim($line);
+        // if the match_type is name and no regular expression was provided
+        // then use the first word as the name, otherwise, we don't set the unqiuename
+        if (strcmp($match_type, 'Unique name')==0) {
+          preg_match("/^\s*(.*?)[\s\|].*$/", $line, $matches);
+          $uname = trim($matches[1]);
+        }
+      }
+      // get the accession
+      preg_match("/$re_accession/", $line, $matches);
+      $accession = trim($matches[1]);
+
+      // get the relationship subject
+      preg_match("/$re_subject/", $line, $matches);
+      $subject = trim($matches[1]);
       }
-   }
+    else {
+      $residues .= trim($line);
+    }
+  }
    // now load the last sequence in the file
-   tripal_feature_fasta_loader_handle_feature($name,$uname,$db_id,
-      $accession,$subject,$rel_type,$parent_type,$analysis_id,$organism_id,$type,
-      $source,$residues,$method,$re_name,$match_type);
-   return '';
+  tripal_feature_fasta_loader_handle_feature($name, $uname, $db_id,
+    $accession, $subject, $rel_type, $parent_type, $analysis_id, $organism_id, $type,
+    $source, $residues, $method, $re_name, $match_type);
+  return '';
 }
 
 /**
@@ -516,194 +523,208 @@ function tripal_feature_load_fasta($dfile, $organism_id, $type,
  *
  * @ingroup fasta_loader
  */
-function tripal_feature_fasta_loader_handle_feature($name,$uname,$db_id,$accession,
-              $parent,$rel_type,$parent_type,$analysis_id,$organism_id,$type, 
-              $source,$residues,$method,$re_name,$match_type) 
-{
-   $previous_db = tripal_db_set_active('chado');
-
-   // first get the type for this sequence
-   $cvtermsql = "SELECT CVT.cvterm_id
-                 FROM {cvterm} CVT
-                    INNER JOIN {cv} CV on CVT.cv_id = CV.cv_id
-                    LEFT JOIN {cvtermsynonym} CVTS on CVTS.cvterm_id = CVT.cvterm_id
-                 WHERE cv.name = '%s' and (CVT.name = '%s' or CVTS.synonym = '%s')";
-   $cvterm = db_fetch_object(db_query($cvtermsql,'sequence',$type,$type));
-   if(!$cvterm){
-      print "ERROR: cannot find the term type: '$type'\n";
-      return 0;
-   }
+function tripal_feature_fasta_loader_handle_feature($name, $uname, $db_id, $accession,
+  $parent, $rel_type, $parent_type, $analysis_id, $organism_id, $type,
+  $source, $residues, $method, $re_name, $match_type) {
+
+  $previous_db = tripal_db_set_active('chado');
+
+  // first get the type for this sequence
+  $cvtermsql = "SELECT CVT.cvterm_id
+               FROM {cvterm} CVT
+                  INNER JOIN {cv} CV on CVT.cv_id = CV.cv_id
+                  LEFT JOIN {cvtermsynonym} CVTS on CVTS.cvterm_id = CVT.cvterm_id
+               WHERE cv.name = '%s' and (CVT.name = '%s' or CVTS.synonym = '%s')";
+  $cvterm = db_fetch_object(db_query($cvtermsql, 'sequence', $type, $type));
+  if (!$cvterm) {
+    print "ERROR: cannot find the term type: '$type'\n";
+    return 0;
+  }
 
    // check to see if this feature already exists
-   if(strcmp($match_type,'Name')==0){
-      $cnt_sql = "SELECT count(*) as cnt FROM {feature} 
-                      WHERE organism_id = %d and name = '%s' and type_id = %d";
-      $cnt = db_fetch_object(db_query($cnt_sql,$organism_id,$name,$cvterm->cvterm_id));
-      if($cnt->cnt > 1){
-         print "ERROR: multiple features exist with the name '$name' of type '$type' for the organism.  skipping\n";
-         return 0;
-      } else {
-         $feature_sql = "SELECT * FROM {feature} 
-                      WHERE organism_id = %d and name = '%s' and type_id = %d";
-         $feature = db_fetch_object(db_query($feature_sql,$organism_id,$name,$cvterm->cvterm_id));
-      }
-   }
-   if(strcmp($match_type,'Unique name')==0){
-      $feature_sql = "SELECT * FROM {feature} 
-                      WHERE organism_id = %d and uniquename = '%s' and type_id = %d";
-      $feature = db_fetch_object(db_query($feature_sql,$organism_id,$uname,$cvterm->cvterm_id));
-   }
-
-   if(!$feature and (strcmp($method,'Insert only')==0 or strcmp($method,'Insert and update')==0)){
-       // if we have a unique name but not a name then set them to be teh same 
-       // and vice versa
-       if(!$uname){
-          $uname = $name;
-       }
-       elseif(!$name){
-          $name = $uname;
-       }
-      // now insert the feature
-      $sql = "INSERT INTO {feature} 
-                 (organism_id, name, uniquename, residues, seqlen, 
-                  md5checksum,type_id,is_analysis,is_obsolete)
-              VALUES(%d,'%s','%s','%s',%d, '%s', %d, %s, %s)";
-      $result = db_query($sql,$organism_id,$name,$uname,$residues,strlen($residues),
-                  md5($residues),$cvterm->cvterm_id,'false','false');
-      if(!$result){
-         print "ERROR: failed to insert feature '$name ($uname)'\n";
-         return 0;
-      } else {
-         print "Inserted feature $name ($uname)\n";
-      }
-      $feature = db_fetch_object(db_query($feature_sql,$organism_id,$uname,$cvterm->cvterm_id));
-   } 
-   if(!$feature and (strcmp($method,'Update only')==0 or strcmp($method,'Insert and update')==0)){
-      print "WARNING: failed to find feature '$name' ('$uname') while matching on " . strtolower($match_type) . ". Skipping\n";
+  if (strcmp($match_type, 'Name')==0) {
+    $cnt_sql = "SELECT count(*) as cnt FROM {feature}
+                  WHERE organism_id = %d and name = '%s' and type_id = %d";
+    $cnt = db_fetch_object(db_query($cnt_sql, $organism_id, $name, $cvterm->cvterm_id));
+    if ($cnt->cnt > 1) {
+      print "ERROR: multiple features exist with the name '$name' of type '$type' for the organism.  skipping\n";
       return 0;
-   }
-
-   if($feature and (strcmp($method,'Update only')==0 or strcmp($method,'Insert and update')==0)){
-       if(strcmp($method,'Update only')==0 or strcmp($method,'Insert and update')==0){
-         if(strcmp($match_type,'Name')==0){
-            // if we're matching on the name but do not have a new unique name then we
-            // don't want to update the uniquename.  If we do have a uniquename then we 
-            // should update it.  We only get a uniquename if there was a regular expression
-            // provided for pulling it out
-            if($uname){
-               $sql = "UPDATE {feature} 
-                        SET uniquename = '%s', residues = '%s', seqlen = '%s', md5checksum = '%s'
-                        WHERE organism_id = %d and name = '%s' and type_id = %d";
-               $result = db_query($sql,$uname,$residues,strlen($residues),md5($residues),$organism_id,$name,$cvterm->cvterm_id);
-            } else {
-               $sql = "UPDATE {feature} 
-                        SET residues = '%s', seqlen = '%s', md5checksum = '%s'
-                        WHERE organism_id = %d and name = '%s' and type_id = %d";
-               $result = db_query($sql,$residues,strlen($residues),md5($residues),$organism_id,$name,$cvterm->cvterm_id);
-            }
-         } else {
-            // if we're matching on the unique name but do not have a new name then we
-            // don't want to update the name.  If we do have a name then we 
-            // should update it.  We only get a name if there was a regular expression
-            // provided for pulling it out
-            if($name){
-               $sql = "UPDATE {feature} 
-                        SET name = '%s', residues = '%s', seqlen = '%s', md5checksum = '%s'
-                        WHERE organism_id = %d and uniquename = '%s' and type_id = %d";
-               $result = db_query($sql,$name,$residues,strlen($residues),md5($residues),$organism_id,$uname,$cvterm->cvterm_id);
-            } else {
-               $sql = "UPDATE {feature} 
-                        SET residues = '%s', seqlen = '%s', md5checksum = '%s'
-                        WHERE organism_id = %d and uniquename = '%s' and type_id = %d";
-               $result = db_query($sql,$residues,strlen($residues),md5($residues),$organism_id,$uname,$cvterm->cvterm_id);
-            }
-         }
-         if(!$result){
-            print "ERROR: failed to update feature '$name ($uname)'\n";
-            return 0;
-         } else {
-            print "Updated feature $name ($uname)\n";
-         }
-      } else {
-         print "WARNING: feature already exists: '$name' ('$uname'). Skipping\n";
-      }
-   }
-   // now get the feature
-   $feature = db_fetch_object(db_query($feature_sql,$organism_id,$uname,$cvterm->cvterm_id));
-   if(!$feature){
-      print "Something bad has happened: $organism_id, $uname, $cvterm->cvterm_id\n";
+    }
+    else {
+      $feature_sql = "SELECT * FROM {feature}
+                  WHERE organism_id = %d and name = '%s' and type_id = %d";
+      $feature = db_fetch_object(db_query($feature_sql, $organism_id, $name, $cvterm->cvterm_id));
+    }
+  }
+  if (strcmp($match_type, 'Unique name')==0) {
+    $feature_sql = "SELECT * FROM {feature}
+                    WHERE organism_id = %d and uniquename = '%s' and type_id = %d";
+    $feature = db_fetch_object(db_query($feature_sql, $organism_id, $uname, $cvterm->cvterm_id));
+  }
+
+  if (!$feature and (strcmp($method, 'Insert only')==0 or strcmp($method, 'Insert and update')==0)) {
+    // if we have a unique name but not a name then set them to be teh same
+    // and vice versa
+    if (!$uname) {
+      $uname = $name;
+    }
+    elseif (!$name) {
+      $name = $uname;
+    }
+    // now insert the feature
+    $sql = "INSERT INTO {feature}
+           (organism_id, name, uniquename, residues, seqlen,
+            md5checksum,type_id,is_analysis,is_obsolete)
+        VALUES(%d,'%s','%s','%s',%d, '%s', %d, %s, %s)";
+    $result = db_query($sql, $organism_id, $name, $uname, $residues, drupal_strlen($residues),
+            md5($residues), $cvterm->cvterm_id, 'false', 'false');
+    if (!$result) {
+      print "ERROR: failed to insert feature '$name ($uname)'\n";
       return 0;
-   }
-
-	 // add in the analysis link
-	 if ($analysis_id) {
-	 	$analysis_link_sql = 'SELECT * FROM analysisfeature WHERE analysis_id=%d AND feature_id=%d';
-	 	$analysis_link = db_fetch_object(db_query($analysis_link_sql, $analysis_id, $feature->feature_id));
-	 	if (!$analysis_link) {
-	 		$sql = "INSERT INTO analysisfeature (analysis_id, feature_id) VALUES (%d, %d)";
-	 		$result = db_query($sql, $analysis_id, $feature->feature_id);
-		  if(!$result){
-			  print "WARNING: could not add link between analysis: ".$analysis_id." and feature: ".$feature->uniquename."\n";
-		  }
-		  $analysis_link = db_fetch_object(db_query($analysis_link_sql, $analysis_id, $feature->feature_id));
-	 	}
-	 }
-	 
-   // now add the database cross reference
-   if($db_id){
-      // check to see if this accession reference exists, if not add it
-      $dbxrefsql = "SELECT * FROM {dbxref} WHERE db_id = %s and accession = '%s'";
-      $dbxref = db_fetch_object(db_query($dbxrefsql,$db_id,$accession));
-      if(!$dbxref){
-         $sql = "INSERT INTO {dbxref} (db_id,accession) VALUES (%d,'%s')";
-         $result = db_query($sql,$db_id,$accession);
-         if(!$result){
-           print "WARNING: could not add external database acession: '$name accession: $accession'\n";
-         }
-         $dbxref = db_fetch_object(db_query($dbxrefsql,$db_id,$accession));
+    }
+    else {
+      print "Inserted feature $name ($uname)\n";
+    }
+    $feature = db_fetch_object(db_query($feature_sql, $organism_id, $uname, $cvterm->cvterm_id));
+    }
+  if (!$feature and (strcmp($method, 'Update only')==0 or drupal_strcmp($method, 'Insert and update')==0)) {
+    print "WARNING: failed to find feature '$name' ('$uname') while matching on " . drupal_strtolower($match_type) . ". Skipping\n";
+    return 0;
+  }
+
+  if ($feature and (strcmp($method, 'Update only')==0 or strcmp($method, 'Insert and update')==0)) {
+    if (strcmp($method, 'Update only')==0 or strcmp($method, 'Insert and update')==0) {
+      if (strcmp($match_type, 'Name')==0) {
+        // if we're matching on the name but do not have a new unique name then we
+        // don't want to update the uniquename.  If we do have a uniquename then we
+        // should update it.  We only get a uniquename if there was a regular expression
+        // provided for pulling it out
+        if ($uname) {
+          $sql = "UPDATE {feature}
+                SET uniquename = '%s', residues = '%s', seqlen = '%s', md5checksum = '%s'
+                WHERE organism_id = %d and name = '%s' and type_id = %d";
+          $result = db_query($sql, $uname, $residues, drupal_strlen($residues), md5($residues), $organism_id, $name, $cvterm->cvterm_id);
+        }
+        else {
+          $sql = "UPDATE {feature}
+                  SET residues = '%s', seqlen = '%s', md5checksum = '%s'
+                  WHERE organism_id = %d and name = '%s' and type_id = %d";
+          $result = db_query($sql, $residues, durpal_strlen($residues), md5($residues), $organism_id, $name, $cvterm->cvterm_id);
+        }
+        }
+        else {
+          // if we're matching on the unique name but do not have a new name then we
+          // don't want to update the name.  If we do have a name then we
+          // should update it.  We only get a name if there was a regular expression
+          // provided for pulling it out
+          if ($name) {
+            $sql = "UPDATE {feature}
+                    SET name = '%s', residues = '%s', seqlen = '%s', md5checksum = '%s'
+                    WHERE organism_id = %d and uniquename = '%s' and type_id = %d";
+            $result = db_query($sql, $name, $residues, drupal_strlen($residues), md5($residues), $organism_id, $uname, $cvterm->cvterm_id);
+          }
+          else {
+            $sql = "UPDATE {feature}
+                    SET residues = '%s', seqlen = '%s', md5checksum = '%s'
+                    WHERE organism_id = %d and uniquename = '%s' and type_id = %d";
+            $result = db_query($sql, $residues, drupal_strlen($residues), md5($residues), $organism_id, $uname, $cvterm->cvterm_id);
+          }
+    }
+    if (!$result) {
+      print "ERROR: failed to update feature '$name ($uname)'\n";
+      return 0;
+    }
+    else {
+      print "Updated feature $name ($uname)\n";
+    }
+    }
+    else {
+      print "WARNING: feature already exists: '$name' ('$uname'). Skipping\n";
+    }
+  }
+   // now get the feature
+  $feature = db_fetch_object(db_query($feature_sql, $organism_id, $uname, $cvterm->cvterm_id));
+  if (!$feature) {
+    print "Something bad has happened: $organism_id, $uname, $cvterm->cvterm_id\n";
+    return 0;
+  }
+
+  // add in the analysis link
+  if ($analysis_id) {
+    // @coder-ignore: non-drupal table thus table prefixing doesn't apply
+    $analysis_link_sql = 'SELECT * FROM analysisfeature WHERE analysis_id=%d AND feature_id=%d';
+    $analysis_link = db_fetch_object(db_query($analysis_link_sql, $analysis_id, $feature->feature_id));
+    if (!$analysis_link) {
+      // @coder-ignore: non-drupal table thus table prefixing doesn't apply
+      $sql = "INSERT INTO analysisfeature (analysis_id, feature_id) VALUES (%d, %d)";
+      $result = db_query($sql, $analysis_id, $feature->feature_id);
+      if (!$result) {
+        print "WARNING: could not add link between analysis: " . $analysis_id . " and feature: " . $feature->uniquename . "\n";
       }
+      $analysis_link = db_fetch_object(db_query($analysis_link_sql, $analysis_id, $feature->feature_id));
+    }
+  }
 
-      // check to see if the feature dbxref record exists if not, then add it 
-      $fdbxrefsql = "SELECT * FROM {feature_dbxref} WHERE feature_id = %d and dbxref_id = %d";
-      $fdbxref = db_fetch_object(db_query($fdbxrefsql,$feature->feature_id,$dbxref->dbxref_id));
-      if(!$fdbxref){
-         $sql = "INSERT INTO {feature_dbxref} (feature_id,dbxref_id) VALUES (%d,%d)";
-         $result = db_query($sql,$feature->feature_id,$dbxref->dbxref_id);
-         if(!$result){
-            print "WARNING: could not associate database cross reference with feature: '$name accession: $accession'\n";
-         } else {
-            print "Added database crossreference $name ($uname) -> $accession\n";
-         }
+   // now add the database cross reference
+  if ($db_id) {
+    // check to see if this accession reference exists, if not add it
+    // @coder-ignore: non-drupal table thus table prefixing doesn't apply
+    $dbxrefsql = "SELECT * FROM dbxref WHERE db_id = %d and accession = '%s'";
+    $dbxref = db_fetch_object(db_query($dbxrefsql, $db_id, $accession));
+    if (!$dbxref) {
+      // @coder-ignore: non-drupal table thus table prefixing doesn't apply
+      $sql = "INSERT INTO dbxref (db_id,accession) VALUES (%d, '%s')";
+      $result = db_query($sql, $db_id, $accession);
+      if (!$result) {
+        print "WARNING: could not add external database acession: '$name accession: $accession'\n";
+      }
+      $dbxref = db_fetch_object(db_query($dbxrefsql, $db_id, $accession));
+    }
+
+    // check to see if the feature dbxref record exists if not, then add it
+    $fdbxrefsql = "SELECT * FROM {feature_dbxref} WHERE feature_id = %d and dbxref_id = %d";
+    $fdbxref = db_fetch_object(db_query($fdbxrefsql, $feature->feature_id, $dbxref->dbxref_id));
+    if (!$fdbxref) {
+      $sql = "INSERT INTO {feature_dbxref} (feature_id,dbxref_id) VALUES (%d, %d)";
+      $result = db_query($sql, $feature->feature_id, $dbxref->dbxref_id);
+      if (!$result) {
+        print "WARNING: could not associate database cross reference with feature: '$name accession: $accession'\n";
+      }
+      else {
+        print "Added database crossreference $name ($uname) -> $accession\n";
       }
-   }
+    }
+    }
 
    // now add in the relationship if one exists.  First, get the parent type for the relationship
-   // then get the parent feature 
-   if($rel_type){
-      $parentcvterm = db_fetch_object(db_query($cvtermsql,'sequence',$parent_type,$parent_type));
-      $relcvterm = db_fetch_object(db_query($cvtermsql,'relationship',$rel_type,$rel_type));
-      $parent_feature = db_fetch_object(db_query($feature_sql,$organism_id,$parent,$parentcvterm->cvterm_id));
-      if($parent_feature){
-         // check to see if the relationship already exists
-         $sql = "SELECT * FROM {feature_relationship} WHERE subject_id = %d and object_id = %d and type_id = %d";
-         $rel = db_fetch_object(db_query($sql,$feature->feature_id,$parent_feature->feature_id,$relcvterm->cvterm_id));
-         if($rel){
-            print "WARNING: relationship already exists, skipping '$uname' ($type) $rel_type '$parent' ($parent_type)\n";
-         } else {      
-            $sql = "INSERT INTO {feature_relationship} (subject_id,object_id,type_id)
-                    VALUES (%d,%d,%d)";
-            $result = db_query($sql,$feature->feature_id,$parent_feature->feature_id,$relcvterm->cvterm_id);
-            if(!$result){
-               print "WARNING: failed to insert feature relationship '$uname' ($type) $rel_type '$parent' ($parent_type)\n";
-            } else {
-               print "Inserted relationship relationship: '$uname' ($type) $rel_type '$parent' ($parent_type)\n";
-            }
-         } 
+   // then get the parent feature
+  if ($rel_type) {
+    $parentcvterm = db_fetch_object(db_query($cvtermsql, 'sequence', $parent_type, $parent_type));
+    $relcvterm = db_fetch_object(db_query($cvtermsql, 'relationship', $rel_type, $rel_type));
+    $parent_feature = db_fetch_object(db_query($feature_sql, $organism_id, $parent, $parentcvterm->cvterm_id));
+    if ($parent_feature) {
+      // check to see if the relationship already exists
+      $sql = "SELECT * FROM {feature_relationship} WHERE subject_id = %d and object_id = %d and type_id = %d";
+      $rel = db_fetch_object(db_query($sql, $feature->feature_id, $parent_feature->feature_id, $relcvterm->cvterm_id));
+      if ($rel) {
+        print "WARNING: relationship already exists, skipping '$uname' ($type) $rel_type '$parent' ($parent_type)\n";
       }
       else {
-         print "WARNING: cannot establish relationship '$uname' ($type) $rel_type '$parent' ($parent_type): Cannot find the parent\n";
+        $sql = "INSERT INTO {feature_relationship} (subject_id,object_id,type_id)
+                VALUES (%d,%d,%d)";
+        $result = db_query($sql, $feature->feature_id, $parent_feature->feature_id, $relcvterm->cvterm_id);
+        if (!$result) {
+          print "WARNING: failed to insert feature relationship '$uname' ($type) $rel_type '$parent' ($parent_type)\n";
+        }
+        else {
+          print "Inserted relationship relationship: '$uname' ($type) $rel_type '$parent' ($parent_type)\n";
+        }
       }
-   }
-   tripal_db_set_active($previous_db);
+    }
+    else {
+      print "WARNING: cannot establish relationship '$uname' ($type) $rel_type '$parent' ($parent_type): Cannot find the parent\n";
+    }
+    }
+  tripal_db_set_active($previous_db);
 }
 

Tiedoston diff-näkymää rajattu, sillä se on liian suuri
+ 617 - 605
tripal_feature/gff_loader.php


+ 146 - 139
tripal_feature/indexFeatures.php

@@ -1,61 +1,41 @@
 <?php
+/**
+ * @file
+ * @todo Add file header description
+ */
+
 
 // This script can be run as a stand-alone script to sync all the features from chado to drupal
 //
 // To index a single feature
 // -i feature_id
-// -n node_id 
+// -n node_id
 //
 // To index all features
-// -i 0 
+// -i 0
 
 $arguments = getopt("i:n:");
 
-if(isset($arguments['i'])){
-   $drupal_base_url = parse_url('http://www.example.com');
-   $_SERVER['HTTP_HOST'] = $drupal_base_url['host'];
-   $_SERVER['REQUEST_URI'] = $_SERVER['SCRIPT_NAME'] = $_SERVER['PHP_SELF'];
-   $_SERVER['REMOTE_ADDR'] = NULL;
-   $_SERVER['REQUEST_METHOD'] = NULL;
-	
-   require_once 'includes/bootstrap.inc';
-   drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);
-
-   $feature_id = $arguments['i'];
-   $nid        = $arguments['n'];
-
-   # print "\n";
-   # print "feature id is $feature_id\n";
-   # print "nid is $nid\n";
-   # print "\n";
-
-   if($feature_id > 0){ 
-      # print "indexing feature $feature_id\n";
-     // We register a shutdown function to ensure that the nodes
-     // that are indexed will have proper entries in the search_totals
-     // table.  Without these entries, the searching doesn't work
-     // properly. This function may run for quite a while since
-     // it must calculate the sum of the scores of all entries in
-     // the search_index table.  In the case of common words like
-     // 'contig', this will take quite a while
-      register_shutdown_function('search_update_totals');
-      tripal_feature_index_feature($feature_id, $nid); 
-   }
-   else{ 
-      print "indexing all features...\n";
-      tripal_features_reindex(0);
-   }
+if (isset($arguments['i'])) {
+  $drupal_base_url = parse_url('http://www.example.com');
+  $_SERVER['HTTP_HOST'] = $drupal_base_url['host'];
+  $_SERVER['REQUEST_URI'] = $_SERVER['SCRIPT_NAME'] = $_SERVER['PHP_SELF'];
+  $_SERVER['REMOTE_ADDR'] = NULL;
+  $_SERVER['REQUEST_METHOD'] = NULL;
 
-}
+  require_once 'includes/bootstrap.inc';
+  drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);
 
-/**
- *
- *
- * @ingroup tripal_feature
- */
-function tripal_features_reindex ($max_sync,$job_id = NULL){
-   $i = 0;
+  $feature_id = $arguments['i'];
+  $nid        = $arguments['n'];
 
+  # print "\n";
+  # print "feature id is $feature_id\n";
+  # print "nid is $nid\n";
+  # print "\n";
+
+  if ($feature_id > 0) {
+    # print "indexing feature $feature_id\n";
    // We register a shutdown function to ensure that the nodes
    // that are indexed will have proper entries in the search_totals
    // table.  Without these entries, the searching doesn't work
@@ -63,63 +43,90 @@ function tripal_features_reindex ($max_sync,$job_id = NULL){
    // it must calculate the sum of the scores of all entries in
    // the search_index table.  In the case of common words like
    // 'contig', this will take quite a while
-   register_shutdown_function('search_update_totals');
-
-   // use this SQL statement to get the features that we're going to index. This
-   // SQL statement is derived from the hook_search function in the Drupal API.
-   // Essentially, this is the SQL statement that finds all nodes that need
-   // reindexing, but adjusted to include the chado_feature
-   $sql = "SELECT N.nid, N.title, CF.feature_id ".
-          "FROM {node} N ".
-          "  INNER JOIN chado_feature CF ON CF.nid = N.nid ";
-   $results = db_query($sql);
-
-   // load into ids array
-   $count = 0;
-   $chado_features = array();
-   while($chado_feature = db_fetch_object($results)){
-      $chado_features[$count] = $chado_feature;
-      $count++;
-   }
-
-   // Iterate through features that need to be indexed 
-   $interval = intval($count * 0.01);
-   if($interval >= 0){
-      $interval = 1;
-   }
-   foreach($chado_features as $chado_feature){
-
-      // update the job status every 1% features
-      if($job_id and $i % $interval == 0){
-         $prog = intval(($i/$count)*100);
-         tripal_job_set_progress($job_id,$prog);
-         print "$prog%\n";
-      }
-
-      // sync only the max requested
-      if($max_sync and $i == $max_sync){
-         return '';
-      }
-      $i++;
-
-      # tripal_feature_index_feature ($chado_feature->feature_id,$chado_feature->nid);
-      # parsing all the features can cause memory overruns 
-      # we are not sure why PHP does not clean up the memory as it goes
-      # to avoid this problem we will call this script through an
-      # independent system call
-
-      $cmd = "php " . drupal_get_path('module', 'tripal_feature') . "/indexFeatures.php ";
-      $cmd .= "-i $chado_feature->feature_id -n $chado_feature->nid ";
-
-      # print "\t$cmd\n";
-      # print "\tfeature id is $chado_feature->feature_id\n";
-      # print "\tnid is $chado_feature->nid\n";
-      # print "\n";
-
-      system($cmd);
-   }
-
-   return '';
+    register_shutdown_function('search_update_totals');
+    tripal_feature_index_feature($feature_id, $nid);
+  }
+  else{
+    print "indexing all features...\n";
+    tripal_features_reindex(0);
+  }
+
+}
+
+/**
+ *
+ *
+ * @ingroup tripal_feature
+ */
+function tripal_features_reindex($max_sync, $job_id = NULL) {
+  $i = 0;
+
+  // We register a shutdown function to ensure that the nodes
+  // that are indexed will have proper entries in the search_totals
+  // table.  Without these entries, the searching doesn't work
+  // properly. This function may run for quite a while since
+  // it must calculate the sum of the scores of all entries in
+  // the search_index table.  In the case of common words like
+  // 'contig', this will take quite a while
+  register_shutdown_function('search_update_totals');
+
+  // use this SQL statement to get the features that we're going to index. This
+  // SQL statement is derived from the hook_search function in the Drupal API.
+  // Essentially, this is the SQL statement that finds all nodes that need
+  // reindexing, but adjusted to include the chado_feature
+  $sql = "SELECT N.nid, N.title, CF.feature_id ".
+        "FROM {node} N ".
+        "  INNER JOIN chado_feature CF ON CF.nid = N.nid ";
+  $results = db_query($sql);
+
+  // load into ids array
+  $count = 0;
+  $chado_features = array();
+  while ($chado_feature = db_fetch_object($results)) {
+    $chado_features[$count] = $chado_feature;
+    $count++;
+  }
+
+  // Iterate through features that need to be indexed
+  $interval = intval($count * 0.01);
+  if ($interval >= 0) {
+    $interval = 1;
+  }
+  foreach ($chado_features as $chado_feature) {
+
+    // update the job status every 1% features
+    if ($job_id and $i % $interval == 0) {
+      $prog = intval(($i/$count)*100);
+      tripal_job_set_progress($job_id, $prog);
+      print "$prog%\n";
+    }
+
+    // sync only the max requested
+    if ($max_sync and $i == $max_sync) {
+      return '';
+    }
+    $i++;
+
+  /**
+    * tripal_feature_index_feature ($chado_feature->feature_id,$chado_feature->nid);
+    * parsing all the features can cause memory overruns
+    * we are not sure why PHP does not clean up the memory as it goes
+    * to avoid this problem we will call this script through an
+    * independent system call
+    */
+
+    $cmd = "php " . drupal_get_path('module', 'tripal_feature') . "/indexFeatures.php ";
+    $cmd .= "-i $chado_feature->feature_id -n $chado_feature->nid ";
+
+    # print "\t$cmd\n";
+    # print "\tfeature id is $chado_feature->feature_id\n";
+    # print "\tnid is $chado_feature->nid\n";
+    # print "\n";
+
+    system($cmd);
+    }
+
+  return '';
 }
 
 /**
@@ -127,44 +134,44 @@ function tripal_features_reindex ($max_sync,$job_id = NULL){
  *
  * @ingroup tripal_feature
  */
-function tripal_feature_index_feature ($feature_id,$nid){
-   #print "\tfeature $feature_id nid $nid\n";
-   // return if we haven't been provided with a feature_id
-   if(!$feature_id){
+function tripal_feature_index_feature($feature_id, $nid) {
+  #print "\tfeature $feature_id nid $nid\n";
+  // return if we haven't been provided with a feature_id
+  if (!$feature_id) {
+    return 0;
+  }
+
+  // if we only have a feature_id then let's find a corresponding
+  // node.  If we can't find a node then return.
+  if (!$nid) {
+    $nsql = "SELECT N.nid,N.title FROM {chado_feature} CF ".
+            "  INNER JOIN {node} N ON N.nid = CF.nid ".
+            "WHERE CF.feature_id = %d";
+    $node = db_fetch_object(db_query($nsql, $feature_id));
+    if (!$node) {
       return 0;
-   }
-
-   // if we only have a feature_id then let's find a corresponding
-   // node.  If we can't find a node then return.
-   if(!$nid){
-      $nsql = "SELECT N.nid,N.title FROM {chado_feature} CF ".
-              "  INNER JOIN {node} N ON N.nid = CF.nid ".
-              "WHERE CF.feature_id = %d";
-      $node = db_fetch_object(db_query($nsql,$feature_id));
-      if(!$node){
-         return 0;
-      }
-      $node = node_load($node->nid);
-   } else {
-      $node = node_load($nid);
-   }
-
-   // node load the noad, the comments and the taxonomy and
-   // index
-   $node->build_mode = NODE_BUILD_SEARCH_INDEX;
-   $node = node_build_content($node, FALSE, FALSE);
-   $node->body = drupal_render($node->content);
-   node_invoke_nodeapi($node, 'view', FALSE, FALSE);
-//   $node->body .= module_invoke('comment', 'nodeapi', $node, 'update index');
-//   $node->body .= module_invoke('taxonomy','nodeapi', $node, 'update index');
-   //   print "$node->title: $node->body\n";
-   search_index($node->nid,'node',$node->body);
-
-   # $mem = memory_get_usage(TRUE);
-   # $mb = $mem/1048576;
-   # print "$mb mb\n";
-
-   return 1;
+    }
+    $node = node_load($node->nid);
+  }
+  else {
+    $node = node_load($nid);
+  }
+
+  // node load the noad, the comments and the taxonomy and
+  // index
+  $node->build_mode = NODE_BUILD_SEARCH_INDEX;
+  $node = node_build_content($node, FALSE, FALSE);
+  $node->body = drupal_render($node->content);
+  node_invoke_nodeapi($node, 'view', FALSE, FALSE);
+  //   $node->body .= module_invoke('comment', 'nodeapi', $node, 'update index');
+  //   $node->body .= module_invoke('taxonomy','nodeapi', $node, 'update index');
+  //   print "$node->title: $node->body\n";
+  search_index($node->nid, 'node', $node->body);
+
+  # $mem = memory_get_usage(TRUE);
+  # $mb = $mem/1048576;
+  # print "$mb mb\n";
+
+  return 1;
 }
 
-?>

+ 379 - 370
tripal_feature/syncFeatures.php

@@ -1,268 +1,274 @@
 <?php
 
+/**
+ * @file
+ * @todo Add file header description
+ */
+
 
 # This script can be run as a stand-alone script to sync all the features from chado to drupal
 // Parameter f specifies the feature_id to sync
-// -f 0 will sync all features 
+// -f 0 will sync all features
 
 $arguments = getopt("f:");
 
-if(isset($arguments['f'])){
-   $drupal_base_url = parse_url('http://www.example.com');
-   $_SERVER['HTTP_HOST'] = $drupal_base_url['host'];
-   $_SERVER['REQUEST_URI'] = $_SERVER['SCRIPT_NAME'] = $_SERVER['PHP_SELF'];
-   $_SERVER['REMOTE_ADDR'] = NULL;
-   $_SERVER['REQUEST_METHOD'] = NULL;
-	
-   require_once 'includes/bootstrap.inc';
-   drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);
-
-   $feature_id = $arguments['f'];
-
-   if($feature_id > 0 ){ 
-      tripal_feature_sync_feature($feature_id); 
-   }
-   else{ 
-      print "syncing all features...\n";
-      tripal_feature_sync_features();
-   }   
+if (isset($arguments['f'])) {
+  $drupal_base_url = parse_url('http://www.example.com');
+  $_SERVER['HTTP_HOST'] = $drupal_base_url['host'];
+  $_SERVER['REQUEST_URI'] = $_SERVER['SCRIPT_NAME'] = $_SERVER['PHP_SELF'];
+  $_SERVER['REMOTE_ADDR'] = NULL;
+  $_SERVER['REQUEST_METHOD'] = NULL;
+
+  require_once 'includes/bootstrap.inc';
+  drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);
+
+  $feature_id = $arguments['f'];
+
+  if ($feature_id > 0 ) {
+    tripal_feature_sync_feature($feature_id);
+  }
+  else{
+    print "syncing all features...\n";
+    tripal_feature_sync_features();
+  }
 }
 /**
-*
-*/
-function tripal_feature_sync_form (){
-
-   $form['description'] = array(
-      '#type' => 'item',
-      '#value' => t("Add feature types, optionally select an organism and ".
-         "click the 'Sync all Features' button to create Drupal ".
-         "content for features in chado. Only features of the types listed ".
-         "below in the Feature Types box will be synced. You may limit the ".
-         "features to be synced by a specific organism. Depending on the ".
-         "number of features in the chado database this may take a long ".
-         "time to complete. "),
-   );
-
-   $form['feature_types'] = array(
-      '#title'       => t('Feature Types'),
-      '#type'        => 'textarea',
-      '#description' => t('Enter the names of the sequence types that the ".
-         "site will support with independent pages.  Pages for these data ".
-         "types will be built automatically for features that exist in the ".
-         "chado database.  The names listed here should be spearated by ".
-         "spaces or entered separately on new lines. The names must match ".
-         "exactly (spelling and case) with terms in the sequence ontology'),
-      '#required'    => TRUE,
-      '#default_value' => variable_get('chado_sync_feature_types','gene contig'),
-   );
-
-   // get the list of organisms
-   $sql = "SELECT * FROM {organism} ORDER BY genus, species";
-   $orgs = tripal_organism_get_synced(); 
-   $organisms[] = ''; 
-   foreach($orgs as $organism){
-      $organisms[$organism->organism_id] = "$organism->genus $organism->species ($organism->common_name)";
-   }
-   $form['organism_id'] = array (
-     '#title'       => t('Organism'),
-     '#type'        => t('select'),
-     '#description' => t("Choose the organism for which features will be deleted."),
-     '#options'     => $organisms,
-   );
-
-
-   $form['button'] = array(
-      '#type' => 'submit',
-      '#value' => t('Sync all Features'),
-      '#weight' => 3,
-   );
-
-   return $form;
+ *
+ */
+function tripal_feature_sync_form() {
+
+  $form['description'] = array(
+  '#type' => 'item',
+  '#value' => t("Add feature types, optionally select an organism and ".
+     "click the 'Sync all Features' button to create Drupal ".
+     "content for features in chado. Only features of the types listed ".
+     "below in the Feature Types box will be synced. You may limit the ".
+     "features to be synced by a specific organism. Depending on the ".
+     "number of features in the chado database this may take a long ".
+     "time to complete. "),
+  );
+
+  $form['feature_types'] = array(
+    '#title'       => t('Feature Types'),
+    '#type'        => 'textarea',
+    '#description' => t('Enter the names of the sequence types that the ".
+       "site will support with independent pages.  Pages for these data ".
+       "types will be built automatically for features that exist in the ".
+       "chado database.  The names listed here should be spearated by ".
+       "spaces or entered separately on new lines. The names must match ".
+       "exactly (spelling and case) with terms in the sequence ontology'),
+    '#required'    => TRUE,
+    '#default_value' => variable_get('chado_sync_feature_types', 'gene contig'),
+  );
+
+  // get the list of organisms
+  $sql = "SELECT * FROM {organism} ORDER BY genus, species";
+  $orgs = tripal_organism_get_synced();
+  $organisms[] = '';
+  foreach ($orgs as $organism) {
+    $organisms[$organism->organism_id] = "$organism->genus $organism->species ($organism->common_name)";
+  }
+  $form['organism_id'] = array(
+    '#title'       => t('Organism'),
+    '#type'        => t('select'),
+    '#description' => t("Choose the organism for which features will be deleted."),
+    '#options'     => $organisms,
+  );
+
+
+  $form['button'] = array(
+    '#type' => 'submit',
+    '#value' => t('Sync all Features'),
+    '#weight' => 3,
+  );
+
+  return $form;
 }
 /**
-*
-*/
-function tripal_feature_sync_form_validate ($form, &$form_state){
-   $organism_id   = $form_state['values']['organism_id'];
-   $feature_types = $form_state['values']['feature_types'];
+ *
+ */
+function tripal_feature_sync_form_validate($form, &$form_state) {
+  $organism_id   = $form_state['values']['organism_id'];
+  $feature_types = $form_state['values']['feature_types'];
 
-   // nothing to do
+  // nothing to do
 }
 /**
-*
-*/
-function tripal_feature_sync_form_submit ($form, &$form_state){
+ *
+ */
+function tripal_feature_sync_form_submit($form, &$form_state) {
 
-   global $user;
+  global $user;
 
-   $organism_id   = $form_state['values']['organism_id'];
-   $feature_types = $form_state['values']['feature_types'];
+  $organism_id   = $form_state['values']['organism_id'];
+  $feature_types = $form_state['values']['feature_types'];
 
-   $job_args = array(0,$organism_id,$feature_types);
+  $job_args = array(0, $organism_id, $feature_types);
 
-   if($organism_id){
-      $organism = tripal_core_chado_select('organism',array('genus','species'),array('organism_id' => $organism_id));
-      $title = "Sync all features for " .  $organism[0]->genus . " " . $organism[0]->species;
-   } else {
-      $title = t('Sync all features for all synced organisms');
-   }
+  if ($organism_id) {
+    $organism = tripal_core_chado_select('organism', array('genus', 'species'), array('organism_id' => $organism_id));
+    $title = "Sync all features for " .  $organism[0]->genus . " " . $organism[0]->species;
+  }
+  else {
+    $title = t('Sync all features for all synced organisms');
+  }
 
-   variable_set('chado_sync_feature_types',$feature_types);
+  variable_set('chado_sync_feature_types', $feature_types);
 
-   tripal_add_job($title,'tripal_feature',
-         'tripal_feature_sync_features',$job_args,$user->uid);
+  tripal_add_job($title, 'tripal_feature',
+    'tripal_feature_sync_features', $job_args, $user->uid);
 }
 /**
-*
-*/   
-function tripal_feature_set_urls($job_id = NULL){
-   // first get the list of features that have been synced
-   $sql = "SELECT * FROM {chado_feature}";
-   $nodes = db_query($sql);
-   while($node = db_fetch_object($nodes)){
-      // now get the feature details
-      $feature_arr = tripal_core_chado_select('feature',
-         array('feature_id','name','uniquename'),
-         array('feature_id' => $node->feature_id));
-      $feature = $feature_arr[0];
-
-      tripal_feature_set_feature_url($node,$feature);
-   }
+ *
+ */
+function tripal_feature_set_urls($job_id = NULL) {
+  // first get the list of features that have been synced
+  $sql = "SELECT * FROM {chado_feature}";
+  $nodes = db_query($sql);
+  while ($node = db_fetch_object($nodes)) {
+    // now get the feature details
+    $feature_arr = tripal_core_chado_select('feature',
+      array('feature_id', 'name', 'uniquename'),
+      array('feature_id' => $node->feature_id));
+    $feature = $feature_arr[0];
+
+    tripal_feature_set_feature_url($node, $feature);
+  }
 }
 /**
-*
-*/
-function tripal_feature_set_feature_url($node,$feature){
-
-   // determine which URL alias to use
-   $alias_type = variable_get('chado_feature_url','internal ID');
-   $aprefix = variable_get('chado_feature_accession_prefix','ID');
-   switch ($alias_type) {
-      case 'feature name':
-         $url_alias = $feature->name;
-         break;
-      case 'feature unique name':
-         $url_alias = $feature->uniquename;
-         break;
-      default:
-         $url_alias = "$aprefix$feature->feature_id";
-   }
-   print "Setting $alias_type as URL alias for $feature->name: node/$node->nid => $url_alias\n";
-   // remove any previous alias
-   db_query("DELETE FROM {url_alias} WHERE src = '%s'", "node/$node->nid");
-   // add the new alias
-   path_set_alias("node/$node->nid",$url_alias);
+ *
+ */
+function tripal_feature_set_feature_url($node, $feature) {
+
+  // determine which URL alias to use
+  $alias_type = variable_get('chado_feature_url', 'internal ID');
+  $aprefix = variable_get('chado_feature_accession_prefix', 'ID');
+  switch ($alias_type) {
+    case 'feature name':
+      $url_alias = $feature->name;
+      break;
+    case 'feature unique name':
+      $url_alias = $feature->uniquename;
+      break;
+    default:
+      $url_alias = "$aprefix$feature->feature_id";
+  }
+  print "Setting $alias_type as URL alias for $feature->name: node/$node->nid => $url_alias\n";
+  // remove any previous alias
+  db_query("DELETE FROM {url_alias} WHERE src = '%s'", "node/$node->nid");
+  // add the new alias
+  path_set_alias("node/$node->nid", $url_alias);
 }
 /**
  *
  *
  * @ingroup tripal_feature
  */
-function tripal_feature_sync_features ($max_sync = 0, $organism_id = NULL, 
-   $feature_types = NULL, $job_id = NULL)
-{
-   //print "Syncing features (max of $max_sync)\n";
-   $i = 0;
-
-   // get the list of available sequence ontology terms for which
-   // we will build drupal pages from features in chado.  If a feature
-   // is not one of the specified typse we won't build a node for it.
-   if(!$feature_types){
-      $allowed_types = variable_get('chado_sync_feature_types','gene contig');
-   } else {
-      $allowed_types = $feature_types;
-   }
-   $allowed_types = preg_replace("/[\s\n\r]+/"," ",$allowed_types);
-
-   print "Looking for features of type: $allowed_types\n";
-
-   $so_terms = split(' ',$allowed_types);
-   $where_cvt = "";
-   foreach ($so_terms as $term){
-      $where_cvt .= "CVT.name = '$term' OR ";
-   }
-   $where_cvt = substr($where_cvt,0,strlen($where_cvt)-3);  # strip trailing 'OR'
-
-   // get the list of organisms that are synced and only include features from
-   // those organisms
-   $orgs = tripal_organism_get_synced();
-   $where_org = "";
-   foreach($orgs as $org){
-      if($organism_id){
-         if($org->organism_id and $org->organism_id == $organism_id){
-            $where_org .= "F.organism_id = $org->organism_id OR ";
-         }
-      } 
-      else {
-         if($org->organism_id){
-            $where_org .= "F.organism_id = $org->organism_id OR ";
-         }
-      }
-   }
-   $where_org = substr($where_org,0,strlen($where_org)-3);  # strip trailing 'OR'
-
-   // use this SQL statement to get the features that we're going to upload
-   $sql = "SELECT feature_id ".
-          "FROM {FEATURE} F ".
-          "  INNER JOIN Cvterm CVT ON F.type_id = CVT.cvterm_id ".
-          "  INNER JOIN CV on CV.cv_id = CVT.cv_id ".
-          "WHERE ($where_cvt) AND ($where_org) AND CV.name = 'sequence' ".
-          "ORDER BY feature_id";
-
-   // get the list of features
-   $previous_db = tripal_db_set_active('chado');  // use chado database
-   $results = db_query($sql);
-
-   tripal_db_set_active($previous_db);  // now use drupal database
-
-   // load into ids array
-   $count = 0;
-   $ids = array();
-   while($id = db_fetch_object($results)){
-      $ids[$count] = $id->feature_id;
-      $count++;
-   }
-
-   // make sure our vocabularies are set before proceeding
-   tripal_feature_set_vocabulary();
-
-   // pre-create the SQL statement that will be used to check
-   // if a feature has already been synced.  We skip features
-   // that have been synced
-   $sql = "SELECT * FROM {chado_feature} WHERE feature_id = %d";
-
-   // Iterate through features that need to be synced
-   $interval = intval($count * 0.01);
-   if($interval > 1){
-      $interval = 1;
-   }
-   $num_ids = sizeof($ids);
-   $i = 0;
-   foreach($ids as $feature_id){
-      // update the job status every 1% features
-      if($job_id and $i % $interval == 0){
-         tripal_job_set_progress($job_id,intval(($i/$count)*100));
-      }
-      // if we have a maximum number to sync then stop when we get there
-      // if not then just continue on
-      if($max_sync and $i == $max_sync){
-         return '';
+function tripal_feature_sync_features($max_sync = 0, $organism_id = NULL,
+  $feature_types = NULL, $job_id = NULL) {
+  //print "Syncing features (max of $max_sync)\n";
+  $i = 0;
+
+  // get the list of available sequence ontology terms for which
+  // we will build drupal pages from features in chado.  If a feature
+  // is not one of the specified typse we won't build a node for it.
+  if (!$feature_types) {
+    $allowed_types = variable_get('chado_sync_feature_types', 'gene contig');
+  }
+  else {
+    $allowed_types = $feature_types;
+  }
+  $allowed_types = preg_replace("/[\s\n\r]+/", " ", $allowed_types);
+
+  print "Looking for features of type: $allowed_types\n";
+
+  $so_terms = split(' ', $allowed_types);
+  $where_cvt = "";
+  foreach ($so_terms as $term) {
+    $where_cvt .= "CVT.name = '$term' OR ";
+  }
+  $where_cvt = drupal_substr($where_cvt, 0, drupal_strlen($where_cvt)-3);  # strip trailing 'OR'
+
+  // get the list of organisms that are synced and only include features from
+  // those organisms
+  $orgs = tripal_organism_get_synced();
+  $where_org = "";
+  foreach ($orgs as $org) {
+    if ($organism_id) {
+      if ($org->organism_id and $org->organism_id == $organism_id) {
+        $where_org .= "F.organism_id = $org->organism_id OR ";
       }
-      if(!db_fetch_object(db_query($sql,$feature_id))){
-        
-         # parsing all the features can cause memory overruns 
-         # we are not sure why PHP does not clean up the memory as it goes
-         # to avoid this problem we will call this script through an
-         # independent system call
-         print "$i of $num_ids Syncing feature id: $feature_id\n";
-         $cmd = "php " . drupal_get_path('module', 'tripal_feature') . "/syncFeatures.php -f $feature_id ";
-         system($cmd);
-
-      }
-      $i++;
-   }
-
-   return '';
+    }
+    else {
+    if ($org->organism_id) {
+      $where_org .= "F.organism_id = $org->organism_id OR ";
+    }
+    }
+  }
+  $where_org = drupal_substr($where_org, 0, drupal_strlen($where_org)-3);  # strip trailing 'OR'
+
+  // use this SQL statement to get the features that we're going to upload
+  $sql = "SELECT feature_id ".
+        "FROM {FEATURE} F ".
+        "  INNER JOIN Cvterm CVT ON F.type_id = CVT.cvterm_id ".
+        "  INNER JOIN CV on CV.cv_id = CVT.cv_id ".
+        "WHERE ($where_cvt) AND ($where_org) AND CV.name = 'sequence' ".
+        "ORDER BY feature_id";
+
+  // get the list of features
+  $previous_db = tripal_db_set_active('chado');  // use chado database
+  $results = db_query($sql);
+
+  tripal_db_set_active($previous_db);  // now use drupal database
+
+  // load into ids array
+  $count = 0;
+  $ids = array();
+  while ($id = db_fetch_object($results)) {
+    $ids[$count] = $id->feature_id;
+    $count++;
+  }
+
+  // make sure our vocabularies are set before proceeding
+  tripal_feature_set_vocabulary();
+
+  // pre-create the SQL statement that will be used to check
+  // if a feature has already been synced.  We skip features
+  // that have been synced
+  $sql = "SELECT * FROM {chado_feature} WHERE feature_id = %d";
+
+  // Iterate through features that need to be synced
+  $interval = intval($count * 0.01);
+  if ($interval > 1) {
+    $interval = 1;
+  }
+  $num_ids = sizeof($ids);
+  $i = 0;
+  foreach ($ids as $feature_id) {
+    // update the job status every 1% features
+    if ($job_id and $i % $interval == 0) {
+      tripal_job_set_progress($job_id, intval(($i/$count)*100));
+    }
+    // if we have a maximum number to sync then stop when we get there
+    // if not then just continue on
+    if ($max_sync and $i == $max_sync) {
+      return '';
+    }
+    if (!db_fetch_object(db_query($sql, $feature_id))) {
+
+      # parsing all the features can cause memory overruns
+      # we are not sure why PHP does not clean up the memory as it goes
+      # to avoid this problem we will call this script through an
+      # independent system call
+      print "$i of $num_ids Syncing feature id: $feature_id\n";
+      $cmd = "php " . drupal_get_path('module', 'tripal_feature') . "/syncFeatures.php -f $feature_id ";
+      system($cmd);
+
+    }
+    $i++;
+  }
+
+  return '';
 }
 
 /**
@@ -270,149 +276,152 @@ function tripal_feature_sync_features ($max_sync = 0, $organism_id = NULL,
  *
  * @ingroup tripal_feature
  */
-function tripal_feature_sync_feature ($feature_id){
-//   print "\tSyncing feature $feature_id\n";
-
-   $mem = memory_get_usage(TRUE);
-   $mb = $mem/1048576;
-//   print "$mb mb\n";
-
-   global $user;
-   $create_node = 1;   // set to 0 if the node exists and we just sync and not create
-
-   // get the accession prefix
-   $aprefix = variable_get('chado_feature_accession_prefix','ID');
-
-   // if we don't have a feature_id then return
-   if(!$feature_id){
-      drupal_set_message(t("Please provide a feature_id to sync"));
-      return '';
-   }
-
-   // get information about this feature
-   $fsql = "SELECT F.feature_id, F.name, F.uniquename,O.genus, ".
-           "    O.species,CVT.name as cvname,F.residues,F.organism_id ".
-           "FROM {FEATURE} F ".
-           "  INNER JOIN Cvterm CVT ON F.type_id = CVT.cvterm_id ".
-           "  INNER JOIN Organism O ON F.organism_id = O.organism_ID ".
-           "WHERE F.feature_id = %d";
-   $previous_db = tripal_db_set_active('chado');  // use chado database
-   $feature = db_fetch_object(db_query($fsql,$feature_id));
-   tripal_db_set_active($previous_db);  // now use drupal database
-
-   // get the synonyms for this feature
-   $synsql = "SELECT S.name ".
-             "FROM {feature_synonym} FS ".
-             "  INNER JOIN {synonym} S on FS.synonym_id = S.synonym_id ".
-             "WHERE FS.feature_id = %d";
-   $previous_db = tripal_db_set_active('chado');  // use chado database
-   $synonyms = db_query($synsql,$feature_id);
-   tripal_db_set_active($previous_db);  // now use drupal database
-
-   // now add these synonyms to the feature object as a single string   
-   $synstring = '';
-   while($synonym = db_fetch_object($synonyms)){
-      $synstring .= "$synonym->name\n";
-   }        
-   $feature->synonyms = $synstring;
-
-   // check to make sure that we don't have any nodes with this feature name as a title
-   // but without a corresponding entry in the chado_feature table if so then we want to
-   // clean up that node.  (If a node is found we don't know if it belongs to our feature or
-   // not since features can have the same name/title.)
-   $tsql =  "SELECT * FROM {node} N ".
-            "WHERE title = '%s'";
-   $cnsql = "SELECT * FROM {chado_feature} ".
-            "WHERE nid = %d";
-   $nodes = db_query($tsql,$feature->name);
-   // cycle through all nodes that may have this title
-   while($node = db_fetch_object($nodes)){
-      $feature_nid = db_fetch_object(db_query($cnsql,$node->nid));
-      if(!$feature_nid){
-         drupal_set_message(t("$feature_id: A node is present but the chado_feature entry is missing... correcting"));
-         node_delete($node->nid);
+function tripal_feature_sync_feature($feature_id) {
+  //   print "\tSyncing feature $feature_id\n";
+
+  $mem = memory_get_usage(TRUE);
+  $mb = $mem/1048576;
+  //   print "$mb mb\n";
+
+  global $user;
+  $create_node = 1;   // set to 0 if the node exists and we just sync and not create
+
+  // get the accession prefix
+  $aprefix = variable_get('chado_feature_accession_prefix', 'ID');
+
+  // if we don't have a feature_id then return
+  if (!$feature_id) {
+    drupal_set_message(t("Please provide a feature_id to sync"));
+    return '';
+  }
+
+  // get information about this feature
+  $fsql = "SELECT F.feature_id, F.name, F.uniquename,O.genus, ".
+         "    O.species,CVT.name as cvname,F.residues,F.organism_id ".
+         "FROM {FEATURE} F ".
+         "  INNER JOIN Cvterm CVT ON F.type_id = CVT.cvterm_id ".
+         "  INNER JOIN Organism O ON F.organism_id = O.organism_ID ".
+         "WHERE F.feature_id = %d";
+  $previous_db = tripal_db_set_active('chado');  // use chado database
+  $feature = db_fetch_object(db_query($fsql, $feature_id));
+  tripal_db_set_active($previous_db);  // now use drupal database
+
+  // get the synonyms for this feature
+  $synsql = "SELECT S.name ".
+           "FROM {feature_synonym} FS ".
+           "  INNER JOIN {synonym} S on FS.synonym_id = S.synonym_id ".
+           "WHERE FS.feature_id = %d";
+  $previous_db = tripal_db_set_active('chado');  // use chado database
+  $synonyms = db_query($synsql, $feature_id);
+  tripal_db_set_active($previous_db);  // now use drupal database
+
+  // now add these synonyms to the feature object as a single string
+  $synstring = '';
+  while ($synonym = db_fetch_object($synonyms)) {
+    $synstring .= "$synonym->name\n";
+  }
+  $feature->synonyms = $synstring;
+
+  // check to make sure that we don't have any nodes with this feature name as a title
+  // but without a corresponding entry in the chado_feature table if so then we want to
+  // clean up that node.  (If a node is found we don't know if it belongs to our feature or
+  // not since features can have the same name/title.)
+  $tsql =  "SELECT * FROM {node} N ".
+          "WHERE title = '%s'";
+  $cnsql = "SELECT * FROM {chado_feature} ".
+          "WHERE nid = %d";
+  $nodes = db_query($tsql, $feature->name);
+  // cycle through all nodes that may have this title
+  while ($node = db_fetch_object($nodes)) {
+    $feature_nid = db_fetch_object(db_query($cnsql, $node->nid));
+    if (!$feature_nid) {
+      drupal_set_message(t("%feature_id: A node is present but the chado_feature entry is missing... correcting", array('%feature_id' => $feature_id)));
+      node_delete($node->nid);
+    }
+  }
+
+  // check if this feature already exists in the chado_feature table.
+  // if we have a chado feature, we want to check to see if we have a node
+  $cfsql = "SELECT * FROM {chado_feature} ".
+          "WHERE feature_id = %d";
+  // @coder-ignore: don't need to use db_rewrite_sql() since need all nodes regardless of access control
+  $nsql =  "SELECT * FROM {node} ".
+          "WHERE nid = %d";
+  $chado_feature = db_fetch_object(db_query($cfsql, $feature->feature_id));
+  if ($chado_feature) {
+    drupal_set_message(t("%feature_id: A chado_feature entry exists", array('%feature_id' => $feature_id)));
+    $node = db_fetch_object(db_query($nsql, $chado_feature->nid));
+    if (!$node) {
+      // if we have a chado_feature but not a node then we have a problem and
+      // need to cleanup
+      drupal_set_message(t("%feature_id: The node is missing, but has a chado_feature entry... correcting", array('%feature_id' => $feature_id)));
+      $df_sql = "DELETE FROM {chado_feature} WHERE feature_id = %d";
+      db_query($df_sql, $feature_id);
+    }
+    else {
+      drupal_set_message(t("%feature_id: A corresponding node exists", array('%feature_id' => $feature_id)));
+      $create_node = 0;
+    }
+  }
+
+  // if we've encountered an error then just return.
+  if ($error_msg = db_error()) {
+    //print "$error_msg\n";
+    return '';
+  }
+
+  // if a drupal node does not exist for this feature then we want to
+  // create one.  Note that the node_save call in this block
+  // will call the hook_submit function which
+  if ($create_node) {
+    // get the organism for this feature
+    $sql = "SELECT * FROM {organism} WHERE organism_id = %d";
+    $organism = db_fetch_object(db_query($sql, $feature->organism_id));
+
+    drupal_set_message(t("%feature_id: Creating node $feature->name", array('%feature_id' => $feature_id)));
+    $new_node = new stdClass();
+    $new_node->type = 'chado_feature';
+    $new_node->uid = $user->uid;
+    $new_node->title = "$feature->name, $feature->uniquename ($feature->cvname) $organism->genus $organism->species";
+    $new_node->fname = "$feature->name";
+    $new_node->uniquename = "$feature->uniquename";
+    $new_node->feature_id = $feature->feature_id;
+    $new_node->residues = $feature->residues;
+    $new_node->organism_id = $feature->organism_id;
+    $new_node->feature_type = $feature->cvname;
+    $new_node->synonyms = $feature->synonyms;
+
+    // validate the node and if okay then submit
+    node_validate($new_node);
+    if ($errors = form_get_errors()) {
+      foreach ($errors as $key => $msg) {
+        drupal_set_message(t("%msg", array('%msg' => $msg)));
       }
-   }
-
-   // check if this feature already exists in the chado_feature table.
-   // if we have a chado feature, we want to check to see if we have a node
-   $cfsql = "SELECT * FROM {chado_feature} ".
-            "WHERE feature_id = %d";
-   $nsql =  "SELECT * FROM {node} ".
-            "WHERE nid = %d";
-   $chado_feature = db_fetch_object(db_query($cfsql,$feature->feature_id));
-   if($chado_feature){
-      drupal_set_message(t("$feature_id: A chado_feature entry exists"));
-      $node = db_fetch_object(db_query($nsql,$chado_feature->nid));
-      if(!$node){
-         // if we have a chado_feature but not a node then we have a problem and
-         // need to cleanup
-         drupal_set_message(t("$feature_id: The node is missing, but has a chado_feature entry... correcting"));
-         $df_sql = "DELETE FROM {chado_feature} WHERE feature_id = %d";
-         db_query($df_sql,$feature_id);
-      } else {
-         drupal_set_message(t("$feature_id: A corresponding node exists"));
-         $create_node = 0;
-      }
-   }
+      return $errors;
+    }
+    else {
+      $node = node_submit($new_node);
+      node_save($node);
+    }
 
-   // if we've encountered an error then just return.
-   if($error_msg = db_error()){
-      //print "$error_msg\n";
-      return '';
-   }
-
-   // if a drupal node does not exist for this feature then we want to
-   // create one.  Note that the node_save call in this block
-   // will call the hook_submit function which
-   if($create_node){
-      // get the organism for this feature
-      $sql = "SELECT * FROM {organism} WHERE organism_id = %d";
-      $organism = db_fetch_object(db_query($sql,$feature->organism_id));
-
-      drupal_set_message(t("$feature_id: Creating node $feature->name"));
-      $new_node = new stdClass();
-      $new_node->type = 'chado_feature';
-      $new_node->uid = $user->uid;
-      $new_node->title = "$feature->name, $feature->uniquename ($feature->cvname) $organism->genus $organism->species";
-      $new_node->fname = "$feature->name";
-      $new_node->uniquename = "$feature->uniquename";
-      $new_node->feature_id = $feature->feature_id;
-      $new_node->residues = $feature->residues;
-      $new_node->organism_id = $feature->organism_id;
-      $new_node->feature_type = $feature->cvname;
-      $new_node->synonyms = $feature->synonyms;
-
-      // validate the node and if okay then submit
-      node_validate($new_node);
-      if ($errors = form_get_errors()) {
-         foreach($errors as $key => $msg){
-            drupal_set_message($msg);
-         }
-         return $errors;
-      } else {
-         $node = node_submit($new_node);
-         node_save($node);
-      }
-
-   }
-   else {
-      $node = $chado_feature;
-   }
+  }
+  else {
+    $node = $chado_feature;
+  }
 
 
-   // set the taxonomy for this node
-   drupal_set_message(t("$feature_id ($node->nid): setting taxonomy"));
-   tripal_feature_set_taxonomy($node,$feature_id);
+  // set the taxonomy for this node
+  drupal_set_message(t("%feature_id ($node->nid): setting taxonomy", array('%feature_id' => $feature_id)));
+  tripal_feature_set_taxonomy($node, $feature_id);
 
-   // reindex the node
-   // drupal_set_message(t("$feature_id( $node->nid): indexing"));
-   // tripal_feature_index_feature ($feature_id,$node->nid);
+  // reindex the node
+  // drupal_set_message(t("$feature_id( $node->nid): indexing"));
+  // tripal_feature_index_feature ($feature_id,$node->nid);
 
-   // set the URL alias for this node
-   tripal_feature_set_feature_url($node,$feature);
+  // set the URL alias for this node
+  tripal_feature_set_feature_url($node, $feature);
 
 
-   return '';
+  return '';
 }
-?>
+

+ 116 - 116
tripal_feature/tripal_feature-db_references.inc

@@ -13,13 +13,13 @@
 function tripal_feature_add_ALL_dbreferences_page($node) {
   $output = '';
 
-  $output .= tripal_feature_implement_add_chado_properties_progress('db_references') . '<br>';
-  $output .= '<b>All Database References should strictly pertain to THE CURRENT Individual</b><br>';
-  $output .= '<br><b>Current Database References</b><br>';
+  $output .= tripal_feature_implement_add_chado_properties_progress('db_references') . '<br />';
+  $output .= '<b>All Database References should strictly pertain to THE CURRENT Individual</b><br />';
+  $output .= '<br /><b>Current Database References</b><br />';
   $output .= list_dbreferences_for_node($node->db_references);
-  $output .= '<br><br>';
+  $output .= '<br /><br />';
   $output .= drupal_get_form('tripal_feature_add_ONE_dbreference_form', $node);
-  $output .= '<br>';
+  $output .= '<br />';
   $output .= drupal_get_form('tripal_feature_implement_add_chado_properties_navigate', 'db_references', $node->nid);
   return $output;
 }
@@ -84,29 +84,29 @@ function tripal_feature_add_ONE_dbreference_form($form_state, $node) {
  */
 function tripal_feature_add_ONE_dbreference_form_validate($form, &$form_state) {
 
-   $db_id = $form_state['values']['db_id'];
-   $accession = $form_state['values']['accession'];
-   $description = $form_state['values']['description'];
-   $feature_id = $form_state['values']['feature_id'];
-   $nid = $form_state['values']['nid'];
-
-   // Check database is valid db_id in chado
-   $previous_db = tripal_db_set_active('chado');
-   $tmp_obj = db_fetch_object(db_query("SELECT count(*) as count FROM {db} WHERE db_id=%d", $db_id));
-   tripal_db_set_active($previous_db);
-   if ($tmp_obj->count != 1) {
-      form_set_error('database', 'The database you selected is not valid. Please choose another one.');
-   }
-
-   // Check Accession is unique for database
-   $previous_db = tripal_db_set_active('chado');
-   $sql = "SELECT count(*) as count FROM {dbxref} WHERE accession='%s' and db_id = %d";
-   $tmp_obj = db_fetch_object(db_query($sql, $accession, $db_id));
-   tripal_db_set_active($previous_db);
-
-   if ($tmp_obj->count > 0) {
-      form_set_error('accession', 'This accession has already been assigned to another feature in the selected database.');
-   }
+  $db_id = $form_state['values']['db_id'];
+  $accession = $form_state['values']['accession'];
+  $description = $form_state['values']['description'];
+  $feature_id = $form_state['values']['feature_id'];
+  $nid = $form_state['values']['nid'];
+
+  // Check database is valid db_id in chado
+  $previous_db = tripal_db_set_active('chado');
+  $tmp_obj = db_fetch_object(db_query("SELECT count(*) as count FROM {db} WHERE db_id=%d", $db_id));
+  tripal_db_set_active($previous_db);
+  if ($tmp_obj->count != 1) {
+    form_set_error('database', 'The database you selected is not valid. Please choose another one.');
+  }
+
+  // Check Accession is unique for database
+  $previous_db = tripal_db_set_active('chado');
+  $sql = "SELECT count(*) as count FROM {dbxref} WHERE accession='%s' and db_id = %d";
+  $tmp_obj = db_fetch_object(db_query($sql, $accession, $db_id));
+  tripal_db_set_active($previous_db);
+
+  if ($tmp_obj->count > 0) {
+    form_set_error('accession', 'This accession has already been assigned to another feature in the selected database.');
+  }
 
 }
 
@@ -117,33 +117,33 @@ function tripal_feature_add_ONE_dbreference_form_validate($form, &$form_state) {
  */
 function tripal_feature_add_ONE_dbreference_form_submit($form, &$form_state) {
 
-   $db_id = $form_state['values']['db_id'];
-   $accession = $form_state['values']['accession'];
-   $description = $form_state['values']['description'];
-   $feature_id = $form_state['values']['feature_id'];
-   $nid = $form_state['values']['nid'];
+  $db_id = $form_state['values']['db_id'];
+  $accession = $form_state['values']['accession'];
+  $description = $form_state['values']['description'];
+  $feature_id = $form_state['values']['feature_id'];
+  $nid = $form_state['values']['nid'];
 
-   // create dbxref
-   $previous_db = tripal_db_set_active('chado');
-   $isql =  "INSERT INTO {dbxref} (db_id, accession, description) VALUES (%d, '%s', '%s')";
-   db_query($isql, $db_id, $accession, $description);
-   tripal_db_set_active($previous_db);
+  // create dbxref
+  $previous_db = tripal_db_set_active('chado');
+  $isql =  "INSERT INTO {dbxref} (db_id, accession, description) VALUES (%d, '%s', '%s')";
+  db_query($isql, $db_id, $accession, $description);
+  tripal_db_set_active($previous_db);
 
-   //create feature_dbxref
-   $dbxref = tripal_db_get_dbxref( array('db_id' => array('type' => 'INT', 'value' => $form_state['values']['db_id']),
-                       'accession' => array('type' => 'STRING', 'exact' => TRUE, 'value' => $form_state['values']['accession']) ) );
+  //create feature_dbxref
+  $dbxref = tripal_db_get_dbxref( array('db_id' => array('type' => 'INT', 'value' => $form_state['values']['db_id']),
+                     'accession' => array('type' => 'STRING', 'exact' => TRUE, 'value' => $form_state['values']['accession']) ) );
 
   if (!empty($dbxref->dbxref_id)) {
     $previous_db = tripal_db_set_active('chado');
       $isql = "INSERT INTO {feature_dbxref} (feature_id, dbxref_id) VALUES (%d, %d)";
       db_query($isql, $feature_id, $dbxref->dbxref_id);
     tripal_db_set_active($previous_db);
-      drupal_set_message('Successfully Added Database Reference');
+      drupal_set_message(t('Successfully Added Database Reference'));
       drupal_goto('node/' . $nid);
-   }
-   else {
-      drupal_set_message('Database reference NOT successfully created...', 'error');
-   } //end of if dbxref was created successfully
+  }
+  else {
+    drupal_set_message(t('Database reference NOT successfully created...'), 'error');
+  } //end of if dbxref was created successfully
 
 }
 
@@ -157,9 +157,9 @@ function tripal_feature_edit_ALL_dbreferences_page($node) {
   $output = '';
 
   $output .= drupal_get_form('tripal_feature_edit_ALL_db_references_form', $node);
-  $output .= '<br>';
+  $output .= '<br />';
   $output .= drupal_get_form('tripal_feature_add_ONE_dbreference_form', $node);
-  $output .= '<br>';
+  $output .= '<br />';
   $output .= drupal_get_form('tripal_feature_implement_back_to_feature_button', $node->nid);
 
   return $output;
@@ -190,52 +190,52 @@ function tripal_feature_edit_ALL_db_references_form($form_state, $node) {
   ksort($db_options);
 
   if (sizeof($references) != 0) {
-     foreach ($references as $ref) {
-       $i++;
-       $form["num-$i"] = array(
-         '#type' => 'fieldset',
-         '#title' => t("Database Reference") . " $i"
-       );
-
-       $form["num-$i"]["accession-$i"] = array(
-         '#type' => 'textfield',
-         '#title' => t('Accession'),
-         '#size' => 30,
-         '#required' => TRUE,
-         '#default_value' => $ref->accession
-       );
-
-       $form["num-$i"]["db_id-$i"] = array(
-         '#type' => 'select',
-         '#title' => t('Database'),
-         '#options' => $db_options,
-         '#required' => TRUE,
-         '#default_value' => $ref->db_id
-       );
-
-
-       $form["num-$i"]["dbxref_id-$i"] = array(
-         '#type' => 'hidden',
-         '#value' => $ref->dbxref_id
-       );
-
-       $form["num-$i"]["delete-$i"] = array(
-         '#type' => 'submit',
-         '#value' => t("Delete"),
-         '#name' => "delete-$i",
-       );
-
-     }
-
-     $form['num_db_references'] = array(
-       '#type' => 'hidden',
-       '#value' => $i
-     );
-
-     $form["submit-edits"] = array(
-       '#type' => 'submit',
-       '#value' => t('Update All References')
-     );
+    foreach ($references as $ref) {
+      $i++;
+      $form["num-$i"] = array(
+        '#type' => 'fieldset',
+        '#title' => t("Database Reference") . " $i"
+      );
+
+      $form["num-$i"]["accession-$i"] = array(
+        '#type' => 'textfield',
+        '#title' => t('Accession'),
+        '#size' => 30,
+        '#required' => TRUE,
+        '#default_value' => $ref->accession
+      );
+
+      $form["num-$i"]["db_id-$i"] = array(
+        '#type' => 'select',
+        '#title' => t('Database'),
+        '#options' => $db_options,
+        '#required' => TRUE,
+        '#default_value' => $ref->db_id
+      );
+
+
+      $form["num-$i"]["dbxref_id-$i"] = array(
+        '#type' => 'hidden',
+        '#value' => $ref->dbxref_id
+      );
+
+      $form["num-$i"]["delete-$i"] = array(
+        '#type' => 'submit',
+        '#value' => t("Delete"),
+        '#name' => "delete-$i",
+      );
+
+      }
+
+      $form['num_db_references'] = array(
+        '#type' => 'hidden',
+        '#value' => $i
+      );
+
+      $form["submit-edits"] = array(
+        '#type' => 'submit',
+        '#value' => t('Update All References')
+      );
   } //end of foreach db ref
   return $form;
 }
@@ -253,29 +253,29 @@ function tripal_feature_edit_ALL_db_references_form_submit($form, &$form_state)
   $nid = $form_state['values']['nid'];
 
   if (strcmp($action, 'Update All References')==0) {
-     for ($i=1; $i<=$num_refs; $i++) {
-     $dbxref_id = $form_state['values']["dbxref_id-$i"];
-     $db_id = $form_state['values']["db_id-$i"];
-     $accession = $form_state['values']["accession-$i"];
-       tripal_feature_update_db_reference($dbxref_id, $db_id, $accession);
-     }
-     drupal_set_message("Updated all Database References");
-     drupal_goto('node/' . $nid);
+    for ($i=1; $i<=$num_refs; $i++) {
+    $dbxref_id = $form_state['values']["dbxref_id-$i"];
+    $db_id = $form_state['values']["db_id-$i"];
+    $accession = $form_state['values']["accession-$i"];
+      tripal_feature_update_db_reference($dbxref_id, $db_id, $accession);
+    }
+    drupal_set_message(t("Updated all Database References"));
+    drupal_goto('node/' . $nid);
   }
   elseif (strcmp($action, 'Delete')==0) {
-     if (preg_match('/delete-(\d+)/', $button, $matches) ) {
-        $i = $matches[1];
-       $dbxref_id = $form_state['values']["dbxref_id-$i"];
-        tripal_feature_delete_db_reference($dbxref_id);
-        drupal_set_message("Deleted Database Reference");
-        drupal_goto('node/' . $nid);
-     }
-     else {
-        drupal_set_message("Could not remove database reference: ", 'error');
-     }
-  }
+    if (preg_match('/delete-(\d+)/', $button, $matches) ) {
+      $i = $matches[1];
+      $dbxref_id = $form_state['values']["dbxref_id-$i"];
+      tripal_feature_delete_db_reference($dbxref_id);
+      drupal_set_message(t("Deleted Database Reference"));
+      drupal_goto('node/' . $nid);
+    }
+    else {
+      drupal_set_message(t("Could not remove database reference:"), 'error');
+    }
+    }
   else {
-    drupal_set_message("Unrecognized Button Pressed", 'error');
+    drupal_set_message(t("Unrecognized Button Pressed"), 'error');
   }
 
 }
@@ -323,7 +323,7 @@ function tripal_feature_delete_db_reference($dbxref_id) {
 function theme_tripal_feature_edit_ALL_db_references_form($form) {
   $output = '';
 
-  $output .= '<br><fieldset>';
+  $output .= '<br /><fieldset>';
   $output .= '<legend>Edit Existing Database References<span class="form-optional" title="This field is optional">(optional)</span></legend>';
   $output .= '<p>Below is a list of already existing database references, one per line. When entering a database reference, the accession '
          .'is a unique identifier for this feature in the specified database.</p>';
@@ -337,7 +337,7 @@ function theme_tripal_feature_edit_ALL_db_references_form($form) {
          . drupal_render($form["submit-$i"]) . '</td></tr>';
   }
 
-  $output .= '</table><br>';
+  $output .= '</table><br />';
   $output .= drupal_render($form);
   $output .= '</fieldset>';
 

+ 142 - 143
tripal_feature/tripal_feature-delete.inc

@@ -5,167 +5,166 @@
  */
 
 function tripal_feature_delete_form() {
-   // get the list of organisms
-   $sql = "SELECT * FROM {organism} ORDER BY genus, species";
-   $previous_db = tripal_db_set_active('chado');  // use chado database
-   $org_rset = db_query($sql);
-   tripal_db_set_active($previous_db);  // now use drupal database
-   $organisms = array();
-   $organisms[''] = '';
-   while ($organism = db_fetch_object($org_rset)) {
-      $organisms[$organism->organism_id] = "$organism->genus $organism->species ($organism->common_name)";
-   }
-   $form['desc'] = array(
-      '#type' => 'markup',
-      '#value' => t("Use one or more of the following fields to identify sets of features to be deleted."),
-   );
-
-   $form['feature_names']= array(
-      '#type' => 'textarea',
-      '#title' => t('Feature Names'),
-      '#description' => t('Please provide a list of feature names or unique names,
-         separated by spaces or by new lines to be delete. If you specify feature names then
-         all other options below will be ignored (except the unique checkbox).'),
-   );
+  // get the list of organisms
+  $sql = "SELECT * FROM {organism} ORDER BY genus, species";
+  $previous_db = tripal_db_set_active('chado');  // use chado database
+  $org_rset = db_query($sql);
+  tripal_db_set_active($previous_db);  // now use drupal database
+  $organisms = array();
+  $organisms[''] = '';
+  while ($organism = db_fetch_object($org_rset)) {
+    $organisms[$organism->organism_id] = "$organism->genus $organism->species ($organism->common_name)";
+  }
+  $form['desc'] = array(
+    '#type' => 'markup',
+    '#value' => t("Use one or more of the following fields to identify sets of features to be deleted."),
+  );
+
+  $form['feature_names']= array(
+    '#type' => 'textarea',
+    '#title' => t('Feature Names'),
+    '#description' => t('Please provide a list of feature names or unique names,
+       separated by spaces or by new lines to be delete. If you specify feature names then
+       all other options below will be ignored (except the unique checkbox).'),
+  );
   $form['is_unique'] = array(
-      '#title' => t('Names are Unique Names'),
-      '#type' => 'checkbox',
-      '#description' => t('Select this checbox if the names listed in the feature
-        names box above are the unique name of the feature rather than the human readable names.'),
+    '#title' => t('Names are Unique Names'),
+    '#type' => 'checkbox',
+    '#description' => t('Select this checbox if the names listed in the feature
+      names box above are the unique name of the feature rather than the human readable names.'),
+  );
+  $form['seq_type']= array(
+    '#type' => 'textfield',
+    '#title' => t('Sequence Type'),
+    '#description' => t('Please enter the Sequence Ontology term that describes the features to be deleted. Use in conjunction with an organism or anaylysis.'),
+  );
+
+  $form['organism_id'] = array(
+   '#title'       => t('Organism'),
+   '#type'        => t('select'),
+   '#description' => t("Choose the organism for which features will be deleted."),
+   '#options'     => $organisms,
+  );
+
+
+  // get the list of analyses
+  $sql = "SELECT * FROM {analysis} ORDER BY name";
+  $previous_db = tripal_db_set_active('chado');  // use chado database
+  $org_rset = db_query($sql);
+  tripal_db_set_active($previous_db);  // now use drupal database
+  $analyses = array();
+  $analyses[''] = '';
+  while ($analysis = db_fetch_object($org_rset)) {
+    $analyses[$analysis->analysis_id] = "$analysis->name ($analysis->program $analysis->programversion, $analysis->sourcename)";
+  }
+  //  TODO: ADD THIS BACK IN LATER
+  //
+  //   $form['analysis']['analysis_id'] = array (
+  //     '#title'       => t('Analysis'),
+  //     '#type'        => t('select'),
+  //     '#description' => t("Choose the analysis for which associated features will be deleted."),
+  //     '#options'     => $analyses,
+  //   );
+
+  $form['button'] = array(
+    '#type' => 'submit',
+    '#value' => t('Delete Features'),
   );
-   $form['seq_type']= array(
-      '#type' => 'textfield',
-      '#title' => t('Sequence Type'),
-      '#description' => t('Please enter the Sequence Ontology term that describes the features to be deleted. Use in conjunction with an organism or anaylysis.'),
-   );
-
-   $form['organism_id'] = array(
-     '#title'       => t('Organism'),
-     '#type'        => t('select'),
-     '#description' => t("Choose the organism for which features will be deleted."),
-     '#options'     => $organisms,
-   );
-
-
-   // get the list of analyses
-   $sql = "SELECT * FROM {analysis} ORDER BY name";
-   $previous_db = tripal_db_set_active('chado');  // use chado database
-   $org_rset = db_query($sql);
-   tripal_db_set_active($previous_db);  // now use drupal database
-   $analyses = array();
-   $analyses[''] = '';
-   while ($analysis = db_fetch_object($org_rset)) {
-      $analyses[$analysis->analysis_id] = "$analysis->name ($analysis->program $analysis->programversion, $analysis->sourcename)";
-   }
-//  TODO: ADD THIS BACK IN LATER
-//
-//   $form['analysis']['analysis_id'] = array (
-//     '#title'       => t('Analysis'),
-//     '#type'        => t('select'),
-//     '#description' => t("Choose the analysis for which associated features will be deleted."),
-//     '#options'     => $analyses,
-//   );
-
-   $form['button'] = array(
-      '#type' => 'submit',
-      '#value' => t('Delete Features'),
-   );
-   return $form;
+  return $form;
 }
 
 function tripal_feature_delete_form_validate($form, &$form_state) {
-   $organism_id   = $form_state['values']['organism_id'];
-   $seq_type      = trim($form_state['values']['seq_type']);
-   $analysis_id   = $form_state['values']['analysis_id'];
-   $is_unique     = $form_state['values']['is_unique'];
-   $feature_names = $form_state['values']['feature_names'];
-
-   if (!$organism_id and !$anaysis_id and !$seq_type and !$feature_names) {
-      form_set_error('feature_names', t("Please select at least one option"));
-   }
-
-   // check to make sure the types exists
-   if ($seq_type) {
-      $cvtermsql = "SELECT CVT.cvterm_id
-                    FROM {cvterm} CVT
-                       INNER JOIN {cv} CV on CVT.cv_id = CV.cv_id
-                       LEFT JOIN {cvtermsynonym} CVTS on CVTS.cvterm_id = CVT.cvterm_id
-                    WHERE cv.name = '%s' and (CVT.name = '%s' or CVTS.synonym = '%s')";
-      $cvterm = db_fetch_object(db_query($cvtermsql, 'sequence', $seq_type, $seq_type));
-      if (!$cvterm) {
-         form_set_error('seq_type', t("The Sequence Ontology (SO) term selected for the sequence type is not available in the database. Please check spelling or select another."));
-      }
-   }
+  $organism_id   = $form_state['values']['organism_id'];
+  $seq_type      = trim($form_state['values']['seq_type']);
+  $analysis_id   = $form_state['values']['analysis_id'];
+  $is_unique     = $form_state['values']['is_unique'];
+  $feature_names = $form_state['values']['feature_names'];
+
+  if (!$organism_id and !$anaysis_id and !$seq_type and !$feature_names) {
+    form_set_error('feature_names', t("Please select at least one option"));
+  }
+
+  // check to make sure the types exists
+  if ($seq_type) {
+    $cvtermsql = "SELECT CVT.cvterm_id
+                  FROM {cvterm} CVT
+                     INNER JOIN {cv} CV on CVT.cv_id = CV.cv_id
+                     LEFT JOIN {cvtermsynonym} CVTS on CVTS.cvterm_id = CVT.cvterm_id
+                  WHERE cv.name = '%s' and (CVT.name = '%s' or CVTS.synonym = '%s')";
+    $cvterm = db_fetch_object(db_query($cvtermsql, 'sequence', $seq_type, $seq_type));
+    if (!$cvterm) {
+      form_set_error('seq_type', t("The Sequence Ontology (SO) term selected for the sequence type is not available in the database. Please check spelling or select another."));
+    }
+  }
 }
 
 function tripal_feature_delete_form_submit($form, &$form_state) {
-   global $user;
+  global $user;
 
-   $organism_id   = $form_state['values']['organism_id'];
-   $seq_type      = trim($form_state['values']['seq_type']);
-   $analysis_id   = $form_state['values']['analysis_id'];
-   $is_unique     = $form_state['values']['is_unique'];
-   $feature_names = $form_state['values']['feature_names'];
+  $organism_id   = $form_state['values']['organism_id'];
+  $seq_type      = trim($form_state['values']['seq_type']);
+  $analysis_id   = $form_state['values']['analysis_id'];
+  $is_unique     = $form_state['values']['is_unique'];
+  $feature_names = $form_state['values']['feature_names'];
 
-   $args = array($organism_id, $analysis_id, $seq_type, $is_unique, $feature_names);
+  $args = array($organism_id, $analysis_id, $seq_type, $is_unique, $feature_names);
 
-   tripal_add_job("Delete features", 'tripal_feature',
-      'tripal_feature_delete_features', $args, $user->uid);
+  tripal_add_job("Delete features", 'tripal_feature',
+    'tripal_feature_delete_features', $args, $user->uid);
 }
 
 
 function tripal_feature_delete_features($organism_id, $analysis_id, $seq_type,
-   $is_unique, $feature_names, $job = NULL) {
-
-   global $user;
-   $match = array();
-
-   // if feature names have been provided then handle that separately
-   if ($feature_names) {
-      $names = preg_split('/\s+/', $feature_names);
-      if (sizeof($names) == 1) {
-         $names = $names[0];
-      }
-      if ($is_unique) {
-         $match['uniquename'] = $names;
-      }
-      else {
-         $match['name'] = $names;
-      }
-      $num_deletes = tripal_core_chado_select('feature', array('count(*) as cnt'), $match);
-      print "Deleting " . $num_deletes[0]->cnt . " features\n";
-      tripal_core_chado_delete('feature', $match);
-   }
-
-   // if the user has provided an analysis_id then handle that separately
-   elseif ($analysis_id) {
-      tripal_feature_delete_by_analysis();
-   }
-   else {
-
-
-      if ($organism_id) {
-         $match['organism_id'] = $organism_id;
-      }
-      if ($seq_type) {
-         $match['type_id'] = array(
-            'name' => $seq_type,
-            'cv_id' => array(
-               'name' => 'sequence'
-            ),
-         );
-      }
-      $num_deletes = tripal_core_chado_select('feature', array('count(*) as cnt'), $match);
-      print "Deleting " . $num_deletes[0]->cnt . " features\n";
-      tripal_core_chado_delete('feature', $match);
-   }
-
-   print "Removing orphaned feature pages\n";
-   tripal_features_cleanup(array(), $user->uid);
+  $is_unique, $feature_names, $job = NULL) {
+
+  global $user;
+  $match = array();
+
+  // if feature names have been provided then handle that separately
+  if ($feature_names) {
+    $names = preg_split('/\s+/', $feature_names);
+    if (sizeof($names) == 1) {
+      $names = $names[0];
+    }
+    if ($is_unique) {
+      $match['uniquename'] = $names;
+    }
+    else {
+      $match['name'] = $names;
+    }
+    $num_deletes = tripal_core_chado_select('feature', array('count(*) as cnt'), $match);
+    print "Deleting " . $num_deletes[0]->cnt . " features\n";
+    tripal_core_chado_delete('feature', $match);
+  }
+
+  // if the user has provided an analysis_id then handle that separately
+  elseif ($analysis_id) {
+    tripal_feature_delete_by_analysis();
+  }
+  else {
+
+    if ($organism_id) {
+      $match['organism_id'] = $organism_id;
+    }
+    if ($seq_type) {
+      $match['type_id'] = array(
+        'name' => $seq_type,
+        'cv_id' => array(
+          'name' => 'sequence'
+        ),
+      );
+    }
+    $num_deletes = tripal_core_chado_select('feature', array('count(*) as cnt'), $match);
+    print "Deleting " . $num_deletes[0]->cnt . " features\n";
+    tripal_core_chado_delete('feature', $match);
+  }
+
+  print "Removing orphaned feature pages\n";
+  tripal_features_cleanup(array(), $user->uid);
 }
 
 function tripal_feature_delete_by_analysis($organism_id, $analysis_id, $seq_type,
-   $is_unique, $feature_names, $job = NULL) {
+  $is_unique, $feature_names, $job = NULL) {
 
 }
 

+ 79 - 79
tripal_feature/tripal_feature-properties.inc

@@ -101,19 +101,19 @@ function tripal_feature_add_ONE_property_form($form_state, $node, $expand) {
  */
 function tripal_feature_add_ONE_property_form_validate($form, &$form_state) {
 
-   // Only Require if Adding Property
-   if ($form_state['clicked_button']['#value'] == t('Add Property') ) {
+  // Only Require if Adding Property
+  if ($form_state['clicked_button']['#value'] == t('Add Property') ) {
 
-      // Check that there is a feature
-      if ( $form_state['values']['feature_id'] <= 0 ) {
-         form_set_error('feature_id', 'There is no associated feature.');
-      }
+    // Check that there is a feature
+    if ( $form_state['values']['feature_id'] <= 0 ) {
+      form_set_error('feature_id', 'There is no associated feature.');
+    }
 
-      // Check that Selected a type
-      if ( !$form_state['values']['property']) {
-         form_set_error('property', 'Please select a type of property.');
-      }
-   }
+    // Check that Selected a type
+    if ( !$form_state['values']['property']) {
+      form_set_error('property', 'Please select a type of property.');
+    }
+  }
 }
 
 /**
@@ -122,18 +122,18 @@ function tripal_feature_add_ONE_property_form_validate($form, &$form_state) {
  * @ingroup tripal_feature
  */
 function tripal_feature_add_ONE_property_form_submit($form, &$form_state) {
-   $feature_id = $form_state['values']['feature_id'];
-   $property = $form_state['values']['property'];
-   $value = $form_state['values']['prop_value'];
-   $cv_name = $form_state['values']['cv_name'];
-
-   $succes = tripal_feature_insert_property($feature_id, $property, $value, 0, $cv_name);
-   if ($succes) {
-      drupal_set_message(t("Successfully Added Property: %property => %value", array('%property' => $property), array('%value' => $value)));
-   }
-   else {
-      drupal_set_message(t("Failed to Add Property: %property => %value", array('%property' => $property), array('%value' => $value)));
-   }
+  $feature_id = $form_state['values']['feature_id'];
+  $property = $form_state['values']['property'];
+  $value = $form_state['values']['prop_value'];
+  $cv_name = $form_state['values']['cv_name'];
+
+  $succes = tripal_feature_insert_property($feature_id, $property, $value, 0, $cv_name);
+  if ($succes) {
+    drupal_set_message(t("Successfully Added Property: %property => %value", array('%property' => $property), array('%value' => $value)));
+  }
+  else {
+    drupal_set_message(t("Failed to Add Property: %property => %value", array('%property' => $property), array('%value' => $value)));
+  }
 }
 
 /**
@@ -170,9 +170,9 @@ function tripal_feature_edit_ALL_properties_form($form_state, $node, $properties
     $prop_type_options = array();
     $columns = array('cvterm_id', 'name');
     $values = array(
-       'cv_id' => array(
-          'name' => $form['cv_name']['#value']
-       )
+      'cv_id' => array(
+        'name' => $form['cv_name']['#value']
+      )
     );
     $results = tripal_core_chado_select('cvterm', $columns, $values);
     foreach ($results as $r) {
@@ -180,30 +180,30 @@ function tripal_feature_edit_ALL_properties_form($form_state, $node, $properties
     }
 
     // iterate through all of the properties and create a set of form elements
-    foreach ($properties as $i => $property) {
-       $form["num-$i"] = array(
-          '#type' => 'fieldset',
-          '#value' => "Property $i"
-       );
-       $form["num-$i"]["id-$i"] = array(
-          '#type' => 'hidden',
-          '#value' => $property->featureprop_id
-       );
-       $default = array_search($property->type, $prop_type_options);
-       $form["num-$i"]["type-$i"] = array(
-          '#type' => 'select',
-          '#options' => $prop_type_options,
-          '#default_value' => $property->type_id->name
-       );
-       $form["num-$i"]["value-$i"] = array(
-          '#type' => 'textfield',
-          '#default_value' => $property->value
-       );
-       $form["num-$i"]["delete-$i"] = array(
-          '#type' => 'submit',
-          '#value' => t("Delete"),
-         '#name' => "delete-$i",
-       );
+  foreach ($properties as $i => $property) {
+    $form["num-$i"] = array(
+      '#type' => 'fieldset',
+      '#value' => "Property $i"
+    );
+    $form["num-$i"]["id-$i"] = array(
+      '#type' => 'hidden',
+      '#value' => $property->featureprop_id
+    );
+    $default = array_search($property->type, $prop_type_options);
+    $form["num-$i"]["type-$i"] = array(
+      '#type' => 'select',
+      '#options' => $prop_type_options,
+      '#default_value' => $property->type_id->name
+    );
+    $form["num-$i"]["value-$i"] = array(
+      '#type' => 'textfield',
+      '#default_value' => $property->value
+    );
+    $form["num-$i"]["delete-$i"] = array(
+      '#type' => 'submit',
+      '#value' => t("Delete"),
+      '#name' => "delete-$i",
+    );
     } //end of foreach property
 
     $form['num_properties'] = array(
@@ -233,38 +233,38 @@ function tripal_feature_edit_ALL_properties_form_submit($form, &$form_state) {
 
   // if the update button was clicked then do the update
   if ($form_state['clicked_button']['#value'] == t('Update All Properties') ) {
-     // iterate through each of the properties and set each one
-     for ($i=1; $i<=$form_state['values']['num_properties']; $i++) {
-       $featureprop_id = $form_state['values']["id-$i"];
-       $property = $form_state['values']["type-$i"];
-       $value = $form_state['values']["value-$i"];
-       $success = tripal_feature_update_property_by_id($featureprop_id, $property, $value, $cv_name);
-       if (!$success) {
-          drupal_set_message(t("Failed to Update Property: %property => %value", array('%property' => $property), array('%value' => $value)));
-          $all_good = 0;
-       }
-     }
-     if ($all_good) {
-        drupal_set_message("Updated all Properties");
-     }
-     drupal_goto('node/' . $form_state['values']['nid']);
+    // iterate through each of the properties and set each one
+    for ($i=1; $i<=$form_state['values']['num_properties']; $i++) {
+      $featureprop_id = $form_state['values']["id-$i"];
+      $property = $form_state['values']["type-$i"];
+      $value = $form_state['values']["value-$i"];
+      $success = tripal_feature_update_property_by_id($featureprop_id, $property, $value, $cv_name);
+      if (!$success) {
+        drupal_set_message(t("Failed to Update Property: %property => %value", array('%property' => $property), array('%value' => $value)));
+        $all_good = 0;
+      }
+    }
+    if ($all_good) {
+      drupal_set_message(t("Updated all Properties"));
+    }
+    drupal_goto('node/' . $form_state['values']['nid']);
   }
   // if the delete button was clicked then remove the property
   elseif (preg_match('/delete-(\d+)/', $form_state['clicked_button']['#name'], $matches) ) {
-     $i = $matches[1];
-     $featureprop_id = $form_state['values']["id-$i"];
-     $property = $form_state['values']["type-$i"];
-     $value = $form_state['values']["value-$i"];
-     $success = tripal_feature_delete_property_by_id($featureprop_id);
-     if ($success) {
-        drupal_set_message("Deleted Property");
-     }
-     else {
-        drupal_set_message("Unable to Delete Property");
-     }
+    $i = $matches[1];
+    $featureprop_id = $form_state['values']["id-$i"];
+    $property = $form_state['values']["type-$i"];
+    $value = $form_state['values']["value-$i"];
+    $success = tripal_feature_delete_property_by_id($featureprop_id);
+    if ($success) {
+      drupal_set_message(t("Deleted Property"));
+    }
+    else {
+      drupal_set_message(t("Unable to Delete Property"));
+    }
   }
   else {
-    drupal_set_message("Unrecognized Button Pressed", 'error');
+    drupal_set_message(t("Unrecognized Button Pressed"), 'error');
   }
 }
 /**
@@ -275,7 +275,7 @@ function tripal_feature_edit_ALL_properties_form_submit($form, &$form_state) {
 function theme_tripal_feature_edit_ALL_properties_form($form) {
   $output = '';
 
-  $output .= '<br><fieldset>';
+  $output .= '<br /><fieldset>';
   $output .= '<legend>Edit Already Existing Properties<span class="form-optional" title="This field is optional">(optional)</span></legend>';
   $output .= '<p>Below is a list of already existing properties for this feature, one property per line. The type refers to the type of '
          .'property and the value is the value for that property. </p>';
@@ -289,7 +289,7 @@ function theme_tripal_feature_edit_ALL_properties_form($form) {
     }
   }
 
-  $output .= '</table><br>';
+  $output .= '</table><br />';
   $output .= drupal_render($form);
   $output .= '</fieldset>';
 

+ 110 - 112
tripal_feature/tripal_feature-relationships.inc

@@ -12,13 +12,13 @@
 function tripal_feature_add_ALL_relationships_page($node) {
   $output = '';
 
-  $output .= tripal_feature_implement_add_chado_properties_progress('relationships') . '<br>';
-  $output .= '<b>All Relationships should include the CURRENT Individual (' . $node->uniquename . ')</b><br>';
-  $output .= '<br><b>Current Relationships</b><br>';
+  $output .= tripal_feature_implement_add_chado_properties_progress('relationships') . '<br />';
+  $output .= '<b>All Relationships should include the CURRENT Individual (' . $node->uniquename . ')</b><br />';
+  $output .= '<br /><b>Current Relationships</b><br />';
   $output .= list_relationships_for_node($node->uniquename, $node->subject_relationships, $node->object_relationships);
-  $output .= '<br><br>';
+  $output .= '<br /><br />';
   $output .= drupal_get_form('tripal_feature_add_ONE_relationship_form', $node);
-  $output .= '<br>';
+  $output .= '<br />';
   $output .= drupal_get_form('tripal_feature_implement_add_chado_properties_navigate', 'relationships', $node->nid);
   return $output;
 }
@@ -120,13 +120,13 @@ function tripal_feature_add_ONE_relationship_form_validate($form, &$form_state)
       for ($i=0; $i<sizeof($subject_results); $i++) {
       $links[] = l($i+1, "node/" . $subject_results[$i]->nid); }
       $message = "Too many stocks match '" . $form_state['values']['subject_id'] . "'! "
-                  . " Please refine your input to match ONLY ONE stock. <br>"
+                  . " Please refine your input to match ONLY ONE stock. <br />"
      . "To aid in this process, here are the stocks that match your initial input: "
      . join(', ', $links);
       form_set_error('subject_id', $message);
     }
     elseif (sizeof($subject_results) < 1) {
-      form_set_error('subject_id', "There are no stocks matching your input. Please check your input for typos and/or lookup the stock " . l('here', 'stocks'));
+      form_set_error('subject_id', t("There are no stocks matching your input. Please check your input for typos and/or lookup the stock %link", array('%link' => l(t('here'), 'stocks'))));
     }
     elseif (sizeof($subject_results) == 1) {
       $form_state['values']['subject_id'] = $subject_results[0]->stock_id;
@@ -141,13 +141,13 @@ function tripal_feature_add_ONE_relationship_form_validate($form, &$form_state)
       for ($i=0; $i<sizeof($object_results); $i++) {
       $links[] = l($i+1, "node/" . $object_results[$i]->nid); }
       $message = "Too many stocks match '" . $form_state['values']['object_id'] . "'! "
-                 . "Please refine your input to match ONLY ONE stock. <br>"
+                 . "Please refine your input to match ONLY ONE stock. <br />"
                  . "To aid in this process, here are the stocks that match your initial input: "
                  . join(', ', $links);
       form_set_error('object_id', $message);
     }
     elseif (sizeof($object_results) < 1) {
-      form_set_error('object_id', "There are no stocks matching your input. Please check your input for typos and/or lookup the stock " . l('here', 'stocks'));
+      form_set_error('object_id', t("There are no stocks matching your input. Please check your input for typos and/or lookup the stock %link", array('%link' => l(t('here'), 'stocks'))));
     }
     elseif (sizeof($object_results) == 1) {
       $form_state['values']['object_id'] = $object_results[0]->stock_id;
@@ -194,7 +194,7 @@ function tripal_feature_add_ONE_relationship_form_submit($form, &$form_state) {
     );
     db_set_active($previous_db);
 
-    drupal_set_message('Successfully Added Relationship.');
+    drupal_set_message(t('Successfully Added Relationship.'));
   } //end of insert relationship
 
 }
@@ -208,9 +208,9 @@ function tripal_feature_edit_ALL_relationships_page($node) {
   $output = '';
 
   $output .= drupal_get_form('tripal_feature_edit_ALL_relationships_form', $node);
-  $output .= '<br>';
+  $output .= '<br />';
   $output .= drupal_get_form('tripal_feature_add_ONE_relationship_form', $node);
-  $output .= '<br>';
+  $output .= '<br />';
   $output .= drupal_get_form('tripal_feature_implement_back_to_feature_button', $node->nid);
 
   return $output;
@@ -243,93 +243,91 @@ function tripal_feature_edit_ALL_relationships_form($form_state, $node) {
   $relationships = array_merge($orelationships, $srelationships);
 
   if (sizeof($relationships) != 0) {
-     foreach ($relationships as $r) {
-
-       $i++;
-       $form["num-$i"] = array(
-         '#type' => 'fieldset',
-         '#title' => t("Relationship %i", array('%i' => $i)),
-       );
-
-       $form["num-$i"]["id-$i"] = array(
-         '#type' => 'hidden',
-         '#value' => $r->stock_relationship_id
-       );
-
-       //Enter relationship specific fields
-       if ( !empty($r->subject_id) ) {
-         $default = $r->subject_uniquename;
-         $description = l($r->subject_name, 'node/' . $r->subject_nid);
-       }
-       else {
-          $default = $node->uniquename;
-          $description = "Current Feature";
-       }
-       $description .= " (" . $r->subject_type . ")";
-       $form["num-$i"]["subject_id-$i"] = array(
-         '#type' => 'textfield',
-         //'#title' => t('Subject'),
-         '#required'   => TRUE,
-         '#size' => 30,
-         '#default_value' => $default,
-         '#description' => t('%description', array('%description' => $description)),
-       );
-
-       $cv = tripal_cv_get_cv_by_name('relationship');
-       $type_options = tripal_cv_get_cvterm_options($cv->cv_id);
-       ksort($type_options);
-       $form["num-$i"]["type_id-$i"] = array(
-         '#type' => 'select',
-         //'#title' => t('Type of Relationship'),
-         '#options' => $type_options,
-         '#required' => TRUE,
-         '#default_value' => $r->relationship_type_id
-       );
-
-       if (!empty($r->object_id) ) {
-         $default = $r->object_uniquename;
-         $description = l($r->object_name, 'node/' . $r->object_nid);
-       }
-       else {
-         $default = $node->uniquename;
-         $description = 'Current Feature';
-       }
-       $description .= " (" . $r->object_type . ")";
-       $form["num-$i"]["object_id-$i"] = array(
-         '#type' => 'textfield',
-         //'#title' => t('Object'),
-         '#required'   => TRUE,
-         '#size' => 30,
-         '#default_value' => $default,
-         '#description' => $description
-       );
-
-       $form["num-$i"]["delete-$i"] = array(
-         '#type' => 'submit',
-         '#value' => t("Delete"),
-         '#name' => "delete-$i",
-       );
-
-     } //end of foreach relationship
-     $form['num_relationships'] = array(
-       '#type' => 'hidden',
-       '#value' => $i
-     );
-
-     $form["submit-edits"] = array(
-       '#type' => 'submit',
-       '#value' => t('Update All Relationships')
-     );
+    foreach ($relationships as $r) {
+
+      $i++;
+      $form["num-$i"] = array(
+        '#type' => 'fieldset',
+        '#title' => t("Relationship %i", array('%i' => $i)),
+      );
+
+      $form["num-$i"]["id-$i"] = array(
+        '#type' => 'hidden',
+        '#value' => $r->stock_relationship_id
+      );
+
+      //Enter relationship specific fields
+      if ( !empty($r->subject_id) ) {
+        $default = $r->subject_uniquename;
+        $description = l($r->subject_name, 'node/' . $r->subject_nid);
+      }
+      else {
+        $default = $node->uniquename;
+        $description = "Current Feature";
+      }
+      $description .= " (" . $r->subject_type . ")";
+      $form["num-$i"]["subject_id-$i"] = array(
+        '#type' => 'textfield',
+        //'#title' => t('Subject'),
+        '#required'   => TRUE,
+        '#size' => 30,
+        '#default_value' => $default,
+        '#description' => t('%description', array('%description' => $description)),
+      );
+
+      $cv = tripal_cv_get_cv_by_name('relationship');
+      $type_options = tripal_cv_get_cvterm_options($cv->cv_id);
+      ksort($type_options);
+      $form["num-$i"]["type_id-$i"] = array(
+        '#type' => 'select',
+        //'#title' => t('Type of Relationship'),
+        '#options' => $type_options,
+        '#required' => TRUE,
+        '#default_value' => $r->relationship_type_id
+      );
+
+      if (!empty($r->object_id) ) {
+        $default = $r->object_uniquename;
+        $description = l($r->object_name, 'node/' . $r->object_nid);
+      }
+      else {
+        $default = $node->uniquename;
+        $description = 'Current Feature';
+      }
+      $description .= " (" . $r->object_type . ")";
+      $form["num-$i"]["object_id-$i"] = array(
+        '#type' => 'textfield',
+        //'#title' => t('Object'),
+        '#required'   => TRUE,
+        '#size' => 30,
+        '#default_value' => $default,
+        '#description' => $description
+      );
+
+      $form["num-$i"]["delete-$i"] = array(
+        '#type' => 'submit',
+        '#value' => t("Delete"),
+        '#name' => "delete-$i",
+      );
+
+    } //end of foreach relationship
+    $form['num_relationships'] = array(
+      '#type' => 'hidden',
+      '#value' => $i
+    );
+
+    $form["submit-edits"] = array(
+      '#type' => 'submit',
+      '#value' => t('Update All Relationships')
+    );
   }
   else {
-     $form["info"] = array(
-       '#type' => 'markup',
-       '#value' => t('No relationships currently exist for this feature.')
-     );
+    $form["info"] = array(
+      '#type' => 'markup',
+      '#value' => t('No relationships currently exist for this feature.')
+    );
   }
 
-
-
   return $form;
 }
 
@@ -354,13 +352,13 @@ function tripal_feature_edit_ALL_relationships_form_validate($form, &$form_state
         for ($j=0; $j<sizeof($subject_results); $j++) {
         $links[] = l($j+1, "node/" . $subject_results[$j]->nid); }
         $message = "Too many stocks match '" . $form_state['values']["subject_id-$i"] . "'! "
-                 . "Please refine your input to match ONLY ONE stock. <br>"
+                 . "Please refine your input to match ONLY ONE stock. <br />"
                  . "To aid in this process, here are the stocks that match your initial input: "
                  . join(', ', $links);
         form_set_error("subject_id-$i", $message);
       }
       elseif (sizeof($subject_results) < 1) {
-        form_set_error("subject_id-$i", "There are no stocks matching your input. Please check your input for typos and/or lookup the stock " . l('here', 'stocks'));
+        form_set_error("subject_id-$i", t("There are no stocks matching your input. Please check your input for typos and/or lookup the stock %link", array('%link' => l(t('here'), 'stocks'))));
       }
       elseif (sizeof($subject_results) == 1) {
         $form_state['values']["subject_id-$i"] = $subject_results[0]->stock_id;
@@ -375,13 +373,13 @@ function tripal_feature_edit_ALL_relationships_form_validate($form, &$form_state
         for ($j=0; $j<sizeof($object_results); $j++) {
         $links[] = l($j+1, "node/" . $object_results[$j]->nid); }
         $message = "Too many stocks match '" . $form_state['values']["object_id-$i"] . "'! "
-                 . "Please refine your input to match ONLY ONE stock. <br>"
+                 . "Please refine your input to match ONLY ONE stock. <br />"
                  . "To aid in this process, here are the stocks that match your initial input: "
                  . join(', ', $links);
         form_set_error("object_id-$i", $message);
       }
       elseif (sizeof($object_results) < 1) {
-        form_set_error("object_id-$i", "There are no stocks matching your input. Please check your input for typos and/or lookup the stock " . l('here', 'stocks'));
+        form_set_error("object_id-$i", t("There are no stocks matching your input. Please check your input for typos and/or lookup the stock %link", array('%link' => l(t('here'), 'stocks'))));
       }
       elseif (sizeof($object_results) == 1) {
         $form_state['values']["object_id-$i"] = $object_results[0]->stock_id;
@@ -421,33 +419,33 @@ function tripal_feature_edit_ALL_relationships_form_validate($form, &$form_state
 function tripal_feature_edit_ALL_relationships_form_submit($form, &$form_state) {
 
   if ($form_state['clicked_button']['#value'] == t('Update Relationships') ) {
-     //Update all
-     for ($i=1; $i<=$form_state['values']['num_relationships']; $i++) {
+    //Update all
+    for ($i=1; $i<=$form_state['values']['num_relationships']; $i++) {
 
-       //process stock textfields
-       tripal_feature_update_relationship(
+      //process stock textfields
+      tripal_feature_update_relationship(
         $form_state['values']["id-$i"],
         $form_state['values']["subject_id-$i"],
         $form_state['values']["type_id-$i"],
         $form_state['values']["object_id-$i"]
       );
-     }
-     drupal_set_message("Updated all Relationships");
-     drupal_goto('node/' . $form_state['values']['nid']);
+    }
+    drupal_set_message(t("Updated all Relationships"));
+    drupal_goto('node/' . $form_state['values']['nid']);
 
   }
   elseif ( preg_match('/Delete #(\d+)/', $form_state['clicked_button']['#value'], $matches) ) {
 
-     $i = $matches[1];
-     tripal_feature_delete_relationship($form_state['values']["id-$i"]);
-     drupal_set_message("Deleted Relationship");
+    $i = $matches[1];
+    tripal_feature_delete_relationship($form_state['values']["id-$i"]);
+    drupal_set_message(t("Deleted Relationship"));
 
   }
   elseif ($form_state['clicked_button']['#value'] == t('Back to Stock') ) {
     drupal_goto('node/' . $form_state['values']['nid']);
   }
   else {
-    drupal_set_message("Unrecognized Button Pressed", 'error');
+    drupal_set_message(t("Unrecognized Button Pressed"), 'error');
   }
 
 }
@@ -495,7 +493,7 @@ function tripal_feature_delete_relationship($stock_relationship_id) {
 function theme_tripal_feature_edit_ALL_relationships_form($form) {
   $output = '';
 
-  $output .= '<br><fieldset>';
+  $output .= '<br /><fieldset>';
   $output .= '<legend>Edit Already Existing Relationships<span class="form-optional" title="This field is optional">(optional)</span></legend>';
   $output .= '<p>Each relationship for this stock is listed below, one per line. The textboxes indicating '
         .'the subject and object of the relationship can contain the uniquename, name, database '
@@ -511,7 +509,7 @@ function theme_tripal_feature_edit_ALL_relationships_form($form) {
               '<td>' . drupal_render($form["submit-$i"]) . '</td></tr>';
   }
 
-  $output .= '</table><br>';
+  $output .= '</table><br />';
   $output .= drupal_render($form);
   $output .= '</fieldset>';
 

Tiedoston diff-näkymää rajattu, sillä se on liian suuri
+ 461 - 462
tripal_feature/tripal_feature.admin.inc


+ 99 - 99
tripal_feature/tripal_feature.api.inc

@@ -225,13 +225,13 @@ function tripal_feature_chado_feature_cvterm_schema() {
           'pub_id' => 'pub_id',
         ),
   );
-  
+
   return $description;
 }
 /**
-*
-* @ingroup tripal_schema_api
-*/
+ *
+ * @ingroup tripal_schema_api
+ */
 function tripal_feature_chado_feature_synonym_schema() {
   $description = array();
 
@@ -286,26 +286,26 @@ function tripal_feature_chado_feature_synonym_schema() {
  * @ingroup tripal_feature_api
  */
 function tripal_feature_analysis_get_property($analysis_id = NULL, $feature_id = NUll,
-   $analysisfeature_id = NULL, $property, $cv_name = 'tripal') {
-
-   // check that the incoming arguments are correct
-   if (($analysis_id and !$feature_id) or
-       (!$analysis_id and $feature_id)) {
-       watchdog('tripal_feature',
-          'tripal_feature_analysis_get_property: Both an analysis ID and feature ID should be specified',
-           array(), WATCHDOG_WARNING);
-   }
-
-   // get the analysisfeature_id if one is not provided
-   if (!$analysisfeature_id) {
-      $columns = array('analysisfeature_id');
-      $values = array('analysis_id' => $analysis_id, 'feature_id' => $feature_id);
-      $result = tripal_core_chado_select('analysisfeature', $columns, $values);
-      $analysisfeature_id = $result[0]->analysisfeature_id;
-   }
-
-   // get the property.
-   return tripal_core_get_property('analysisfeature', $analysisfeature_id, $property, $cv_name);
+  $analysisfeature_id = NULL, $property, $cv_name = 'tripal') {
+
+  // check that the incoming arguments are correct
+  if (($analysis_id and !$feature_id) or
+    (!$analysis_id and $feature_id)) {
+      watchdog('tripal_feature',
+      'tripal_feature_analysis_get_property: Both an analysis ID and feature ID should be specified',
+      array(), WATCHDOG_WARNING);
+  }
+
+  // get the analysisfeature_id if one is not provided
+  if (!$analysisfeature_id) {
+    $columns = array('analysisfeature_id');
+    $values = array('analysis_id' => $analysis_id, 'feature_id' => $feature_id);
+    $result = tripal_core_chado_select('analysisfeature', $columns, $values);
+    $analysisfeature_id = $result[0]->analysisfeature_id;
+  }
+
+  // get the property.
+  return tripal_core_get_property('analysisfeature', $analysisfeature_id, $property, $cv_name);
 }
 
 /**
@@ -339,28 +339,28 @@ function tripal_feature_analysis_get_property($analysis_id = NULL, $feature_id =
  * @ingroup tripal_feature_api
  */
 function tripal_feature_analysis_insert_property($analysis_id = NULL, $feature_id = NUll,
-   $analysisfeature_id = NULL, $property, $value, $update_if_present = 0,
-   $cv_name = 'tripal') {
-
-   // check that the incoming arguments are correct
-   if (($analysis_id and !$feature_id) or
-       (!$analysis_id and $feature_id)) {
-       watchdog('tripal_feature',
-          'tripal_feature_analysis_insert_property: Both an analysis ID and feature ID should be specified',
-           array(), WATCHDOG_WARNING);
-   }
-
-   // get the analysisfeature_id if one is not provided
-   if (!$analysisfeature_id) {
-      $columns = array('analysisfeature_id');
-      $values = array('analysis_id' => $analysis_id, 'feature_id' => $feature_id);
-      $result = tripal_core_chado_select('analysisfeature', $columns, $values);
-      $analysisfeature_id = $result[0]->analysisfeature_id;
-   }
-
-   // insert the property.
-   return tripal_core_insert_property('analysisfeature', $analysisfeature_id,
-      $property, $cv_name, $value, $update_if_present);
+  $analysisfeature_id = NULL, $property, $value, $update_if_present = 0,
+  $cv_name = 'tripal') {
+
+  // check that the incoming arguments are correct
+  if (($analysis_id and !$feature_id) or
+    (!$analysis_id and $feature_id)) {
+    watchdog('tripal_feature',
+      'tripal_feature_analysis_insert_property: Both an analysis ID and feature ID should be specified',
+      array(), WATCHDOG_WARNING);
+  }
+
+  // get the analysisfeature_id if one is not provided
+  if (!$analysisfeature_id) {
+    $columns = array('analysisfeature_id');
+    $values = array('analysis_id' => $analysis_id, 'feature_id' => $feature_id);
+    $result = tripal_core_chado_select('analysisfeature', $columns, $values);
+    $analysisfeature_id = $result[0]->analysisfeature_id;
+  }
+
+  // insert the property.
+  return tripal_core_insert_property('analysisfeature', $analysisfeature_id,
+    $property, $cv_name, $value, $update_if_present);
 }
 
 /**
@@ -400,27 +400,27 @@ function tripal_feature_analysis_insert_property($analysis_id = NULL, $feature_i
  * @ingroup tripal_feature_api
  */
 function tripal_feature_analysis_update_property($analysis_id = NULL, $feature_id = NUll,
-   $analysisfeature_id = NULL, $property, $value, $insert_if_missing = 0,
-   $cv_name = 'tripal') {
-
-   // check that the incoming arguments are correct
-   if (($analysis_id and !$feature_id) or
-       (!$analysis_id and $feature_id)) {
-       watchdog('tripal_feature',
-          'tripal_feature_analysis_update_property: Both an analysis ID and feature ID should be specified',
-           array(), WATCHDOG_WARNING);
-   }
-
-   // get the analysisfeature_id if one is not provided
-   if (!$analysisfeature_id) {
-      $columns = array('analysisfeature_id');
-      $values = array('analysis_id' => $analysis_id, 'feature_id' => $feature_id);
-      $result = tripal_core_chado_select('analysisfeature', $columns, $values);
-      $analysisfeature_id = $result[0]->analysisfeature_id;
-   }
-
-   // update the property.
-   return tripal_core_update_property('analysisfeature', $analysisfeature_id, $property, $cv_name, $value, $insert_if_missing);
+  $analysisfeature_id = NULL, $property, $value, $insert_if_missing = 0,
+  $cv_name = 'tripal') {
+
+  // check that the incoming arguments are correct
+  if (($analysis_id and !$feature_id) or
+    (!$analysis_id and $feature_id)) {
+      watchdog('tripal_feature',
+      'tripal_feature_analysis_update_property: Both an analysis ID and feature ID should be specified',
+      array(), WATCHDOG_WARNING);
+  }
+
+  // get the analysisfeature_id if one is not provided
+  if (!$analysisfeature_id) {
+    $columns = array('analysisfeature_id');
+    $values = array('analysis_id' => $analysis_id, 'feature_id' => $feature_id);
+    $result = tripal_core_chado_select('analysisfeature', $columns, $values);
+    $analysisfeature_id = $result[0]->analysisfeature_id;
+  }
+
+  // update the property.
+  return tripal_core_update_property('analysisfeature', $analysisfeature_id, $property, $cv_name, $value, $insert_if_missing);
 }
 
 /**
@@ -442,10 +442,10 @@ function tripal_feature_analysis_update_property($analysis_id = NULL, $feature_i
  * @ingroup tripal_feature_api
  */
 function tripal_feature_analysis_update_property_by_id($analysisfeatureprop_id,
-   $property, $value, $cv_name = 'tripal') {
+  $property, $value, $cv_name = 'tripal') {
 
-   // update the property.
-   return tripal_core_update_property_by_id('analysisfeature',
+    // update the property.
+    return tripal_core_update_property_by_id('analysisfeature',
       $analysisfeatureprop_id, $property, $cv_name, $value);
 }
 /**
@@ -481,25 +481,25 @@ function tripal_feature_analysis_update_property_by_id($analysisfeatureprop_id,
  * @ingroup tripal_feature_api
  */
 function tripal_feature_analysis_delete_property($analysis_id = NULL, $feature_id = NUll,
-   $analysisfeature_id = NULL, $property, $cv_name = 'tripal') {
-   // check that the incoming arguments are correct
-   if (($analysis_id and !$feature_id) or
-       (!$analysis_id and $feature_id)) {
-       watchdog('tripal_feature',
-          'tripal_feature_analysis_delete_property: Both an analysis ID and feature ID should be specified',
-           array(), WATCHDOG_WARNING);
-   }
-
-   // get the analysisfeature_id if one is not provided
-   if (!$analysisfeature_id) {
-      $columns = array('analysisfeature_id');
-      $values = array('analysis_id' => $analysis_id, 'feature_id' => $feature_id);
-      $result = tripal_core_chado_select('analysisfeature', $columns, $values);
-      $analysisfeature_id = $result[0]->analysisfeature_id;
-   }
-
-   // get the property.
-   return tripal_core_delete_property('analysisfeature', $analysisfeature_id, $property, $cv_name);
+  $analysisfeature_id = NULL, $property, $cv_name = 'tripal') {
+  // check that the incoming arguments are correct
+  if (($analysis_id and !$feature_id) or
+    (!$analysis_id and $feature_id)) {
+      watchdog('tripal_feature',
+      'tripal_feature_analysis_delete_property: Both an analysis ID and feature ID should be specified',
+        array(), WATCHDOG_WARNING);
+  }
+
+  // get the analysisfeature_id if one is not provided
+  if (!$analysisfeature_id) {
+    $columns = array('analysisfeature_id');
+    $values = array('analysis_id' => $analysis_id, 'feature_id' => $feature_id);
+    $result = tripal_core_chado_select('analysisfeature', $columns, $values);
+    $analysisfeature_id = $result[0]->analysisfeature_id;
+  }
+
+  // get the property.
+  return tripal_core_delete_property('analysisfeature', $analysisfeature_id, $property, $cv_name);
 }
 /**
  * Delete a property using the analysisfeatureprop_id
@@ -513,8 +513,8 @@ function tripal_feature_analysis_delete_property($analysis_id = NULL, $feature_i
  * @ingroup tripal_feature_api
  */
 function tripal_feature_analysis_delete_property_by_id($analysisfeatureprop_id) {
-   // get the property.
-   return tripal_core_delete_property_by_id('analysisfeature', $analysisfeatureprop_id);
+  // get the property.
+  return tripal_core_delete_property_by_id('analysisfeature', $analysisfeatureprop_id);
 }
 /**
  * Retrieve properties of a given type for a given feature
@@ -533,7 +533,7 @@ function tripal_feature_analysis_delete_property_by_id($analysisfeatureprop_id)
  * @ingroup tripal_feature_api
  */
 function tripal_feature_get_property($feature_id, $property, $cv_name='tripal') {
-   return tripal_core_get_property('feature', $feature_id, $property, $cv_name);
+  return tripal_core_get_property('feature', $feature_id, $property, $cv_name);
 }
 
 /**
@@ -557,9 +557,9 @@ function tripal_feature_get_property($feature_id, $property, $cv_name='tripal')
  * @ingroup tripal_feature_api
  */
 function tripal_feature_insert_property($feature_id, $property, $value,
-   $update_if_present = 0, $cv_name = 'tripal') {
-    return tripal_core_insert_property('feature', $feature_id, $property,
-       $cv_name, $value, $update_if_present);
+  $update_if_present = 0, $cv_name = 'tripal') {
+  return tripal_core_insert_property('feature', $feature_id, $property,
+    $cv_name, $value, $update_if_present);
 }
 /**
  * Update a feature property using the property name. Only use this
@@ -587,7 +587,7 @@ function tripal_feature_insert_property($feature_id, $property, $value,
  */
 function tripal_feature_update_property($feature_id, $property,
   $value, $insert_if_missing = 0, $cv_name = 'tripal') {
-   return tripal_core_update_property('feature', $feature_id, $property, $cv_name, $value, $insert_if_missing);
+    return tripal_core_update_property('feature', $feature_id, $property, $cv_name, $value, $insert_if_missing);
 }
 
 /**
@@ -610,7 +610,7 @@ function tripal_feature_update_property($feature_id, $property,
  */
 function tripal_feature_update_property_by_id($featureprop_id, $property,
   $value, $cv_name = 'tripal') {
-   return tripal_core_update_property_by_id('feature', $featureprop_id, $property, $cv_name, $value);
+    return tripal_core_update_property_by_id('feature', $featureprop_id, $property, $cv_name, $value);
 }
 
 /**
@@ -634,7 +634,7 @@ function tripal_feature_update_property_by_id($featureprop_id, $property,
  * @ingroup tripal_feature_api
  */
 function tripal_feature_delete_property($feature_id, $property, $cv_name='tripal') {
-   return tripal_core_delete_property('feature', $feature_id, $property, $cv_name);
+  return tripal_core_delete_property('feature', $feature_id, $property, $cv_name);
 }
 /**
  * Delete a given feature property using the featureprop_id
@@ -648,5 +648,5 @@ function tripal_feature_delete_property($feature_id, $property, $cv_name='tripal
  * @ingroup tripal_feature_api
  */
 function tripal_feature_delete_property_by_id($featureprop_id) {
-   return tripal_core_delete_property_by_id('feature', $featureprop_id);
+  return tripal_core_delete_property_by_id('feature', $featureprop_id);
 }

+ 21 - 0
tripal_feature/tripal_feature.coder_ignores.txt

@@ -0,0 +1,21 @@
+; The file should be formatted this way :
+; file:line:warning-type
+; where warning-type is one of security, style, sql, i18n, comment, etc.
+
+; This query selects from a non-drupal schema where the database prefixes are not
+; applied and thus the curcly brackets ({}) are not needed
+fasta_loader.php:655:sql
+fasta_loader.php:659:sql
+fasta_loader.php:672:sql
+fasta_loader.php:676:sql
+gff_loader.php:243:sql
+gff_loader.php:252:sql
+gff_loader.php:919:sql
+
+; This is a multi-line conditional that needs to be re-written to be more readable
+gff_loader.php:164:style
+gff_loader.php:165:style
+gff_loader.php:166:style
+
+; Don't need to use db_rewrite_sql() since need all nodes regardless of access control
+syncFeatures.php:425:sql

+ 146 - 146
tripal_feature/tripal_feature.install

@@ -5,173 +5,173 @@
  */
 
 /**
-*  Implementation of hook_install();
-*
-* @ingroup tripal_feature
-*/
+ * Implementation of hook_install().
+ *
+ * @ingroup tripal_feature
+ */
 function tripal_feature_install() {
-   // create the module's data directory
-   tripal_create_moddir('tripal_feature');
+  // create the module's data directory
+  tripal_create_moddir('tripal_feature');
 
-   // create the tables that correlate drupal nodes with chado
-   // features, organisms, etc....
-   drupal_install_schema('tripal_feature');
+  // create the tables that correlate drupal nodes with chado
+  // features, organisms, etc....
+  drupal_install_schema('tripal_feature');
 
-   // add the materialized view
-   tripal_feature_add_organism_count_mview();
+  // add the materialized view
+  tripal_feature_add_organism_count_mview();
 
 }
 /**
-*  Update for Drupal 6.x, Tripal 0.2b, Feature Module 0.2
-*  This update adjusts the materialized view by adding a 'cvterm_id' column
-*
-* @ingroup tripal_feature
-*/
+ *  Update for Drupal 6.x, Tripal 0.2b, Feature Module 0.2
+ *  This update adjusts the materialized view by adding a 'cvterm_id' column
+ *
+ * @ingroup tripal_feature
+ */
 function tripal_feature_update_6000() {
-   // recreate the materialized view
-   tripal_feature_add_organism_count_mview();
-   $ret = array(
-      '#finished' => 1,
-   );
+  // recreate the materialized view
+  tripal_feature_add_organism_count_mview();
+  $ret = array(
+    '#finished' => 1,
+  );
 
-   return $ret;
+  return $ret;
 }
 
 /**
-*
-* @ingroup tripal_feature
-*/
+ *
+ * @ingroup tripal_feature
+ */
 function tripal_feature_update_6300() {
-   // add the relationship aggregator table to the database
-   $schema = tripal_feature_get_schemas('tripal_feature_relagg');
-   $ret = array();
-   db_create_table($ret, 'tripal_feature_relagg', $schema['tripal_feature_relagg']);
+  // add the relationship aggregator table to the database
+  $schema = tripal_feature_get_schemas('tripal_feature_relagg');
+  $ret = array();
+  db_create_table($ret, 'tripal_feature_relagg', $schema['tripal_feature_relagg']);
 
-   return $ret;
+  return $ret;
 }
 /**
-*
-* @ingroup tripal_feature
-*/
+ *
+ * @ingroup tripal_feature
+ */
 function tripal_feature_add_organism_count_mview() {
-   $view_name = 'organism_feature_count';
-
-   // Drop the MView table if it exists
-   $mview_id = tripal_mviews_get_mview_id($view_name);
-   if ($mview_id) {
-      tripal_mviews_action("delete", $mview_id);
-   }
-
-   // Create the MView
-   tripal_add_mview(
-      // view name
-      $view_name,
-      // tripal module name
-      'tripal_feature',
-      // table name
-      $view_name,
-      // table schema definition
-      'organism_id integer, genus character varying(255), '.
-      '  species character varying(255), '.
-      '  common_name character varying(255), '.
-      '  num_features integer, cvterm_id integer, '.
-      '  feature_type character varying(255)',
-      // columns for indexing
-      'organism_id,cvterm_id,feature_type',
-      // SQL statement to populate the view
-      'SELECT O.organism_id, O.genus, O.species, O.common_name,
-          count(F.feature_id) as num_features,
-          CVT.cvterm_id, CVT.name as feature_type
-       FROM {Organism} O
-          INNER JOIN Feature F           ON O.Organism_id = F.organism_id
-          INNER JOIN Cvterm CVT          ON F.type_id = CVT.cvterm_id
-       GROUP BY O.Organism_id, O.genus, O.species, O.common_name,
-          CVT.cvterm_id, CVT.name',
-      // special index
-      ''
-   );
-
-   // add a job to the job queue so this view gets updated automatically next
-   // time the job facility is run
-   $mview_id = tripal_mviews_get_mview_id($view_name);
-   if ($mview_id) {
-      tripal_mviews_action('update', $mview_id);
-   }
+  $view_name = 'organism_feature_count';
+
+  // Drop the MView table if it exists
+  $mview_id = tripal_mviews_get_mview_id($view_name);
+  if ($mview_id) {
+    tripal_mviews_action("delete", $mview_id);
+  }
+
+  // Create the MView
+  tripal_add_mview(
+    // view name
+    $view_name,
+    // tripal module name
+    'tripal_feature',
+    // table name
+    $view_name,
+    // table schema definition
+    'organism_id integer, genus character varying(255), '.
+    '  species character varying(255), '.
+    '  common_name character varying(255), '.
+    '  num_features integer, cvterm_id integer, '.
+    '  feature_type character varying(255)',
+    // columns for indexing
+    'organism_id,cvterm_id,feature_type',
+    // SQL statement to populate the view
+    'SELECT O.organism_id, O.genus, O.species, O.common_name,
+        count(F.feature_id) as num_features,
+        CVT.cvterm_id, CVT.name as feature_type
+     FROM {Organism} O
+        INNER JOIN Feature F           ON O.Organism_id = F.organism_id
+        INNER JOIN Cvterm CVT          ON F.type_id = CVT.cvterm_id
+     GROUP BY O.Organism_id, O.genus, O.species, O.common_name,
+        CVT.cvterm_id, CVT.name',
+    // special index
+    ''
+  );
+
+  // add a job to the job queue so this view gets updated automatically next
+  // time the job facility is run
+  $mview_id = tripal_mviews_get_mview_id($view_name);
+  if ($mview_id) {
+    tripal_mviews_action('update', $mview_id);
+  }
 }
 /**
-* Implementation of hook_schema().
-*
-* @ingroup tripal_feature
-*/
+ * Implementation of hook_schema().
+ *
+ * @ingroup tripal_feature
+ */
 function tripal_feature_schema() {
-   $schema = tripal_feature_get_schemas();
-   return $schema;
+  $schema = tripal_feature_get_schemas();
+  return $schema;
 }
 /**
-* Implementation of hook_uninstall()
-*
-* @ingroup tripal_feature
-*/
+ * Implementation of hook_uninstall().
+ *
+ * @ingroup tripal_feature
+ */
 function tripal_feature_uninstall() {
 
-   // Drop the MView table if it exists
-   $mview_id = tripal_mviews_get_mview_id('organism_feature_count');
-   if ($mview_id) {
-      tripal_mviews_action("delete", $mview_id);
-   }
-
-   drupal_uninstall_schema('tripal_feature');
-
-   // Get the list of nodes to remove
-   $sql_feature_id = "SELECT nid, vid " .
-                 "FROM {node} " .
-                 "WHERE type='chado_feature'";
-   $result = db_query($sql_feature_id);
-   while ($node = db_fetch_object($result)) {
-      node_delete($node->nid);
-   }
+  // Drop the MView table if it exists
+  $mview_id = tripal_mviews_get_mview_id('organism_feature_count');
+  if ($mview_id) {
+    tripal_mviews_action("delete", $mview_id);
+  }
+
+  drupal_uninstall_schema('tripal_feature');
+
+  // Get the list of nodes to remove
+  $sql_feature_id = "SELECT nid, vid " .
+               "FROM {node} " .
+               "WHERE type='chado_feature'";
+  $result = db_query($sql_feature_id);
+  while ($node = db_fetch_object($result)) {
+    node_delete($node->nid);
+  }
 }
 
 /**
-* This function simply defines all tables needed for the module to work
-* correctly.  By putting the table definitions in a separate function we
-* can easily provide the entire list for hook_install or individual
-* tables for an update.
-*
-* @ingroup tripal_feature
-*/
+ * This function simply defines all tables needed for the module to work
+ * correctly.  By putting the table definitions in a separate function we
+ * can easily provide the entire list for hook_install or individual
+ * tables for an update.
+ *
+ * @ingroup tripal_feature
+ */
 function tripal_feature_get_schemas($table = NULL) {
   $schema = array();
 
 
   if (!$table or strcmp($table, 'chado_feature')==0) {
-     $schema['chado_feature'] = array(
-         'fields' => array(
-            'vid' => array('type' => 'int', 'unsigned' => TRUE, 'not null' => TRUE, 'default' => 0),
-            'nid' => array('type' => 'int', 'unsigned' => TRUE, 'not null' => TRUE, 'default' => 0),
-            'feature_id' => array('type' => 'int', 'not null' => TRUE, 'default' => 0),
-            'sync_date' => array('type' => 'int', 'not null' => FALSE, 'description' => 'UNIX integer sync date/time'),
-         ),
-         'indexes' => array(
-            'feature_id' => array('feature_id')
-          ),
-         'unique keys' => array(
-            'nid_vid' => array('nid', 'vid'),
-            'vid' => array('vid')
-         ),
-         'primary key' => array('nid'),
-     );
+    $schema['chado_feature'] = array(
+      'fields' => array(
+        'vid' => array('type' => 'int', 'unsigned' => TRUE, 'not null' => TRUE, 'default' => 0),
+        'nid' => array('type' => 'int', 'unsigned' => TRUE, 'not null' => TRUE, 'default' => 0),
+        'feature_id' => array('type' => 'int', 'not null' => TRUE, 'default' => 0),
+        'sync_date' => array('type' => 'int', 'not null' => FALSE, 'description' => 'UNIX integer sync date/time'),
+      ),
+      'indexes' => array(
+        'feature_id' => array('feature_id')
+      ),
+      'unique keys' => array(
+        'nid_vid' => array('nid', 'vid'),
+        'vid' => array('vid')
+      ),
+      'primary key' => array('nid'),
+    );
   }
   if (!$table or strcmp($table, 'tripal_feature_relagg')==0) {
-     $schema['tripal_feature_relagg'] = array(
-        'fields' => array(
-           'type_id' => array('type' => 'int', 'unsigned' => TRUE, 'not null' => TRUE, 'default' => 0),
-           'rel_type_id' => array('type' => 'int', 'unsigned' => TRUE, 'not null' => TRUE, 'default' => 0),
-        ),
-        'indexes' => array(
-           'type_id' => array('type_id')
-        ),
-     );
+    $schema['tripal_feature_relagg'] = array(
+      'fields' => array(
+        'type_id' => array('type' => 'int', 'unsigned' => TRUE, 'not null' => TRUE, 'default' => 0),
+        'rel_type_id' => array('type' => 'int', 'unsigned' => TRUE, 'not null' => TRUE, 'default' => 0),
+      ),
+      'indexes' => array(
+        'type_id' => array('type_id')
+      ),
+    );
   }
 
   return $schema;
@@ -184,16 +184,16 @@ function tripal_feature_get_schemas($table = NULL) {
  * @ingroup tripal_feature
  */
 function tripal_feature_requirements($phase) {
-   $requirements = array();
-   if ($phase == 'install') {
-      // make sure the core module is installed...
-      if (!function_exists('tripal_create_moddir')) {
-         $requirements ['tripal_feature'] = array(
-            'title' => "tripal_feature",
-            'value' => "error. Some required modules are just being installed. Please try again.",
-            'severity' => REQUIREMENT_ERROR,
-         );
-      }
-   }
-   return $requirements;
+  $requirements = array();
+  if ($phase == 'install') {
+    // make sure the core module is installed...
+    if (!function_exists('tripal_create_moddir')) {
+      $requirements ['tripal_feature'] = array(
+        'title' => "tripal_feature",
+        'value' => "error. Some required modules are just being installed. Please try again.",
+        'severity' => REQUIREMENT_ERROR,
+      );
+    }
+  }
+  return $requirements;
 }

Tiedoston diff-näkymää rajattu, sillä se on liian suuri
+ 436 - 437
tripal_feature/tripal_feature.module


+ 12 - 12
tripal_feature/tripal_feature.views.inc

@@ -38,7 +38,7 @@ function tripal_feature_views_data()  {
     );
     foreach ($tables as $tablename) {
       if (!tripal_views_is_integrated($tablename, 10)) {
-        $table_integration_array = tripal_views_get_integration_array_for_chado_table($tablename,TRUE);
+        $table_integration_array = tripal_views_get_integration_array_for_chado_table($tablename, TRUE);
         tripal_views_integration_add_entry($table_integration_array);
       }
     }
@@ -67,7 +67,7 @@ function tripal_feature_views_data()  {
     );
     foreach ($tables as $tablename) {
       if (!tripal_views_is_integrated($tablename, 10)) {
-        $table_integration_array = tripal_views_get_integration_array_for_chado_table($tablename,FALSE);
+        $table_integration_array = tripal_views_get_integration_array_for_chado_table($tablename, FALSE);
         tripal_views_integration_add_entry($table_integration_array);
       }
     }
@@ -88,16 +88,16 @@ function tripal_feature_views_data()  {
  * @ingroup tripal_feature_views
  */
 function tripal_feature_views_handlers() {
- return array(
-   'info' => array(
-     'path' => drupal_get_path('module', 'tripal_feature') . '/views_handlers',
-   ),
-   'handlers' => array(
-     'views_handler_field_residues' => array(
-       'parent' => 'views_handler_field',
-     ),
-   ),
- );
+  return array(
+    'info' => array(
+      'path' => drupal_get_path('module', 'tripal_feature') . '/views_handlers',
+    ),
+    'handlers' => array(
+    'views_handler_field_residues' => array(
+      'parent' => 'views_handler_field',
+    ),
+    ),
+  );
 }
 
 /**

+ 1 - 1
tripal_feature/views_handlers/views_handler_field_residues.inc

@@ -24,7 +24,7 @@ class views_handler_field_residues extends views_handler_field {
 
   function render($values) {
     // add a <br> every 100 bp
-    return ereg_replace("(.{100})", "\\1<br>", $values->feature_residues);
+    return ereg_replace("(.{100})", "\\1<br />", $values->feature_residues);
 
   }
 }

+ 2 - 2
tripal_genetic/tripal_genetic.module

@@ -18,9 +18,9 @@ require('tripal_genetic.api.inc');
  *  views integration code is
  */
 function tripal_genetic_views_api() {
-   return array(
+  return array(
       'api' => 2.0,
-   );
+  );
 }
 
 function tripal_genetic_theme() {

+ 7 - 7
tripal_genetic/tripal_genetic.views.inc

@@ -31,7 +31,7 @@ function tripal_genetic_views_data()  {
     );
     foreach ($tables as $tablename) {
       if (!tripal_views_is_integrated($tablename, 10)) {
-        $table_integration_array = tripal_views_get_integration_array_for_chado_table($tablename,TRUE);
+        $table_integration_array = tripal_views_get_integration_array_for_chado_table($tablename, TRUE);
         tripal_views_integration_add_entry($table_integration_array);
       }
     }
@@ -44,7 +44,7 @@ function tripal_genetic_views_data()  {
     );
     foreach ($tables as $tablename) {
       if (!tripal_views_is_integrated($tablename, 10)) {
-        $table_integration_array = tripal_views_get_integration_array_for_chado_table($tablename,FALSE);
+        $table_integration_array = tripal_views_get_integration_array_for_chado_table($tablename, FALSE);
         tripal_views_integration_add_entry($table_integration_array);
       }
     }
@@ -62,12 +62,12 @@ function tripal_genetic_views_data()  {
  * @return: An array of handler definitions
  */
 function tripal_genetic_views_handlers() {
- return array(
+  return array(
    'info' => array(
      'path' => drupal_get_path('module', 'tripal_genetic') . '/views/handlers',
-   ),
+  ),
    'handlers' => array(
 
-   ),
- );
-}
+  ),
+  );
+}

+ 12 - 7
tripal_library/reindex.php

@@ -1,19 +1,24 @@
 <?php
+
+/**
+ * @file
+ * @todo Add file header description
+ */
+
+
 //
 // Copyright 2009 Clemson University
 //
 
 
-/* 
-
-This script must be run at the base directory level of the drupal installation 
-in order to pick up all necessary dependencies 
-
-*/
+/*
+ This script must be run at the base directory level of the drupal installation
+ in order to pick up all necessary dependencies
+ */
 
 require_once './includes/bootstrap.inc';
 drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);
 
 jlibrary_feature_reindex($argv[1]);
 
-?>
+

+ 11 - 7
tripal_library/taxonify.php

@@ -1,18 +1,22 @@
 <?php
+
+/**
+ * @file
+ * @todo Add file header description
+ */
+
 //
 // Copyright 2009 Clemson University
 //
 
-/* 
-
-This script must be run at the base directory level of the drupal installation 
-in order to pick up all necessary dependencies 
-
-*/
+/*
+ This script must be run at the base directory level of the drupal installation
+ in order to pick up all necessary dependencies
+ */
 
 require_once './includes/bootstrap.inc';
 drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);
 
 jlibrary_feature_set_taxonomy($argv[1]);
 
-?>
+

+ 4 - 4
tripal_library/tripal_library.api.inc

@@ -128,7 +128,7 @@ function tripal_library_chado_libraryprop_schema() {
  * @ingroup tripal_library_api
  */
 function tripal_library_get_property($library_id, $property) {
-   return tripal_core_get_property('library', $library_id, $property, 'tripal');
+  return tripal_core_get_property('library', $library_id, $property, 'tripal');
 }
 
 /**
@@ -149,7 +149,7 @@ function tripal_library_get_property($library_id, $property) {
  * @ingroup tripal_library_api
  */
 function tripal_library_insert_property($library_id, $property, $value, $update_if_present = 0) {
-   return tripal_core_insert_property('library', $library_id, $property, 'tripal', $value, $update_if_present);
+  return tripal_core_insert_property('library', $library_id, $property, 'tripal', $value, $update_if_present);
 }
 
 /**
@@ -173,7 +173,7 @@ function tripal_library_insert_property($library_id, $property, $value, $update_
  * @ingroup tripal_library_api
  */
 function tripal_library_update_property($library_id, $property, $value, $insert_if_missing = 0) {
-   return tripal_core_update_property('library', $library_id, $property, 'tripal', $value, $insert_if_missing);
+  return tripal_core_update_property('library', $library_id, $property, 'tripal', $value, $insert_if_missing);
 }
 /**
  * Delete a given property
@@ -192,5 +192,5 @@ function tripal_library_update_property($library_id, $property, $value, $insert_
  * @ingroup tripal_library_api
  */
 function tripal_library_delete_property($library_id, $property) {
-   return tripal_core_delete_property('library', $library_id, $property, 'tripal');
+  return tripal_core_delete_property('library', $library_id, $property, 'tripal');
 }

+ 101 - 101
tripal_library/tripal_library.install

@@ -5,56 +5,56 @@
  */
 
 /**
-*  Implementation of hook_install();
-*
-* @ingroup tripal_library
-*/
+ * Implementation of hook_install().
+ *
+ * @ingroup tripal_library
+ */
 function tripal_library_install() {
-   // create the module's data directory
-   tripal_create_moddir('tripal_library');
+  // create the module's data directory
+  tripal_create_moddir('tripal_library');
 
-   // create the tables that correlate drupal nodes with chado
-   // features, librarys, etc....
-   drupal_install_schema('tripal_library');
+  // create the tables that correlate drupal nodes with chado
+  // features, librarys, etc....
+  drupal_install_schema('tripal_library');
 
-   // Insert cvterm 'library_description' into cvterm table of chado
-   // database. This CV term is used to keep track of the library
-   // description in the libraryprop table.
-   tripal_cv_add_cvterm(array('name' => 'library_description', 'def' => 'Description of a library'), 'tripal', 0, 1, 'tripal');
+  // Insert cvterm 'library_description' into cvterm table of chado
+  // database. This CV term is used to keep track of the library
+  // description in the libraryprop table.
+  tripal_cv_add_cvterm(array('name' => 'library_description', 'def' => 'Description of a library'), 'tripal', 0, 1, 'tripal');
 
-   // Add CVTerms for the library types
-   tripal_cv_add_cvterm(array('name' => 'cdna_library', 'def' => 'cDNA Library'), 'tripal', 0, 1, 'tripal');
-   tripal_cv_add_cvterm(array('name' => 'bac_library', 'def' => 'BAC Library'), 'tripal', 0, 1, 'tripal');
-   tripal_cv_add_cvterm(array('name' => 'fosmid_library', 'def' => 'FOSMID Library'), 'tripal', 0, 1, 'tripal');
-   tripal_cv_add_cvterm(array('name' => 'cosmid_library', 'def' => 'COSMID Library'), 'tripal', 0, 1, 'tripal');
-   tripal_cv_add_cvterm(array('name' => 'yac_library', 'def' => 'YAC Library'), 'tripal', 0, 1, 'tripal');
+  // Add CVTerms for the library types
+  tripal_cv_add_cvterm(array('name' => 'cdna_library', 'def' => 'cDNA Library'), 'tripal', 0, 1, 'tripal');
+  tripal_cv_add_cvterm(array('name' => 'bac_library', 'def' => 'BAC Library'), 'tripal', 0, 1, 'tripal');
+  tripal_cv_add_cvterm(array('name' => 'fosmid_library', 'def' => 'FOSMID Library'), 'tripal', 0, 1, 'tripal');
+  tripal_cv_add_cvterm(array('name' => 'cosmid_library', 'def' => 'COSMID Library'), 'tripal', 0, 1, 'tripal');
+  tripal_cv_add_cvterm(array('name' => 'yac_library', 'def' => 'YAC Library'), 'tripal', 0, 1, 'tripal');
 
-   // Add the materialized view needed to count the features for the library
-   // Drop the MView table if it exists
-   $previous_db = tripal_db_set_active('chado');
-   if (db_table_exists('library_feature_count')) {
-      $sql = "DROP TABLE library_feature_count";
-      db_query($sql);
-   }
-   tripal_db_set_active($previous_db);
-   // Create the MView
-   tripal_add_mview('library_feature_count', 'tripal_library',
-      'library_feature_count',
-      'library_id integer, name character varying(255), '.
-    '  num_features integer, feature_type character varying(255)',
-     'library_id',
-     'SELECT '.
-      '   L.library_id, '.
-      '   L.name, '.
-      '    count(F.feature_id) as num_features, '.
-      '    CVT.name as feature_type '.
-      'FROM {Library} L '.
-      '    INNER JOIN Library_Feature LF  ON LF.library_id = L.library_id '.
-      '    INNER JOIN Feature F           ON LF.feature_id = F.feature_id '.
-      '    INNER JOIN Cvterm CVT          ON F.type_id = CVT.cvterm_id '.
-      'GROUP BY L.library_id, L.name, CVT.name',
-     ''
-   );
+  // Add the materialized view needed to count the features for the library
+  // Drop the MView table if it exists
+  $previous_db = tripal_db_set_active('chado');
+  if (db_table_exists('library_feature_count')) {
+    $sql = "DROP TABLE library_feature_count";
+    db_query($sql);
+  }
+  tripal_db_set_active($previous_db);
+  // Create the MView
+  tripal_add_mview('library_feature_count', 'tripal_library',
+    'library_feature_count',
+    'library_id integer, name character varying(255), '.
+  '  num_features integer, feature_type character varying(255)',
+   'library_id',
+   'SELECT '.
+    '   L.library_id, '.
+    '   L.name, '.
+    '    count(F.feature_id) as num_features, '.
+    '    CVT.name as feature_type '.
+    'FROM {Library} L '.
+    '    INNER JOIN Library_Feature LF  ON LF.library_id = L.library_id '.
+    '    INNER JOIN Feature F           ON LF.feature_id = F.feature_id '.
+    '    INNER JOIN Cvterm CVT          ON F.type_id = CVT.cvterm_id '.
+    'GROUP BY L.library_id, L.name, CVT.name',
+   ''
+  );
 
 }
 
@@ -64,37 +64,37 @@ function tripal_library_install() {
  * @ingroup tripal_library
  */
 function tripal_library_schema() {
-   $schema = tripal_library_get_schemas();
-   return $schema;
+  $schema = tripal_library_get_schemas();
+  return $schema;
 }
 
 /**
- * Implementation of hook_uninstall()
+ * Implementation of hook_uninstall().
  *
  * @ingroup tripal_library
  */
 function tripal_library_uninstall() {
-   drupal_uninstall_schema('tripal_library');
+  drupal_uninstall_schema('tripal_library');
 
-   // remove the materialized view
-   $sql = "SELECT * FROM {tripal_mviews} ".
-          "WHERE name = 'library_feature_count'";
+  // remove the materialized view
+  $sql = "SELECT * FROM {tripal_mviews} ".
+        "WHERE name = 'library_feature_count'";
 
-   if (db_table_exists('tripal_mviews')) {
-      $mview = db_fetch_object(db_query($sql));
-      if ($mview) {
-         tripal_mviews_action('delete', $mview->mview_id);
-      }
-   }
+  if (db_table_exists('tripal_mviews')) {
+    $mview = db_fetch_object(db_query($sql));
+    if ($mview) {
+      tripal_mviews_action('delete', $mview->mview_id);
+    }
+  }
 
-   // Get the list of nodes to remove
-   $sql_lib_id = "SELECT nid, vid ".
-                 "FROM {node} ".
-                 "WHERE type='chado_library'";
-   $result = db_query($sql_lib_id);
-   while ($node = db_fetch_object($result)) {
-      node_delete($node->nid);
-   }
+  // Get the list of nodes to remove
+  $sql_lib_id = "SELECT nid, vid ".
+               "FROM {node} ".
+               "WHERE type='chado_library'";
+  $result = db_query($sql_lib_id);
+  while ($node = db_fetch_object($result)) {
+    node_delete($node->nid);
+  }
 }
 
 /**
@@ -108,33 +108,33 @@ function tripal_library_uninstall() {
 function tripal_library_get_schemas() {
   $schema = array();
   $schema['chado_library'] = array(
-      'fields' => array(
-         'vid' => array(
-            'type' => 'int',
-            'unsigned' => TRUE,
-            'not null' => TRUE,
-            'default' => 0
-         ),
-         'nid' => array(
-            'type' => 'int',
-            'unsigned' => TRUE,
-            'not null' => TRUE,
-            'default' => 0
-         ),
-         'library_id' => array(
-            'type' => 'int',
-            'not null' => TRUE,
-            'default' => 0
-         )
+    'fields' => array(
+      'vid' => array(
+        'type' => 'int',
+        'unsigned' => TRUE,
+        'not null' => TRUE,
+        'default' => 0
+      ),
+    'nid' => array(
+      'type' => 'int',
+      'unsigned' => TRUE,
+      'not null' => TRUE,
+      'default' => 0
+      ),
+    'library_id' => array(
+      'type' => 'int',
+      'not null' => TRUE,
+      'default' => 0
+      )
       ),
-      'indexes' => array(
-         'library_id' => array('library_id')
+    'indexes' => array(
+      'library_id' => array('library_id')
       ),
-      'unique keys' => array(
-         'nid_vid' => array('nid', 'vid'),
-         'vid' => array('vid')
+    'unique keys' => array(
+      'nid_vid' => array('nid', 'vid'),
+      'vid' => array('vid')
       ),
-      'primary key' => array('nid'),
+    'primary key' => array('nid'),
   );
   return $schema;
 }
@@ -146,15 +146,15 @@ function tripal_library_get_schemas() {
  * @ingroup tripal_library
  */
 function tripal_library_requirements($phase) {
-   $requirements = array();
-   if ($phase == 'install') {
-      if (!function_exists('tripal_create_moddir')) {
-         $requirements ['tripal_library'] = array(
-            'title' => "tripal_library",
-            'value' => "error. Some required modules are just being installed. Please try again.",
-            'severity' => REQUIREMENT_ERROR,
-         );
-      }
-   }
-   return $requirements;
+  $requirements = array();
+  if ($phase == 'install') {
+    if (!function_exists('tripal_create_moddir')) {
+      $requirements ['tripal_library'] = array(
+        'title' => "tripal_library",
+        'value' => "error. Some required modules are just being installed. Please try again.",
+        'severity' => REQUIREMENT_ERROR,
+        );
+    }
+  }
+  return $requirements;
 }

Tiedoston diff-näkymää rajattu, sillä se on liian suuri
+ 531 - 531
tripal_library/tripal_library.module


+ 7 - 7
tripal_library/tripal_library.views.inc

@@ -36,7 +36,7 @@ function tripal_library_views_data()  {
     );
     foreach ($tables as $tablename) {
       if (!tripal_views_is_integrated($tablename, 10)) {
-        $table_integration_array = tripal_views_get_integration_array_for_chado_table($tablename,TRUE);
+        $table_integration_array = tripal_views_get_integration_array_for_chado_table($tablename, TRUE);
         tripal_views_integration_add_entry($table_integration_array);
       }
     }
@@ -50,7 +50,7 @@ function tripal_library_views_data()  {
     );
     foreach ($tables as $tablename) {
       if (!tripal_views_is_integrated($tablename, 10)) {
-        $table_integration_array = tripal_views_get_integration_array_for_chado_table($tablename,FALSE);
+        $table_integration_array = tripal_views_get_integration_array_for_chado_table($tablename, FALSE);
         tripal_views_integration_add_entry($table_integration_array);
       }
     }
@@ -69,16 +69,16 @@ function tripal_library_views_data()  {
  * @ingroup tripal_library_views
  */
 function tripal_library_views_handlers() {
- return array(
+  return array(
    'info' => array(
      'path' => drupal_get_path('module', 'tripal_library') . '/views/handlers',
-   ),
+      ),
    'handlers' => array(
      'views_handler_field_computed_library_nid' => array(
        'parent' => 'views_handler_field_numeric',
-     ),
-   ),
- );
+      ),
+    ),
+  );
 }
 
 /**

+ 2 - 2
tripal_natural_diversity/tripal_natural_diversity.module

@@ -18,9 +18,9 @@ require_once('tripal_natural_diversity.api.inc');
  *  views integration code is
  */
 function tripal_natural_diversity_views_api() {
-   return array(
+  return array(
       'api' => 2.0,
-   );
+  );
 }
 
 /**

+ 8 - 8
tripal_natural_diversity/tripal_natural_diversity.views.inc

@@ -32,7 +32,7 @@ function tripal_natural_diversity_views_data()  {
     );
     foreach ($tables as $tablename) {
       if (!tripal_views_is_integrated($tablename, 10)) {
-        $table_integration_array = tripal_views_get_integration_array_for_chado_table($tablename,TRUE);
+        $table_integration_array = tripal_views_get_integration_array_for_chado_table($tablename, TRUE);
         tripal_views_integration_add_entry($table_integration_array);
       }
     }
@@ -57,7 +57,7 @@ function tripal_natural_diversity_views_data()  {
     );
     foreach ($tables as $tablename) {
       if (!tripal_views_is_integrated($tablename, 10)) {
-        $table_integration_array = tripal_views_get_integration_array_for_chado_table($tablename,FALSE);
+        $table_integration_array = tripal_views_get_integration_array_for_chado_table($tablename, FALSE);
         tripal_views_integration_add_entry($table_integration_array);
       }
     }
@@ -75,17 +75,17 @@ function tripal_natural_diversity_views_data()  {
  * @return: An array of handler definitions
  */
 function tripal_natural_diversity_views_handlers() {
- return array(
+  return array(
    'info' => array(
      'path' => drupal_get_path('module', 'tripal_natural_diversity') . '/views/handlers',
-   ),
+  ),
    'handlers' => array(
   'views_handler_field_chado_relationship_all' => array(
        'parent' => 'views_handler_field_prerender_list',
-     ),
+  ),
   'views_handler_field_chado_relationship_by_type' => array(
        'parent' => 'views_handler_field_prerender_list',
-     ),
-   ),
- );
+  ),
+  ),
+  );
 }

+ 18 - 18
tripal_organism/tripal_organism.api.inc

@@ -59,18 +59,18 @@ function tripal_organism_get_organism_by_organism_id($organism_id) {
     return node_load($r->nid);
   }
   else {
-    drupal_set_message("Function: tripal_organism_get_organism_by_organism_id() -no organism with that organism id sync'd with drupal", 'error');
+    drupal_set_message(t("Function: tripal_organism_get_organism_by_organism_id() -no organism with that organism id sync'd with drupal"), 'error');
   }
 
   return 0;
 
 }
 
-/*****
+/**
  * @section Chado Table Descriptions
  * There should be a default table description for all chado tables included
  * in core.
- ****************************************************************************/
+ */
 
 /**
  * Implements hook_chado_organism_schema()
@@ -137,22 +137,22 @@ function tripal_organism_chado_organismprop_schema() {
  */
 function tripal_organism_get_synced() {
 
-   // use this SQL for getting synced organisms
-   $dsql =  "SELECT * FROM {chado_organism}";
-   $orgs = db_query($dsql);
+  // use this SQL for getting synced organisms
+  $dsql =  "SELECT * FROM {chado_organism}";
+  $orgs = db_query($dsql);
 
-   // use this SQL statement for getting the organisms
-   $csql =  "SELECT * FROM {Organism} ".
-            "WHERE organism_id = %d";
+  // use this SQL statement for getting the organisms
+  $csql =  "SELECT * FROM {Organism} ".
+          "WHERE organism_id = %d";
 
-   $org_list = array();
+  $org_list = array();
 
-   // iterate through the organisms and build an array of those that are synced
-   while ($org = db_fetch_object($orgs)) {
-      $previous_db = tripal_db_set_active('chado');  // use chado database
-      $info = db_fetch_object(db_query($csql, $org->organism_id));
-      tripal_db_set_active($previous_db);  // now use drupal database
-      $org_list[] = $info;
-   }
-   return $org_list;
+  // iterate through the organisms and build an array of those that are synced
+  while ($org = db_fetch_object($orgs)) {
+    $previous_db = tripal_db_set_active('chado');  // use chado database
+    $info = db_fetch_object(db_query($csql, $org->organism_id));
+    tripal_db_set_active($previous_db);  // now use drupal database
+    $org_list[] = $info;
+  }
+  return $org_list;
 }

+ 61 - 61
tripal_organism/tripal_organism.install

@@ -6,73 +6,73 @@
  */
 
 /**
-*  Implementation of hook_install();
-*
-* @ingroup tripal_organism
-*/
+ * Implementation of hook_install().
+ *
+ * @ingroup tripal_organism
+ */
 function tripal_organism_install() {
 
-   // create the module's data directory
-   tripal_create_moddir('tripal_organism');
+  // create the module's data directory
+  tripal_create_moddir('tripal_organism');
 
-   // create the directory where image files will be stored.  We create this
-   // here otherwise it will get created when the first organism is synced.
-   // The user that performs the syncing will receive ownership of the
-   // images directory which may not allow for write access by the web server
-   // user.  So, we create it here
-   $dest = file_directory_path() . "/tripal/tripal_organism/images";
-   file_check_directory($dest, FILE_CREATE_DIRECTORY);
+  // create the directory where image files will be stored.  We create this
+  // here otherwise it will get created when the first organism is synced.
+  // The user that performs the syncing will receive ownership of the
+  // images directory which may not allow for write access by the web server
+  // user.  So, we create it here
+  $dest = file_directory_path() . "/tripal/tripal_organism/images";
+  file_check_directory($dest, FILE_CREATE_DIRECTORY);
 
-   // create the tables that correlate drupal nodes with chado
-   // features, organisms, etc....
-   drupal_install_schema('tripal_organism');
+  // create the tables that correlate drupal nodes with chado
+  // features, organisms, etc....
+  drupal_install_schema('tripal_organism');
 
 }
 
 /**
-* Implementation of hook_schema().
-*
-* @ingroup tripal_organism
-*/
+ * Implementation of hook_schema().
+ *
+ * @ingroup tripal_organism
+ */
 function tripal_organism_schema() {
-   $schema = tripal_organism_get_schemas();
+  $schema = tripal_organism_get_schemas();
   return $schema;
 }
 
 /**
-* Implementation of hook_uninstall()
-*
-* @ingroup tripal_organism
-*/
+ * Implementation of hook_uninstall().
+ *
+ * @ingroup tripal_organism
+ */
 function tripal_organism_uninstall() {
-   drupal_uninstall_schema('tripal_organism');
+  drupal_uninstall_schema('tripal_organism');
 
-   // Get the list of nodes to remove
-   $sql_lib_id = "SELECT nid, vid ".
-                 "FROM {node} ".
-                 "WHERE type='chado_organism'";
-   $result = db_query($sql_lib_id);
-   while ($node = db_fetch_object($result)) {
-      node_delete($node->nid);
-   }
+  // Get the list of nodes to remove
+  $sql_lib_id = "SELECT nid, vid ".
+               "FROM {node} ".
+               "WHERE type='chado_organism'";
+  $result = db_query($sql_lib_id);
+  while ($node = db_fetch_object($result)) {
+    node_delete($node->nid);
+  }
 
-   // remove the materialized views
+  // remove the materialized views
 
-   // Remove the custom view if exists
-   if (db_table_exists('tripal_organism_views_common_name')) {
-      $sql = "DROP TABLE {tripal_organism_views_common_name}";
-      db_query($sql);
-   }
+  // Remove the custom view if exists
+  if (db_table_exists('tripal_organism_views_common_name')) {
+    $sql = "DROP TABLE {tripal_organism_views_common_name}";
+    db_query($sql);
+  }
 }
 
 /**
-* This function simply defines all tables needed for the module to work
-* correctly.  By putting the table definitions in a separate function we
-* can easily provide the entire list for hook_install or individual
-* tables for an update.
-*
-* @ingroup tripal_organism
-*/
+ * This function simply defines all tables needed for the module to work
+ * correctly.  By putting the table definitions in a separate function we
+ * can easily provide the entire list for hook_install or individual
+ * tables for an update.
+ *
+ * @ingroup tripal_organism
+ */
 function tripal_organism_get_schemas() {
   $schema = array();
 
@@ -83,18 +83,18 @@ function tripal_organism_get_schemas() {
             'unsigned' => TRUE,
             'not null' => TRUE,
             'default' => 0
-         ),
+          ),
          'nid' => array(
             'type' => 'int',
             'unsigned' => TRUE,
             'not null' => TRUE,
             'default' => 0
-         ),
+          ),
          'organism_id' => array(
             'type' => 'int',
             'not null' => TRUE,
             'default' => 0
-         )
+          )
       ),
       'indexes' => array(
          'organism_id' => array('organism_id')
@@ -115,15 +115,15 @@ function tripal_organism_get_schemas() {
  * @ingroup tripal_organism
  */
 function tripal_organism_requirements($phase) {
-   $requirements = array();
-   if ($phase == 'install') {
-      if (!function_exists('tripal_create_moddir')) {
-         $requirements ['tripal_organism'] = array(
-            'title' => "tripal_organism",
-            'value' => "error. Some required modules are just being installed. Please try again.",
-            'severity' => REQUIREMENT_ERROR,
-         );
-      }
-   }
-   return $requirements;
+  $requirements = array();
+  if ($phase == 'install') {
+    if (!function_exists('tripal_create_moddir')) {
+      $requirements ['tripal_organism'] = array(
+        'title' => "tripal_organism",
+        'value' => "error. Some required modules are just being installed. Please try again.",
+        'severity' => REQUIREMENT_ERROR,
+      );
+    }
+  }
+  return $requirements;
 }

Tiedoston diff-näkymää rajattu, sillä se on liian suuri
+ 442 - 441
tripal_organism/tripal_organism.module


+ 14 - 14
tripal_organism/tripal_organism.views.inc

@@ -37,7 +37,7 @@ function tripal_organism_views_data()  {
     );
     foreach ($tables as $tablename) {
       if (!tripal_views_is_integrated($tablename, 10)) {
-        $table_integration_array = tripal_views_get_integration_array_for_chado_table($tablename,TRUE);
+        $table_integration_array = tripal_views_get_integration_array_for_chado_table($tablename, TRUE);
         tripal_views_integration_add_entry($table_integration_array);
       }
     }
@@ -49,7 +49,7 @@ function tripal_organism_views_data()  {
     );
     foreach ($tables as $tablename) {
       if (!tripal_views_is_integrated($tablename, 10)) {
-        $table_integration_array = tripal_views_get_integration_array_for_chado_table($tablename,FALSE);
+        $table_integration_array = tripal_views_get_integration_array_for_chado_table($tablename, FALSE);
         tripal_views_integration_add_entry($table_integration_array);
       }
     }
@@ -68,19 +68,19 @@ function tripal_organism_views_data()  {
  * @ingroup tripal_organism_views
  */
 function tripal_organism_views_handlers() {
- return array(
-   'info' => array(
-     'path' => drupal_get_path('module', 'tripal_organism') . '/views/handlers',
-   ),
-   'handlers' => array(
-     'views_handler_field_computed_organism_nid' => array(
-       'parent' => 'views_handler_field_numeric',
-     ),
-     'views_handler_filter_organism_common_name' => array(
+  return array(
+    'info' => array(
+      'path' => drupal_get_path('module', 'tripal_organism') . '/views/handlers',
+    ),
+    'handlers' => array(
+      'views_handler_field_computed_organism_nid' => array(
+        'parent' => 'views_handler_field_numeric',
+      ),
+      'views_handler_filter_organism_common_name' => array(
       'parent' => 'views_handler_filter_string',
-     ),
-   ),
- );
+    ),
+    ),
+  );
 }
 
 /**

+ 2 - 2
tripal_phenotype/tripal_phenotype.module

@@ -16,7 +16,7 @@
  *  views integration code is
  */
 function tripal_phenotype_views_api() {
-   return array(
+  return array(
       'api' => 2.0,
-   );
+  );
 }

+ 13 - 13
tripal_phenotype/tripal_phenotype.views.inc

@@ -6,17 +6,17 @@
  *  chado/tripal_phenotype tables. Supplementary functions can be found in
  *  ./views/
  *
- *  Documentation on views integration can be found at 
+ *  Documentation on views integration can be found at
  *  http://views2.logrus.com/doc/html/index.html.
  */
- 
+
 /*************************************************************************
  * Implements hook_views_data()
  * Purpose: Describe chado/tripal tables & fields to views
  *
  * @return: a data array which follows the structure outlined in the
  *   views2 documentation for this hook. Essentially, it's an array of table
- *   definitions keyed by chado/tripal table name. Each table definition 
+ *   definitions keyed by chado/tripal table name. Each table definition
  *   includes basic details about the table, fields in that table and
  *   relationships between that table and others (joins)
  */
@@ -29,41 +29,41 @@ function tripal_phenotype_views_data()  {
     );
     foreach ($tables as $tablename) {
       if (!tripal_views_is_integrated($tablename, 10)) {
-        $table_integration_array = tripal_views_get_integration_array_for_chado_table($tablename,TRUE);
+        $table_integration_array = tripal_views_get_integration_array_for_chado_table($tablename, TRUE);
         tripal_views_integration_add_entry($table_integration_array);
       }
     }
-        
+
     $tables = array(
       'feature_phenotype',
       'phenotype_cvterm'
     );
     foreach ($tables as $tablename) {
       if (!tripal_views_is_integrated($tablename, 10)) {
-        $table_integration_array = tripal_views_get_integration_array_for_chado_table($tablename,FALSE);
+        $table_integration_array = tripal_views_get_integration_array_for_chado_table($tablename, FALSE);
         tripal_views_integration_add_entry($table_integration_array);
       }
     }
   }
-  
+
   return $data;
 }
 
 /*************************************************************************
  * Implements hook_views_handlers()
  * Purpose: Register all custom handlers with views
- *   where a handler describes either "the type of field", 
+ *   where a handler describes either "the type of field",
  *   "how a field should be filtered", "how a field should be sorted"
  *
  * @return: An array of handler definitions
  */
 function tripal_phenotype_views_handlers() {
- return array(
+  return array(
    'info' => array(
      'path' => drupal_get_path('module', 'tripal_phenotype') . '/views/handlers',
-   ),
+  ),
    'handlers' => array(
 
-   ),
- );
-}
+  ),
+  );
+}

+ 3 - 3
tripal_project/tripal_project.admin.inc

@@ -5,10 +5,10 @@
  */
 
 function tripal_project_administration_description_page() {
- $output = '';
+  $output = '';
 
 
- return $output;
+  return $output;
 }
 
 function tripal_project_configuration_page() {
@@ -91,7 +91,7 @@ function tripal_project_sync_all_projects() {
       $node = node_submit($new_node);
       node_save($node);
       if ($node->nid) {
-         print "Added " . $project[0]->name . " (Node ID:" . $node->nid . ")\n";
+        print "Added " . $project[0]->name . " (Node ID:" . $node->nid . ")\n";
       }
     }
     else {

+ 3 - 3
tripal_project/tripal_project.install

@@ -11,21 +11,21 @@
  */
 
 /**
- * Implementation of hook_install()
+ * Implementation of hook_install().
  */
 function tripal_project_install() {
   drupal_install_schema('tripal_project');
 }
 
 /**
- * Implementation of hook_uninstall()
+ * Implementation of hook_uninstall().
  */
 function tripal_project_uninstall() {
   drupal_uninstall_schema('tripal_project');
 }
 
 /**
- * Implementation of hook_schema()
+ * Implementation of hook_schema().
  */
 function tripal_project_schema() {
 

+ 63 - 63
tripal_project/tripal_project.module

@@ -25,9 +25,9 @@ require('tripal_project.admin.inc');
  *
  */
 function tripal_project_views_api() {
-   return array(
+  return array(
       'api' => 2.0,
-   );
+  );
 }
 
 /**
@@ -35,14 +35,14 @@ function tripal_project_views_api() {
  */
 function tripal_project_menu() {
   $items[ 'admin/tripal/tripal_project' ]= array(
-    'title' => t('Projects'),
+    'title' => 'Projects',
     'page callback' => 'tripal_project_administration_description_page',
     'access arguments' => array('administer site configuration'),
     'type' => MENU_NORMAL_ITEM
   );
 
   $items[ 'admin/tripal/tripal_project/configuration' ]= array(
-    'title' => t('Configuration'),
+    'title' => 'Configuration',
     'page callback' => 'tripal_project_configuration_page',
     'access arguments' => array('administer site configuration'),
     'type' => MENU_NORMAL_ITEM
@@ -99,10 +99,10 @@ function chado_project_access($op, $node, $account) {
   if ($op == 'update' || $op == 'delete') {
 
     if (!user_access('edit own chado_projects', $account)) {
-       return FALSE;
+      return FALSE;
     }
     if (user_access('edit own chado_projects', $account) &&
-       $account->uid != $node->uid) {
+      $account->uid != $node->uid) {
       return FALSE;
     }
   }
@@ -120,13 +120,13 @@ function chado_project_access($op, $node, $account) {
 //-----------------------------------------------------------------------------
 
 /**
-* Implementation of hook_node_info()
-*
-* This node_info, is a simple node that describes the functionallity of the module. It specifies
-* that the title(Project Name) and body(Description) set to true so that they information can be
-* entered
-*
-*/
+ * Implementation of hook_node_info().
+ *
+ * This node_info, is a simple node that describes the functionallity of the module. It specifies
+ * that the title(Project Name) and body(Description) set to true so that they information can be
+ * entered
+ *
+ */
 function tripal_project_node_info() {
   return array(
     'chado_project' => array(
@@ -142,21 +142,21 @@ function tripal_project_node_info() {
 }
 
 /**
-* Implementation of hook_form().
-*
-*  This form takes the Project Title information and description from the user.
-*
-*  @parm &$node
-*    The initialized node
-*
-*  @parm $form_state
-*    The state of the form, that has the user entered information that is neccessary for adding
-*    information to the project
-*
-*  @return $form
-*    An array as described by the Drupal Form API
-*
-*/
+ * Implementation of hook_form().
+ *
+ *  This form takes the Project Title information and description from the user.
+ *
+ *  @parm &$node
+ *    The initialized node
+ *
+ *  @parm $form_state
+ *    The state of the form, that has the user entered information that is neccessary for adding
+ *    information to the project
+ *
+ *  @return $form
+ *    An array as described by the Drupal Form API
+ *
+ */
 function chado_project_form(&$node, $form_state) {
 
   $type = node_get_types('type', $node);
@@ -193,23 +193,23 @@ function chado_project_form(&$node, $form_state) {
 }
 
 /**
-* Implementation of hook_insert()
-*
-*  @parm $node
-*    Then node that has the information stored within, accessed given the nid
-*
-*/
+ * Implementation of hook_insert().
+ *
+ *  @parm $node
+ *    Then node that has the information stored within, accessed given the nid
+ *
+ */
 function chado_project_insert($node) {
 
   $values =  array(
      'name' => $node->title,
      'description' => $node->description,
-   );
+  );
 
-   if (!$node->project_id) {
+  if (!$node->project_id) {
      //inserts info into chado table.
-     $result = tripal_core_chado_insert('project', $values);
-     $node->project_id = $result['project_id'];
+  $result = tripal_core_chado_insert('project', $values);
+  $node->project_id = $result['project_id'];
   }
 
   //inserts the row of vid,nid,project_id into the chado_project table
@@ -218,21 +218,21 @@ function chado_project_insert($node) {
 }
 
 /**
-*
-* Implementation of hook_delete().
-*
-* @param $node
-* The node which is to be deleted, only chado project and chado_project need to be dealt with
-* since the drupal node is deleted automagically
-*
-*/
+ *
+ * Implementation of hook_delete().
+ *
+ * @param $node
+ * The node which is to be deleted, only chado project and chado_project need to be dealt with
+ * since the drupal node is deleted automagically
+ *
+ */
 function chado_project_delete($node) {
   // Notice that we're matching all revision, by using the node's nid.
 
   // Find the project to delete
   $values =  array(
      'project_id' => $node->project->project_id,
-   );
+  );
   tripal_core_chado_delete('project', $values);
 
   //deleteing in drupal chado_project table
@@ -241,13 +241,13 @@ function chado_project_delete($node) {
 }
 
 /**
-* Implements hook_update()
-*
-* @param $node
-*  The node which is to have its containing information updated when the user modifies information
-*  pertaining to the specific project
-*
-*/
+ * Implements hook_update().
+ *
+ * @param $node
+ *  The node which is to have its containing information updated when the user modifies information
+ *  pertaining to the specific project
+ *
+ */
 function chado_project_update($node) {
 
   // Find the project to update
@@ -266,15 +266,15 @@ function chado_project_update($node) {
 }
 
 /**
-* Implementation of node_load().
-*
-* @param $node
-*   The node that is to have its containing information loaded
-*
-* @return $node
-*   The node, containing the loaded project with the current nid
-*
-*/
+ * Implementation of node_load().
+ *
+ * @param $node
+ *   The node that is to have its containing information loaded
+ *
+ * @return $node
+ *   The node, containing the loaded project with the current nid
+ *
+ */
 function chado_project_load($node) {
 
   //selecting the coresponding table information

+ 7 - 7
tripal_project/tripal_project.views.inc

@@ -29,7 +29,7 @@ function tripal_project_views_data()  {
     );
     foreach ($tables as $tablename) {
       if (!tripal_views_is_integrated($tablename, 10)) {
-        $table_integration_array = tripal_views_get_integration_array_for_chado_table($tablename,TRUE);
+        $table_integration_array = tripal_views_get_integration_array_for_chado_table($tablename, TRUE);
         tripal_views_integration_add_entry($table_integration_array);
       }
     }
@@ -38,7 +38,7 @@ function tripal_project_views_data()  {
     );
     foreach ($tables as $tablename) {
       if (!tripal_views_is_integrated($tablename, 10)) {
-        $table_integration_array = tripal_views_get_integration_array_for_chado_table($tablename,FALSE);
+        $table_integration_array = tripal_views_get_integration_array_for_chado_table($tablename, FALSE);
         tripal_views_integration_add_entry($table_integration_array);
       }
     }
@@ -56,12 +56,12 @@ function tripal_project_views_data()  {
  * @return: An array of handler definitions
  */
 function tripal_project_views_handlers() {
- return array(
+  return array(
    'info' => array(
      'path' => drupal_get_path('module', 'tripal_project') . '/views/handlers',
-   ),
+  ),
    'handlers' => array(
 
-   ),
- );
-}
+  ),
+  );
+}

+ 5 - 6
tripal_pub/tripal_pub.install

@@ -12,7 +12,7 @@
 
 
 /**
- * Implementation of hook_install()
+ * Implementation of hook_install().
  */
 function tripal_pub_install() {
 
@@ -20,14 +20,13 @@ function tripal_pub_install() {
   $dbxref = array('accession' => 'abstract', 'db_id' => array('name' => 'tripal'));
   $success = tripal_core_chado_insert('dbxref', $dbxref);
   if ($success) {
-    tripal_core_chado_insert('cvterm', array('name' => 'abstract', 'cv_id' => array('name' => 'tripal'), 'db
-xref_id' => $dbxref));
+    tripal_core_chado_insert('cvterm', array('name' => 'abstract', 'cv_id' => array('name' => 'tripal'), 'dbxref_id' => $dbxref));
   }
 }
 
 
 /**
- * Implementation of hook_uninstall()
+ * Implementation of hook_uninstall().
  */
 function tripal_pub_uninstall() {
   //Remove tables
@@ -37,7 +36,7 @@ function tripal_pub_uninstall() {
 
 
 /**
- * Implementation of hook_schema()
+ * Implementation of hook_schema().
  */
 function tripal_pub_schema() {
 //specification for 'tripal_pub_instances'
@@ -78,7 +77,7 @@ function tripal_pub_schema() {
         'default' => '',
         'description' => 'The Author Name.',
       ),
-     ),
+      ),
      //end of shema
 
     'primary key' => array('nid'),

Tiedoston diff-näkymää rajattu, sillä se on liian suuri
+ 483 - 491
tripal_pub/tripal_pub.module


+ 13 - 13
tripal_pub/tripal_pub.views.inc

@@ -6,17 +6,17 @@
  *  chado/tripal_pub tables. Supplementary functions can be found in
  *  ./views/
  *
- *  Documentation on views integration can be found at 
+ *  Documentation on views integration can be found at
  *  http://views2.logrus.com/doc/html/index.html.
  */
- 
+
 /*************************************************************************
  * Implements hook_views_data()
  * Purpose: Describe chado/tripal tables & fields to views
  *
  * @return: a data array which follows the structure outlined in the
  *   views2 documentation for this hook. Essentially, it's an array of table
- *   definitions keyed by chado/tripal table name. Each table definition 
+ *   definitions keyed by chado/tripal table name. Each table definition
  *   includes basic details about the table, fields in that table and
  *   relationships between that table and others (joins)
  */
@@ -29,11 +29,11 @@ function tripal_pub_views_data()  {
     );
     foreach ($tables as $tablename) {
       if (!tripal_views_is_integrated($tablename, 10)) {
-        $table_integration_array = tripal_views_get_integration_array_for_chado_table($tablename,TRUE);
+        $table_integration_array = tripal_views_get_integration_array_for_chado_table($tablename, TRUE);
         tripal_views_integration_add_entry($table_integration_array);
       }
     }
-        
+
     $tables = array(
       'pub_dbxref',
       'pub_relationship',
@@ -42,30 +42,30 @@ function tripal_pub_views_data()  {
     );
     foreach ($tables as $tablename) {
       if (!tripal_views_is_integrated($tablename, 10)) {
-        $table_integration_array = tripal_views_get_integration_array_for_chado_table($tablename,FALSE);
+        $table_integration_array = tripal_views_get_integration_array_for_chado_table($tablename, FALSE);
         tripal_views_integration_add_entry($table_integration_array);
       }
     }
   }
-  
+
   return $data;
 }
 
 /*************************************************************************
  * Implements hook_views_handlers()
  * Purpose: Register all custom handlers with views
- *   where a handler describes either "the type of field", 
+ *   where a handler describes either "the type of field",
  *   "how a field should be filtered", "how a field should be sorted"
  *
  * @return: An array of handler definitions
  */
 function tripal_pub_views_handlers() {
- return array(
+  return array(
    'info' => array(
      'path' => drupal_get_path('module', 'tripal_pub') . '/views/handlers',
-   ),
+    ),
    'handlers' => array(
 
-   ),
- );
-}
+    ),
+  );
+}

+ 8 - 0
tripal_search/tripal_search.coder_ignores.txt

@@ -0,0 +1,8 @@
+; The file should be formatted this way :
+; file:line:warning-type
+; where warning-type is one of security, style, sql, i18n, comment, etc.
+
+; Can't use db placeholders in this case since the variable contains the SQL describing
+; a join and this would be sanitized if that was added through a placeholder
+tripal_search.module:126:sql
+tripal_search.module:136:sql

+ 28 - 15
tripal_search/tripal_search.module

@@ -7,15 +7,15 @@
 //
 // Copyright 2009 Clemson University
 //
-/*******************************************************************************
+/**
  * Tripal Search initiation
- ******************************************************************************/
+ */
 function tripal_search_init() {
-   // Add javascript
-   drupal_add_js(drupal_get_path('theme', 'tripal') .
+  // Add javascript
+  drupal_add_js(drupal_get_path('theme', 'tripal') .
                                   '/js/tripal_search.js');
 }
-/*******************************************************************************
+/**
  *  Tripal Search adds advanced search functions to Drupal's Search module
  */
 function tripal_search_menu() {
@@ -33,8 +33,8 @@ function tripal_search_menu() {
   return $items;
 }
 
-/*******************************************************************************
- * Implementation of hook_form_alter
+/**
+ * Implementation of hook_form_alter().
  */
 function tripal_search_form_alter(&$form, $form_state, $form_id) {
   if ($form_id == 'search_form' && arg(2)) {
@@ -42,10 +42,10 @@ function tripal_search_form_alter(&$form, $form_state, $form_id) {
     $get = drupal_query_string_encode($_GET, array('q'));
     if (preg_match("/node/", arg(1))) {
       $form['basic']['inline']['fasta'] = array('#type' => 'markup',
-          '#value' => "<br><br><a id=\"tripal_search_link\" href=\"".
+          '#value' => "<br /><br /><a id=\"tripal_search_link\" href=\"".
                       url('tripal_search/'. arg(1) .'/'. urlencode(search_get_keys()),
                       array('query' => trim($get)?$get:NULL)) .
-                      "\">Download features (multi-FASTA format)</a><br><br>");
+                      "\">Download features (multi-FASTA format)</a><br /><br />");
 
     }
   }
@@ -82,12 +82,12 @@ function tripal_search_file($type, $keys, $results) {
     $sqld = "SELECT * FROM {chado_feature} CF INNER JOIN {node} N on N.nid = CF.nid WHERE CF.nid = %d";
     if ($f_objd = db_fetch_object(db_query($sqld, $result->sid))) {
 
-       // Get sequence from chado database
-       $previous_db = tripal_db_set_active('chado');  // use chado database
-       $sqlc = "SELECT * FROM {feature} WHERE feature_id = '%s'";
-       $f_objc = db_fetch_object(db_query($sqlc, $f_objd->feature_id));
-       tripal_db_set_active($previous_db);  // now use drupal database
-       print tripal_feature_return_fasta($f_objc, $desc);
+      // Get sequence from chado database
+      $previous_db = tripal_db_set_active('chado');  // use chado database
+      $sqlc = "SELECT * FROM {feature} WHERE feature_id = '%s'";
+      $f_objc = db_fetch_object(db_query($sqlc, $f_objd->feature_id));
+      tripal_db_set_active($previous_db);  // now use drupal database
+      print tripal_feature_return_fasta($f_objc, $desc);
     }
   }
 }
@@ -122,6 +122,7 @@ function tripal_do_search($keywords, $type, $join1 = '', $where1 = '1 = 1', $arg
   }
 
   // Calculate maximum keyword relevance, to normalize it.
+  // @coder-ignore: can't use placeholders since variable defines a join
   $select = "SELECT SUM(i.score * t.count) AS score FROM {search_index} i " . $join . " WHERE $conditions GROUP BY i.type, i.sid HAVING COUNT(*) >= %d ORDER BY score DESC";
   $arguments = array_merge($arguments1, array($query[4]));
   $normalize = db_result(db_query_range($select, $arguments, 0, 1));
@@ -131,6 +132,7 @@ function tripal_do_search($keywords, $type, $join1 = '', $where1 = '1 = 1', $arg
   $columns2 = str_replace('i.relevance', '('. (1.0 / $normalize) .' * SUM(i.score * t.count))', $columns2);
 
   // Build query to retrieve results.
+  // @coder-ignore: can't use placeholders since variable defines a join
   $select = "SELECT i.type, i.sid, $columns2 FROM {search_index} i " . $join . " " . $join2 . " WHERE $conditions GROUP BY i.type, i.sid HAVING COUNT(*) >= %d";
   $count_select =  "SELECT COUNT(*) FROM ($select) n1";
   $arguments = array_merge($arguments2, $arguments1, array($query[4]));
@@ -144,3 +146,14 @@ function tripal_do_search($keywords, $type, $join1 = '', $where1 = '1 = 1', $arg
   }
   return $results;
 }
+
+/**
+ * Implements hook_coder_ignore().
+ * Defines the path to the file (tripal_search.coder_ignores.txt) where ignore rules for coder are stored
+ */
+function tripal_search_coder_ignore() {
+  return array(
+    'path' => drupal_get_path('module', 'tripal_search'),
+    'line prefix' => drupal_get_path('module', 'tripal_search'),
+  );
+}

+ 3 - 3
tripal_stock/other_module_api_functions.inc

@@ -35,11 +35,11 @@ function get_max_chado_rank($tablename, $where_options) {
     if (preg_match('/INT/', $val_array['type'])) {
       $where[] = $key . "=" . $val_array['value'];
     }
-     else {
+    else {
       if ($val_array['exact']) {
-      $operator='='; }
+        $operator='='; }
       else { $operator='~'; }
-      $where[] = $key . $operator . "'" . $val_array['value'] . "'";
+        $where[] = $key . $operator . "'" . $val_array['value'] . "'";
     }
   }
 

+ 147 - 147
tripal_stock/tripal_stock-administration.inc

@@ -17,8 +17,8 @@ function tripal_stock_module_description_page() {
 
   $text = '<h3>Tripal Stock Administrative Tools Quick Links</h3>';
     $text .= '<ul>';
-      $text .= '<li>' . l('Configuration', 'admin/tripal/tripal_stock/configuration') . '</li>';
-      $text .= '<li>' . l('Stock Listing', 'stocks') . '</li>';
+      $text .= '<li>' . l(t('Configuration'), 'admin/tripal/tripal_stock/configuration') . '</li>';
+      $text .= '<li>' . l(t('Stock Listing'), 'stocks') . '</li>';
     $text .= '</ul>';
 
   $text .= '<h3>Module Description:</h3>';
@@ -81,8 +81,8 @@ function tripal_stock_module_description_page() {
   $text .= '<p>In order to access a more flexible listing of stocks you must first install the <a href="http://drupal.org/project/views">Drupal Views2 module</a>. You should then be able to access the default views <a href="../build/views/">here</a>. Essentially, Views is a module which allows you to create custom SQL queries completely through the web interface without knowing SQL. Furthermore, it also does some formatting of the results allowing you to display them as HTML lists, tables or grids. You can also expose filters to the user to let them customize the results they see and even implement various sorting.</p>';
   $text .= '<p>To use one of the Default Views simply click "Enable" and then "Edit" to change it to show exactly what you want. To view the current listing simply clikc "View Page" at the top of the Edit user interface. There are a number of good tutorials out there for Views2, any of which can be used to help you create your own custom listings of biological content. (Note: there aren\'t any tutorials specifically for tripal content but any tutorial for Views2 will show you how to use the views interface.</p></li>';
 
-   $text .= '<h3>Page Customizations</h3>';
-   $text .= '<p>There are several ways to customize the look-and-feel for the way Chado data is presented through Tripal.
+  $text .= '<h3>Page Customizations</h3>';
+  $text .= '<p>There are several ways to customize the look-and-feel for the way Chado data is presented through Tripal.
              Below is a description of several methods.  These methods may be used in conjunction with one another to
              provide fine-grained control.
              <ul>
@@ -148,90 +148,90 @@ function tripal_stock_module_description_page() {
 function tripal_stock_admin() {
   $form = array();
 
-   // before proceeding check to see if we have any
-   // currently processing jobs. If so, we don't want
-   // to give the opportunity to sync Stocks
-   $active_jobs = FALSE;
-   if (tripal_get_module_active_jobs('tripal_stock')) {
-      $active_jobs = TRUE;
-   }
-   if ($active_jobs) {
-
-   $form['notice'] = array(
-         '#type' => 'fieldset',
-         '#title' => t('Stock Management Temporarily Unavailable')
-      );
-
-   $form['notice']['message'] = array(
-         '#value' => t("Currently, stock management jobs are waiting or ".
-            "are running. Managemment features have been hidden until these ".
-            "jobs complete.  Please check back later once these jobs have ".
-            "finished.  You can view the status of pending jobs in the Tripal ".
-            "jobs page."),
-      );
-
-   }
-   else {
-
-   // SET Vocabularies -----------------------------------------------------------------------------------------
-   $form['set_cv'] = array(
+  // before proceeding check to see if we have any
+  // currently processing jobs. If so, we don't want
+  // to give the opportunity to sync Stocks
+  $active_jobs = FALSE;
+  if (tripal_get_module_active_jobs('tripal_stock')) {
+    $active_jobs = TRUE;
+  }
+  if ($active_jobs) {
+
+  $form['notice'] = array(
+       '#type' => 'fieldset',
+       '#title' => t('Stock Management Temporarily Unavailable')
+    );
+
+  $form['notice']['message'] = array(
+       '#value' => t("Currently, stock management jobs are waiting or ".
+          "are running. Managemment features have been hidden until these ".
+          "jobs complete.  Please check back later once these jobs have ".
+          "finished.  You can view the status of pending jobs in the Tripal ".
+          "jobs page."),
+    );
+
+  }
+  else {
+
+    // SET Vocabularies -----------------------------------------------------------------------------------------
+    $form['set_cv'] = array(
       '#type' => 'fieldset',
       '#title' => t('Set Stock Controlled Vocabularies'),
       '#weight' => -10
-   );
+    );
 
-   $form['set_cv']['message'] = array(
+    $form['set_cv']['message'] = array(
          '#value' => t("This setting allows you to set which chado controlled vocabularies (cv)"
                 ." are used. Cvs are used to control user input for the type of stock,"
           ." any properties they enter for a stock & the types of relationships"
           ." between stocks. Only cvs already loaded into chado can be selected here.")
-   );
+    );
 
-   $cv_options = tripal_cv_get_cv_options();
+    $cv_options = tripal_cv_get_cv_options();
 
-   $form['set_cv']['stock_types_cv'] = array(
+    $form['set_cv']['stock_types_cv'] = array(
      '#type' => 'select',
      '#title' => t('Controlled Vocabulary governing Stock Types'),
      '#options' => $cv_options,
      '#default_value' => variable_get('chado_stock_types_cv', 0)
-   );
+    );
 
-   $form['set_cv']['stock_prop_types_cv'] = array(
+    $form['set_cv']['stock_prop_types_cv'] = array(
      '#type' => 'select',
      '#title' => t('Controlled Vocabulary governing Types of Stock Properties'),
      '#description' => t("This cv must contain a cvterm entry where name='synonym'."),
      '#options' => $cv_options,
      '#default_value' => variable_get('chado_stock_prop_types_cv', 0)
-   );
+    );
 
-   $form['set_cv']['stock_relationship_cv'] = array(
+    $form['set_cv']['stock_relationship_cv'] = array(
      '#type' => 'select',
      '#title' => t('Controlled Vocabulary governing Types of Relationsips between Stocks'),
      '#options' => $cv_options,
      '#default_value' => variable_get('chado_stock_relationship_cv', 0)
-   );
+    );
 
-   $form['set_cv']['button'] = array(
+    $form['set_cv']['button'] = array(
       '#type' => 'submit',
       '#value' => t('Set Controlled Vacabularies')
-   );
+    );
 
-   // SYNC STOCKS-----------------------------------------------------------------------------------------------
-   $form['sync'] = array(
+    // SYNC STOCKS-----------------------------------------------------------------------------------------------
+    $form['sync'] = array(
       '#type' => 'fieldset',
       '#title' => t('Sync Stocks'),
       '#weight' => -10
-   );
+    );
 
-   $form['sync']['description'] = array(
+    $form['sync']['description'] = array(
       '#type' => 'item',
       '#value' => t("Click the 'Sync all Germplasm' button to create Drupal ".
          "content for stocks in chado. Depending on the ".
          "number of stocks in the chado database this may take a long ".
          "time to complete. ")
-   );
+    );
 
-   $form['sync']['organisms'] = array(
+    $form['sync']['organisms'] = array(
       '#type' => 'checkboxes',
       '#title' => t('Organisms for which Stocks should be sync\'d'),
       '#description' => t('Only sync\'d Organisms are listed. Leaving an organism unchecked does not delete already sync\'d Stocks.'),
@@ -239,13 +239,13 @@ function tripal_stock_admin() {
       '#required'    => FALSE,
       '#prefix'      => '<div id="lib_boxes">',
       '#suffix'      => '</div>'
-   );
+    );
 
-   $form['sync']['button'] = array(
+    $form['sync']['button'] = array(
       '#type' => 'submit',
       '#value' => t('Sync Stocks')
-   );
-}
+    );
+  }
 
   return system_settings_form($form);
 
@@ -262,31 +262,31 @@ function tripal_stock_admin() {
  * @ingroup tripal_stock
  */
 function tripal_stock_admin_validate($form, &$form_state) {
-   global $user;  // we need access to the user info
-   $job_args = array();
-
-   // Sync Stocks
-   if ($form_state['values']['op'] == t('Sync Stocks')) {
-      // Array organism_id => organims common_name
-      //  which only includes those organisms which the user wants to select stocks for
-      $organisms_2b_syncd = $form_state['values']['organisms'];
-
-      //for each organism selected submit job (handled by tripal_stock_sync_stock_set)
-      //  which syncs all stocks with an organism_id equal to the selelcted organism
-      foreach ( $organisms_2b_syncd as $organism_id ) {
-        if ($organism_id != 0) {
-          $job_args[0] = $organism_id;
-          tripal_add_job("Sync Stocks from Organism $organism_id", 'tripal_stock',
-            'tripal_stock_sync_stock_set', $job_args, $user->uid);
-        }
+  global $user;  // we need access to the user info
+  $job_args = array();
+
+  // Sync Stocks
+  if ($form_state['values']['op'] == t('Sync Stocks')) {
+    // Array organism_id => organims common_name
+    //  which only includes those organisms which the user wants to select stocks for
+    $organisms_2b_syncd = $form_state['values']['organisms'];
+
+    //for each organism selected submit job (handled by tripal_stock_sync_stock_set)
+    //  which syncs all stocks with an organism_id equal to the selelcted organism
+    foreach ( $organisms_2b_syncd as $organism_id ) {
+      if ($organism_id != 0) {
+        $job_args[0] = $organism_id;
+        tripal_add_job("Sync Stocks from Organism $organism_id", 'tripal_stock',
+          'tripal_stock_sync_stock_set', $job_args, $user->uid);
       }
     }
+  }
 
-    if ($form_state['values']['op'] == t('Set Controlled Vacabularies')) {
-      variable_set('chado_stock_types_cv', $form_state['values']['stock_types_cv']);
-      variable_set('chado_stock_prop_types_cv', $form_state['values']['stock_prop_types_cv']);
-      variable_set('chado_stock_relationship_cv', $form_state['values']['stock_relationship_cv']);
-    }
+  if ($form_state['values']['op'] == t('Set Controlled Vacabularies')) {
+    variable_set('chado_stock_types_cv', $form_state['values']['stock_types_cv']);
+    variable_set('chado_stock_prop_types_cv', $form_state['values']['stock_prop_types_cv']);
+    variable_set('chado_stock_relationship_cv', $form_state['values']['stock_relationship_cv']);
+  }
 }
 
 /**
@@ -304,7 +304,7 @@ function tripal_stock_admin_validate($form, &$form_state) {
  *
  * @ingroup tripal_stock
  */
- function tripal_stock_sync_stock_set($organism_id, $job_id) {
+function tripal_stock_sync_stock_set($organism_id, $job_id) {
   global $user;
 
   if (!$organism_id) {
@@ -312,86 +312,86 @@ function tripal_stock_admin_validate($form, &$form_state) {
   }
   else {
 
-    // Get list of stocks to sync
-    $previous_db = tripal_db_set_active('chado');
-    $result = db_query(
-       "SELECT stock_id, uniquename, type_id, organism_id FROM {stock} WHERE organism_id=%d",
-       $organism_id
+  // Get list of stocks to sync
+  $previous_db = tripal_db_set_active('chado');
+  $result = db_query(
+     "SELECT stock_id, uniquename, type_id, organism_id FROM {stock} WHERE organism_id=%d",
+      $organism_id
+  );
+  tripal_db_set_active($previous_db);
+
+  $stocks_created_count = 0; //keeps track of total number of stocks successfully created
+  $stocks_attempted = 0;
+  // foreach stock to be sync'd -> create node & add stock_id
+  while ( $r = db_fetch_object($result) ) {
+    // $r is the current stock to be sync'd
+    $stocks_attempted++;
+
+    print 'Processing ' . $r->uniquename . "... ";
+
+    // check not already in drupal
+    $in_drupal_query = db_query(
+      "SELECT * FROM {chado_stock} WHERE stock_id=%d",
+      $r->stock_id
     );
-    tripal_db_set_active($previous_db);
-
-    $stocks_created_count = 0; //keeps track of total number of stocks successfully created
-    $stocks_attempted = 0;
-    // foreach stock to be sync'd -> create node & add stock_id
-    while ( $r = db_fetch_object($result) ) {
-      // $r is the current stock to be sync'd
-      $stocks_attempted++;
-
-      print 'Processing ' . $r->uniquename . "... ";
-
-      // check not already in drupal
-      $in_drupal_query = db_query(
-        "SELECT * FROM {chado_stock} WHERE stock_id=%d",
-         $r->stock_id
-      );
-      if ( !db_fetch_object($in_drupal_query) ) {
-
-        //create new chado_stock node
-        $new_node = new stdClass();
-         $new_node->type = 'chado_stock';
-        $new_node->uid = $user->uid;
-         $new_node->title = $r->uniquename;
-         $new_node->type_id = $r->type_id;
-         $new_node->organism_id = $r->organism_id;
-         $new_node->stock_id = $r->stock_id;
-        $new_node->chado_stock_exists = TRUE;
-
-         //print 'New Node:';
-         //print_r($new_node);
-
-         node_validate($new_node);
-
-        if (!form_get_errors()) {
-          //print 'Try to Create Node ';
-          $node = node_submit($new_node);
-          node_save($node);
-          if ($node->nid) {
-            $stocks_created_count++;
-
-            //Add stock id to chado_stock table
-            /**
-             db_query(
-               "INSERT INTO chado_stock (stock_id, nid, vid) VALUES (%d, %d, %d)",
-               $r->stock_id,
-               $node->nid,
-               $node->vid
-             );
-             */
-          }
+    if ( !db_fetch_object($in_drupal_query) ) {
+
+      //create new chado_stock node
+      $new_node = new stdClass();
+      $new_node->type = 'chado_stock';
+      $new_node->uid = $user->uid;
+      $new_node->title = $r->uniquename;
+      $new_node->type_id = $r->type_id;
+      $new_node->organism_id = $r->organism_id;
+      $new_node->stock_id = $r->stock_id;
+      $new_node->chado_stock_exists = TRUE;
+
+      //print 'New Node:';
+      //print_r($new_node);
+
+      node_validate($new_node);
+
+      if (!form_get_errors()) {
+        //print 'Try to Create Node ';
+        $node = node_submit($new_node);
+        node_save($node);
+        if ($node->nid) {
+          $stocks_created_count++;
+
+          //Add stock id to chado_stock table
+          /**
+           db_query(
+             "INSERT INTO chado_stock (stock_id, nid, vid) VALUES (%d, %d, %d)",
+             $r->stock_id,
+             $node->nid,
+             $node->vid
+           );
+           */
         }
-        else {
-          print "Not completed due to errors:\nCreate Stock Form Errors: ";
-           print_r(form_get_errors());
-        }
-         print "Nid=" . $node->nid . "\n";
       }
       else {
-        print "Skipped $r->uniquename because it's already in drupal.\n";
-      } //end of if not already in drupal
-    } //end of while still stocks to be sync'd
+        print "Not completed due to errors:\nCreate Stock Form Errors: ";
+        print_r(form_get_errors());
+      }
+        print "Nid=" . $node->nid . "\n";
+    }
+    else {
+      print "Skipped $r->uniquename because it's already in drupal.\n";
+    } //end of if not already in drupal
+  } //end of while still stocks to be sync'd
   } //end of if organism_id not supplied
 
   if ($stocks_attempted == 0) {
-    print "No stocks retrieved for organism (" . $organism_id . ")\n";
+  print "No stocks retrieved for organism (" . $organism_id . ")\n";
+  return 1;
+  }
+  else {
+  if ($stocks_created_count > 0) {
+    print "$stocks_created_count Stocks Successfully Created\n";
     return 1;
   }
   else {
-    if ($stocks_created_count > 0) {
-      print "$stocks_created_count Stocks Successfully Created\n";
-      return 1;
-    }
-    else {
-      return 0;
-    }
+    return 0;
+  }
   }
 }

+ 25 - 25
tripal_stock/tripal_stock-db_references.inc

@@ -20,13 +20,13 @@
 function tripal_stock_add_ALL_dbreferences_page($node) {
   $output = '';
 
-  $output .= tripal_stock_add_chado_properties_progress('db_references') . '<br>';
-  $output .= '<b>All Database References should strictly pertain to THE CURRENT Individual</b><br>';
-  $output .= '<br>';
+  $output .= tripal_stock_add_chado_properties_progress('db_references') . '<br />';
+  $output .= '<b>All Database References should strictly pertain to THE CURRENT Individual</b><br />';
+  $output .= '<br />';
   $output .= theme('tripal_stock_references', $node);
-  $output .= '<br><br>';
+  $output .= '<br /><br />';
   $output .= drupal_get_form('tripal_stock_add_ONE_dbreference_form', $node);
-  $output .= '<br>';
+  $output .= '<br />';
   $output .= drupal_get_form('tripal_stock_add_chado_properties_navigate', 'db_references', $node->nid);
   return $output;
 }
@@ -182,10 +182,10 @@ function tripal_stock_add_ONE_dbreference_form_submit($form, &$form_state) {
       );
       tripal_db_set_active($previous_db);
 
-      drupal_set_message('Successfully Added Database Reference');
+      drupal_set_message(t('Successfully Added Database Reference'));
     }
     else {
-      drupal_set_message('Database reference NOT successfully created...', 'error');
+      drupal_set_message(t('Database reference NOT successfully created...'), 'error');
     } //end of if dbxref was created successfully
   } //end of if valid db reference
 
@@ -208,9 +208,9 @@ function tripal_stock_edit_ALL_dbreferences_page($node) {
   $output = '';
 
   $output .= drupal_get_form('tripal_stock_edit_ALL_db_references_form', $node);
-  $output .= '<br>';
+  $output .= '<br />';
   $output .= drupal_get_form('tripal_stock_add_ONE_dbreference_form', $node);
-  $output .= '<br>';
+  $output .= '<br />';
   $output .= drupal_get_form('tripal_stock_back_to_stock_button', $node->nid);
 
   return $output;
@@ -315,29 +315,29 @@ function tripal_stock_edit_ALL_db_references_form_submit($form, &$form_state) {
 
   if ($form_state['clicked_button']['#value'] == t('Update DB References') ) {
 
-     //Update all
-     for ($i=1; $i<=$form_state['values']['num_db_references']; $i++) {
-       tripal_stock_update_db_reference(
-          $form_state['values']["id-$i"],
-          $form_state['values']["database-$i"],
-          $form_state['values']["accession-$i"]
+       //Update all
+    for ($i=1; $i<=$form_state['values']['num_db_references']; $i++) {
+      tripal_stock_update_db_reference(
+        $form_state['values']["id-$i"],
+        $form_state['values']["database-$i"],
+        $form_state['values']["accession-$i"]
       );
-     }
-     drupal_set_message("Updated all Database References");
-     drupal_goto('node/' . $form_state['values']['nid']);
+    }
+      drupal_set_message(t("Updated all Database References"));
+      drupal_goto('node/' . $form_state['values']['nid']);
 
   }
   elseif ( preg_match('/Delete #(\d+)/', $form_state['clicked_button']['#value'], $matches) ) {
 
-     $i = $matches[1];
-     tripal_stock_delete_db_reference($form_state['values']["id-$i"]);
-     drupal_set_message("Deleted Database Reference");
+    $i = $matches[1];
+    tripal_stock_delete_db_reference($form_state['values']["id-$i"]);
+    drupal_set_message(t("Deleted Database Reference"));
 
   }
   else {
-    drupal_set_message("Unrecognized Button Pressed", 'error');
-  }
+    drupal_set_message(t("Unrecognized Button Pressed"), 'error');
 
+  }
 }
 
 /**
@@ -408,7 +408,7 @@ function tripal_stock_delete_db_reference($dbxref_id) {
 function theme_tripal_stock_edit_ALL_db_references_form($form) {
   $output = '';
 
-  $output .= '<br><fieldset>';
+  $output .= '<br /><fieldset>';
   $output .= '<legend>Edit Existing Database References<span class="form-optional" title="This field is optional">(optional)</span></legend>';
   $output .= '<p>Below is a list of already existing database references, one per line. When entering a database reference, the accession '
          .'is a unique identifier for this stock in the specified database.</p>';
@@ -422,7 +422,7 @@ function theme_tripal_stock_edit_ALL_db_references_form($form) {
          . drupal_render($form["submit-$i"]) . '</td></tr>';
   }
 
-  $output .= '</table><br>';
+  $output .= '</table><br />';
   $output .= drupal_render($form);
   $output .= '</fieldset>';
 

+ 20 - 20
tripal_stock/tripal_stock-properties.inc

@@ -12,13 +12,13 @@
 function tripal_stock_add_ALL_property_page($node) {
   $output = '';
 
-  $output .= tripal_stock_add_chado_properties_progress('properties') . '<br>';
-  $output .= '<b>All Properties should strictly pertain to THE CURRENT Individual</b><br>';
-  $output .= '<br>';
+  $output .= tripal_stock_add_chado_properties_progress('properties') . '<br />';
+  $output .= '<b>All Properties should strictly pertain to THE CURRENT Individual</b><br />';
+  $output .= '<br />';
   $output .= theme('tripal_stock_properties', $node);
-  $output .= '<br><br>';
+  $output .= '<br /><br />';
   $output .= drupal_get_form('tripal_stock_add_ONE_property_form', $node);
-  $output .= '<br>';
+  $output .= '<br />';
   $output .= drupal_get_form('tripal_stock_add_chado_properties_navigate', 'properties', $node->nid);
   return $output;
 }
@@ -147,7 +147,7 @@ function tripal_stock_add_ONE_property_form_submit($form, &$form_state) {
     );
     tripal_db_set_active($previous_db);
 
-    drupal_set_message("Successfully Added Property");
+    drupal_set_message(t("Successfully Added Property"));
 
     // Set Preferred Synonym
     if ($form_state['values']['preferred_synonym'] == 1) {
@@ -178,9 +178,9 @@ function tripal_stock_edit_ALL_properties_page($node) {
   $output = '';
 
   $output .= drupal_get_form('tripal_stock_edit_ALL_properties_form', $node);
-  $output .= '<br>';
+  $output .= '<br />';
   $output .= drupal_get_form('tripal_stock_add_ONE_property_form', $node);
-  $output .= '<br>';
+  $output .= '<br />';
   $output .= drupal_get_form('tripal_stock_back_to_stock_button', $node->nid);
 
   return $output;
@@ -265,20 +265,20 @@ function tripal_stock_edit_ALL_properties_form($form_state, $node) {
 function tripal_stock_edit_ALL_properties_form_submit($form, &$form_state) {
 
   if ($form_state['clicked_button']['#value'] == t('Update Properties') ) {
-     //Update all
-     for ($i=1; $i<=$form_state['values']['num_properties']; $i++) {
-       tripal_stock_update_property($form_state['values']["id-$i"], $form_state['values']["type-$i"], $form_state['values']["value-$i"], $form_state['values']["preferred-$i"], $form_state['values']["nid"]);
-     }
-     drupal_set_message("Updated all Properties");
-     drupal_goto('node/' . $form_state['values']['nid']);
+    //Update all
+    for ($i=1; $i<=$form_state['values']['num_properties']; $i++) {
+      tripal_stock_update_property($form_state['values']["id-$i"], $form_state['values']["type-$i"], $form_state['values']["value-$i"], $form_state['values']["preferred-$i"], $form_state['values']["nid"]);
+    }
+    drupal_set_message(t("Updated all Properties"));
+    drupal_goto('node/' . $form_state['values']['nid']);
   }
   elseif ( preg_match('/Delete #(\d+)/', $form_state['clicked_button']['#value'], $matches) ) {
-     $i = $matches[1];
-     tripal_stock_delete_property($form_state['values']["id-$i"], $form_state['values']["type-$i"], $form_state['values']["value-$i"]);
-     drupal_set_message("Deleted Property");
+    $i = $matches[1];
+    tripal_stock_delete_property($form_state['values']["id-$i"], $form_state['values']["type-$i"], $form_state['values']["value-$i"]);
+    drupal_set_message(t("Deleted Property"));
   }
   else {
-    drupal_set_message("Unrecognized Button Pressed", 'error');
+    drupal_set_message(t("Unrecognized Button Pressed"), 'error');
   }
 
 
@@ -367,7 +367,7 @@ function tripal_stock_delete_property($stockprop_id) {
 function theme_tripal_stock_edit_ALL_properties_form($form) {
   $output = '';
 
-  $output .= '<br><fieldset>';
+  $output .= '<br /><fieldset>';
   $output .= '<legend>Edit Already Existing Properties<span class="form-optional" title="This field is optional">(optional)</span></legend>';
   $output .= '<p>Below is a list of already existing properties for this stock, one property per line. The type refers to the type of '
          .'property and the value is the value for that property. For example, if this stock has a seed coat colour of green then '
@@ -380,7 +380,7 @@ function theme_tripal_stock_edit_ALL_properties_form($form) {
     $output .= '<tr><td>' . drupal_render($form["num-$i"]) . '</td><td>' . drupal_render($form["type-$i"]) . '</td><td>' . drupal_render($form["value-$i"]) . drupal_render($form["preferred-$i"]) . '</td><td>' . drupal_render($form["submit-$i"]) . '</td></tr>';
   }
 
-  $output .= '</table><br>';
+  $output .= '</table><br />';
   $output .= drupal_render($form);
   $output .= '</fieldset>';
 

+ 29 - 29
tripal_stock/tripal_stock-relationships.inc

@@ -12,13 +12,13 @@
 function tripal_stock_add_ALL_relationships_page($node) {
   $output = '';
 
-  $output .= tripal_stock_add_chado_properties_progress('relationships') . '<br>';
-  $output .= '<b>All Relationships should include the CURRENT Individual (' . $node->stock->uniquename . ')</b><br>';
-  $output .= '<br>';
+  $output .= tripal_stock_add_chado_properties_progress('relationships') . '<br />';
+  $output .= '<b>All Relationships should include the CURRENT Individual (' . $node->stock->uniquename . ')</b><br />';
+  $output .= '<br />';
   $output .= theme('tripal_stock_relationships', $node);
-  $output .= '<br><br>';
+  $output .= '<br /><br />';
   $output .= drupal_get_form('tripal_stock_add_ONE_relationship_form', $node);
-  $output .= '<br>';
+  $output .= '<br />';
   $output .= drupal_get_form('tripal_stock_add_chado_properties_navigate', 'relationships', $node->nid);
   return $output;
 }
@@ -115,13 +115,13 @@ function tripal_stock_add_ONE_relationship_form_validate($form, &$form_state) {
       for ($i=0; $i<sizeof($subject_results); $i++) {
       $links[] = l($i+1, "node/" . $subject_results[$i]->nid); }
       $message = "Too many stocks match '" . $form_state['values']['subject_id'] . "'! "
-                  . " Please refine your input to match ONLY ONE stock. <br>"
+                  . " Please refine your input to match ONLY ONE stock. <br />"
      . "To aid in this process, here are the stocks that match your initial input: "
      . join(', ', $links);
       form_set_error('subject_id', $message);
     }
     elseif (sizeof($subject_results) < 1) {
-      form_set_error('subject_id', "There are no stocks matching your input. Please check your input for typos and/or lookup the stock " . l('here', 'stocks'));
+      form_set_error('subject_id', t("There are no stocks matching your input. Please check your input for typos and/or lookup the stock %link", array('%link' => l(t('here'), 'stocks'))));
     }
     elseif (sizeof($subject_results) == 1) {
       $form_state['values']['subject_id'] = $subject_results[0]->stock->stock_id;
@@ -134,13 +134,13 @@ function tripal_stock_add_ONE_relationship_form_validate($form, &$form_state) {
       for ($i=0; $i<sizeof($object_results); $i++) {
       $links[] = l($i+1, "node/" . $object_results[$i]->nid); }
       $message = "Too many stocks match '" . $form_state['values']['object_id'] . "'! "
-                 . "Please refine your input to match ONLY ONE stock. <br>"
+                 . "Please refine your input to match ONLY ONE stock. <br />"
                  . "To aid in this process, here are the stocks that match your initial input: "
                  . join(', ', $links);
       form_set_error('object_id', $message);
     }
     elseif (sizeof($object_results) < 1) {
-      form_set_error('object_id', "There are no stocks matching your input. Please check your input for typos and/or lookup the stock " . l('here', 'stocks'));
+      form_set_error('object_id', t("There are no stocks matching your input. Please check your input for typos and/or lookup the stock %link", array('%link' => l(t('here'), 'stocks'))));
     }
     elseif (sizeof($object_results) == 1) {
       $form_state['values']['object_id'] = $object_results[0]->stock->stock_id;
@@ -187,7 +187,7 @@ function tripal_stock_add_ONE_relationship_form_submit($form, &$form_state) {
     );
     tripal_db_set_active($previous_db);
 
-    drupal_set_message('Successfully Added Relationship.');
+    drupal_set_message(t('Successfully Added Relationship.'));
   } //end of insert relationship
 
 }
@@ -201,9 +201,9 @@ function tripal_stock_edit_ALL_relationships_page($node) {
   $output = '';
 
   $output .= drupal_get_form('tripal_stock_edit_ALL_relationships_form', $node);
-  $output .= '<br>';
+  $output .= '<br />';
   $output .= drupal_get_form('tripal_stock_add_ONE_relationship_form', $node);
-  $output .= '<br>';
+  $output .= '<br />';
   $output .= drupal_get_form('tripal_stock_back_to_stock_button', $node->nid);
 
   return $output;
@@ -343,13 +343,13 @@ function tripal_stock_edit_ALL_relationships_form_validate($form, &$form_state)
         for ($j=0; $j<sizeof($subject_results); $j++) {
         $links[] = l($j+1, "node/" . $subject_results[$j]->nid); }
         $message = "Too many stocks match '" . $form_state['values']["subject_id-$i"] . "'! "
-                 . "Please refine your input to match ONLY ONE stock. <br>"
+                 . "Please refine your input to match ONLY ONE stock. <br />"
                  . "To aid in this process, here are the stocks that match your initial input: "
                  . join(', ', $links);
         form_set_error("subject_id-$i", $message);
       }
       elseif (sizeof($subject_results) < 1) {
-        form_set_error("subject_id-$i", "There are no stocks matching your input. Please check your input for typos and/or lookup the stock " . l('here', 'stocks'));
+        form_set_error("subject_id-$i", t("There are no stocks matching your input. Please check your input for typos and/or lookup the stock %link", array('%link' => l(t('here'), 'stocks'))));
       }
       elseif (sizeof($subject_results) == 1) {
         $form_state['values']["subject_id-$i"] = $subject_results[0]->stock->stock_id;
@@ -362,13 +362,13 @@ function tripal_stock_edit_ALL_relationships_form_validate($form, &$form_state)
         for ($j=0; $j<sizeof($object_results); $j++) {
         $links[] = l($j+1, "node/" . $object_results[$j]->nid); }
         $message = "Too many stocks match '" . $form_state['values']["object_id-$i"] . "'! "
-                 . "Please refine your input to match ONLY ONE stock. <br>"
+                 . "Please refine your input to match ONLY ONE stock. <br />"
                  . "To aid in this process, here are the stocks that match your initial input: "
                  . join(', ', $links);
         form_set_error("object_id-$i", $message);
       }
       elseif (sizeof($object_results) < 1) {
-        form_set_error("object_id-$i", "There are no stocks matching your input. Please check your input for typos and/or lookup the stock " . l('here', 'stocks'));
+        form_set_error("object_id-$i", t("There are no stocks matching your input. Please check your input for typos and/or lookup the stock %link", array('%link' => l(t('here'), 'stocks'))));
       }
       elseif (sizeof($object_results) == 1) {
         $form_state['values']["object_id-$i"] = $object_results[0]->stock->stock_id;
@@ -408,33 +408,33 @@ function tripal_stock_edit_ALL_relationships_form_validate($form, &$form_state)
 function tripal_stock_edit_ALL_relationships_form_submit($form, &$form_state) {
 
   if ($form_state['clicked_button']['#value'] == t('Update Relationships') ) {
-     //Update all
-     for ($i=1; $i<=$form_state['values']['num_relationships']; $i++) {
+    //Update all
+    for ($i=1; $i<=$form_state['values']['num_relationships']; $i++) {
 
-       //process stock textfields
-       tripal_stock_update_relationship(
+      //process stock textfields
+      tripal_stock_update_relationship(
         $form_state['values']["id-$i"],
         $form_state['values']["subject_id-$i"],
         $form_state['values']["type_id-$i"],
         $form_state['values']["object_id-$i"]
       );
-     }
-     drupal_set_message("Updated all Relationships");
-     drupal_goto('node/' . $form_state['values']['nid']);
+    }
+    drupal_set_message(t("Updated all Relationships"));
+    drupal_goto('node/' . $form_state['values']['nid']);
 
   }
   elseif ( preg_match('/Delete #(\d+)/', $form_state['clicked_button']['#value'], $matches) ) {
 
-     $i = $matches[1];
-     tripal_stock_delete_relationship($form_state['values']["id-$i"]);
-     drupal_set_message("Deleted Relationship");
+    $i = $matches[1];
+    tripal_stock_delete_relationship($form_state['values']["id-$i"]);
+    drupal_set_message(t("Deleted Relationship"));
 
   }
   elseif ($form_state['clicked_button']['#value'] == t('Back to Stock') ) {
     drupal_goto('node/' . $form_state['values']['nid']);
   }
   else {
-    drupal_set_message("Unrecognized Button Pressed", 'error');
+    drupal_set_message(t("Unrecognized Button Pressed"), 'error');
   }
 
 }
@@ -482,7 +482,7 @@ function tripal_stock_delete_relationship($stock_relationship_id) {
 function theme_tripal_stock_edit_ALL_relationships_form($form) {
   $output = '';
 
-  $output .= '<br><fieldset>';
+  $output .= '<br /><fieldset>';
   $output .= '<legend>Edit Already Existing Relationships<span class="form-optional" title="This field is optional">(optional)</span></legend>';
   $output .= '<p>Each relationship for this stock is listed below, one per line. The textboxes indicating '
         . 'the subject and object of the relationship can contain the uniquename, name, database '
@@ -498,7 +498,7 @@ function theme_tripal_stock_edit_ALL_relationships_form($form) {
          . drupal_render($form["submit-$i"]) . '</td></tr>';
   }
 
-  $output .= '</table><br>';
+  $output .= '</table><br />';
   $output .= drupal_render($form);
   $output .= '</fieldset>';
 

+ 10 - 3
tripal_stock/tripal_stock.install

@@ -6,12 +6,17 @@
  * @file
  */
 
-/** Implementation of hook_install() */
+/**
+ * Implementation of hook_install().
+ */
 function tripal_stock_install() {
   drupal_install_schema('tripal_stock');
 }
 
-/** Implementation of hook_uninstall() */
+/**
+ * Implementation of hook_uninstall().
+ */
+
 function tripal_stock_uninstall() {
   drupal_uninstall_schema('tripal_stock');
 
@@ -28,7 +33,9 @@ function tripal_stock_uninstall() {
 
 }
 
-/** Implementation of hook_schema() */
+/**
+ * Implementation of hook_schema().
+ */
 function tripal_stock_schema() {
   $schema['chado_stock'] = array(
     'fields' => array(

+ 92 - 92
tripal_stock/tripal_stock.module

@@ -44,16 +44,16 @@ function tripal_stock_menu() {
 
   //Administrative settings menu-----------------
   $items['admin/tripal/tripal_stock'] = array(
-    'title' => t('Stocks'),
-    'description' => t('Basic Description of Tripal Stock Module Functionality'),
+    'title' => 'Stocks',
+    'description' => 'Basic Description of Tripal Stock Module Functionality',
     'page callback' => 'tripal_stock_module_description_page',
     'access arguments' => array('administer site configuration'),
     'type' => MENU_NORMAL_ITEM
   );
 
   $items['admin/tripal/tripal_stock/configuration'] = array(
-    'title' => t('Configuration'),
-    'description' => t('Settings for Chado Stocks'),
+    'title' => 'Configuration',
+    'description' => 'Settings for Chado Stocks',
     'page callback' => 'drupal_get_form',
     'page arguments' => array('tripal_stock_admin'),
     'access arguments' => array('administer site configuration'),
@@ -63,7 +63,7 @@ function tripal_stock_menu() {
   //Displaying stocks----------------------------
   $items['stocks'] = array(
     'menu_name' => ('primary-links'),
-    'title' => t('Stocks'),
+    'title' => 'Stocks',
     'page callback' => 'tripal_stock_show_stocks',
     'access arguments' => array('access chado_stock content'),
     'type' => MENU_NORMAL_ITEM,
@@ -71,8 +71,8 @@ function tripal_stock_menu() {
 
   // Adding Secondary Properties-----------------
   $items['node/%cs_node/properties'] = array(
-    'title' => t('Add Properties & Synonyms'),
-    'description' => t('Settings for Chado Stocks'),
+    'title' => 'Add Properties & Synonyms',
+    'description' => 'Settings for Chado Stocks',
     'page callback' => 'tripal_stock_add_ALL_property_page',
     'page arguments' => array(1),
     'access arguments' => array('create chado_stock content'),
@@ -80,8 +80,8 @@ function tripal_stock_menu() {
   );
 
   $items['node/%cs_node/db_references'] = array(
-    'title' => t('Add Database References'),
-    'description' => t('Settings for Chado Stocks'),
+    'title' => 'Add Database References',
+    'description' => 'Settings for Chado Stocks',
     'page callback' => 'tripal_stock_add_ALL_dbreferences_page',
     'page arguments' => array(1),
     'access arguments' => array('create chado_stock content'),
@@ -89,8 +89,8 @@ function tripal_stock_menu() {
   );
 
   $items['node/%cs_node/relationships'] = array(
-    'title' => t('Add Relationships'),
-    'description' => t('Settings for Chado Stocks'),
+    'title' => 'Add Relationships',
+    'description' => 'Settings for Chado Stocks',
     'page callback' => 'tripal_stock_add_ALL_relationships_page',
     'page arguments' => array(1),
     'access arguments' => array('create chado_stock content'),
@@ -99,8 +99,8 @@ function tripal_stock_menu() {
 
   //Edit/Deleting Secondary Properties-------------
   $items['node/%cs_node/edit_properties'] = array(
-    'title' => t('Edit Properties'),
-    'description' => t('Settings for Chado Stocks'),
+    'title' => 'Edit Properties',
+    'description' => 'Settings for Chado Stocks',
     'page callback' => 'tripal_stock_edit_ALL_properties_page',
     'page arguments' => array(1),
     'access arguments' => array('edit chado_stock content'),
@@ -109,8 +109,8 @@ function tripal_stock_menu() {
   );
 
     $items['node/%cs_node/edit_relationships'] = array(
-    'title' => t('Edit Relationships'),
-    'description' => t('Settings for Chado Stocks'),
+    'title' => 'Edit Relationships',
+    'description' => 'Settings for Chado Stocks',
     'page callback' => 'tripal_stock_edit_ALL_relationships_page',
     'page arguments' => array(1),
     'access arguments' => array('edit chado_stock content'),
@@ -119,8 +119,8 @@ function tripal_stock_menu() {
   );
 
   $items['node/%cs_node/edit_db_references'] = array(
-    'title' => t('Edit DB References'),
-    'description' => t('Settings for Chado Stocks'),
+    'title' => 'Edit DB References',
+    'description' => 'Settings for Chado Stocks',
     'page callback' => 'tripal_stock_edit_ALL_dbreferences_page',
     'page arguments' => array(1),
     'access arguments' => array('edit chado_stock content'),
@@ -158,7 +158,7 @@ function cs_node_load($nid) {
 }
 
 /**
- * Implementation of hook_perm()
+ * Implementation of hook_perm().
  *
  * Purpose: Set the permission types that the chado stock module uses
  *
@@ -192,27 +192,27 @@ function tripal_stock_perm() {
  * @ingroup tripal_stock
  */
 function chado_stock_access($op, $node, $account) {
-   if ($op == 'create') {
-      if (!user_access('create chado_stock content', $account)) {
-        return FALSE;
-      }
-   }
-   if ($op == 'update') {
-      if (!user_access('edit chado_stock content', $account)) {
-         return FALSE;
-      }
-   }
-   if ($op == 'delete') {
-      if (!user_access('delete chado_stock content', $account)) {
-         return FALSE;
-      }
-   }
-   if ($op == 'view') {
-      if (!user_access('access chado_stock content', $account)) {
-         return FALSE;
-      }
-   }
-   return NULL;
+  if ($op == 'create') {
+    if (!user_access('create chado_stock content', $account)) {
+      return FALSE;
+    }
+  }
+  if ($op == 'update') {
+    if (!user_access('edit chado_stock content', $account)) {
+      return FALSE;
+    }
+  }
+  if ($op == 'delete') {
+    if (!user_access('delete chado_stock content', $account)) {
+      return FALSE;
+    }
+  }
+  if ($op == 'view') {
+    if (!user_access('access chado_stock content', $account)) {
+      return FALSE;
+    }
+  }
+  return NULL;
 }
 
 /**
@@ -228,9 +228,9 @@ function chado_stock_access($op, $node, $account) {
  * @ingroup tripal_stock
  */
 function tripal_stock_views_api() {
-   return array(
-      'api' => 2.0,
-   );
+  return array(
+    'api' => 2.0,
+  );
 }
 
 /**
@@ -297,18 +297,18 @@ function tripal_stock_theme() {
  */
 function tripal_stock_show_stocks() {
   $sql = "SELECT COUNT(stock_id) FROM {chado_stock}";
-   $no_stocks = db_result(db_query($sql));
-   if ($no_stocks != 0) {
-      $stocks = tripal_stock_get_all_stocks();
-      if ($no_stocks != count($stocks)) {
-         drupal_set_message("Synchronization needed.");
-      }
-      return theme('tripal_stock_stock_table', &$stocks);
-   }
-   else {
-      return t("No Stocks exists. Please contact administrators to " .
-               "synchronize stocks.");
-   }
+  $no_stocks = db_result(db_query($sql));
+  if ($no_stocks != 0) {
+    $stocks = tripal_stock_get_all_stocks();
+    if ($no_stocks != count($stocks)) {
+      drupal_set_message(t("Synchronization needed."));
+    }
+    return theme('tripal_stock_stock_table', &$stocks);
+  }
+  else {
+    return t("No Stocks exists. Please contact administrators to " .
+             "synchronize stocks.");
+  }
 }
 
 /**
@@ -345,7 +345,7 @@ function theme_tripal_stock_stock_table(&$stocks) {
   $output .= "</table>";
   $output .= "</div>";
 
-   return $output;
+  return $output;
 }
 
 /**
@@ -677,7 +677,7 @@ function chado_stock_insert($node) {
         $values['version'] = '1';
         $dbxref_status = tripal_core_chado_insert('dbxref', $values);
         if (!$dbxref_status) {
-          drupal_set_message('Unable to add database reference to this stock.', 'warning');
+          drupal_set_message(t('Unable to add database reference to this stock.'), 'warning');
           watchdog('tripal_stock',
             'Insert Stock: Unable to create dbxref where values:%values',
             array('%values' => print_r($values, TRUE)),
@@ -739,7 +739,7 @@ function chado_stock_insert($node) {
       }
     }
     else {
-      drupal_set_message('Error during stock creation.', 'error');
+      drupal_set_message(t('Error during stock creation.'), 'error');
       watchdog('tripal_stock',
         'Insert Stock: Unable to find newly created stock where values:%values',
         array('%values' => print_r($values, TRUE)),
@@ -749,7 +749,7 @@ function chado_stock_insert($node) {
     }
   }
   else {
-    drupal_set_message('Error during stock creation.', 'error');
+    drupal_set_message(t('Error during stock creation.'), 'error');
     watchdog('tripal_stock',
       'Insert Stock: Unable to create stock where values:%values',
       array('%values' => print_r($values, TRUE)),
@@ -820,7 +820,7 @@ function chado_stock_update($node) {
             $dbxref_mode = 'Create';
           }
           else {
-            drupal_set_message('Unable to find stock to Update', 'error');
+            drupal_set_message(t('Unable to find stock to Update'), 'error');
             watchdog(
               'tripal_stock',
               'Stock Update: Unable to find stock to update using values: %values',
@@ -863,7 +863,7 @@ function chado_stock_update($node) {
     );
 
     if (!$status) {
-      drupal_set_message('Unable to update stock', 'error');
+      drupal_set_message(t('Unable to update stock'), 'error');
       watchdog(
         'tripal_stock',
         'Stock Update: Unable to update stock using match values: %mvalues and update values: %uvalues',
@@ -943,39 +943,39 @@ function tripal_stock_block($op = 'list', $delta = 0, $edit=array()) {
 
       return $blocks;
 
-     case 'view':
-       if (user_access('access chado_stock content') and arg(0) == 'node' and is_numeric(arg(1))) {
-        $nid = arg(1);
-        $node = node_load($nid);
-
-        $block = array();
-        switch ($delta) {
-          case 'base':
-            $block['subject'] = t('Stock Details');
-            $block['content'] = theme('tripal_stock_base', $node);
-            break;
-
-          case 'properties':
-            $block['subject'] = t('Properties');
-            $block['content'] = theme('tripal_stock_properties', $node);
-            break;
-
-          case 'references':
-            $block['subject'] = t('References');
-            $block['content'] = theme('tripal_stock_references', $node);
-            break;
-
-          case 'relationships':
-            $block['subject'] = t('Relationships');
-            $block['content'] = theme('tripal_stock_relationships', $node);
-            break;
-
-          case 'synonyms':
-            $block['subject'] = t('Synonyms');
-            $block['content'] = theme('tripal_stock_synonyms', $node);
-            break;
+    case 'view':
+      if (user_access('access chado_stock content') and arg(0) == 'node' and is_numeric(arg(1))) {
+      $nid = arg(1);
+      $node = node_load($nid);
+
+      $block = array();
+      switch ($delta) {
+        case 'base':
+          $block['subject'] = t('Stock Details');
+          $block['content'] = theme('tripal_stock_base', $node);
+          break;
+
+        case 'properties':
+          $block['subject'] = t('Properties');
+          $block['content'] = theme('tripal_stock_properties', $node);
+          break;
+
+        case 'references':
+          $block['subject'] = t('References');
+          $block['content'] = theme('tripal_stock_references', $node);
+          break;
+
+        case 'relationships':
+          $block['subject'] = t('Relationships');
+          $block['content'] = theme('tripal_stock_relationships', $node);
+          break;
+
+        case 'synonyms':
+          $block['subject'] = t('Synonyms');
+          $block['content'] = theme('tripal_stock_synonyms', $node);
+          break;
 
-        }
+      }
         return $block;
       }
   }

+ 46 - 46
tripal_stock/tripal_stock.views.inc

@@ -38,7 +38,7 @@ function tripal_stock_views_data()  {
     );
     foreach ($tables as $tablename) {
       if (!tripal_views_is_integrated($tablename, 10)) {
-        $table_integration_array = tripal_views_get_integration_array_for_chado_table($tablename,TRUE);
+        $table_integration_array = tripal_views_get_integration_array_for_chado_table($tablename, TRUE);
         tripal_views_integration_add_entry($table_integration_array);
       }
     }
@@ -57,7 +57,7 @@ function tripal_stock_views_data()  {
     );
     foreach ($tables as $tablename) {
       if (!tripal_views_is_integrated($tablename, 10)) {
-        $table_integration_array = tripal_views_get_integration_array_for_chado_table($tablename,FALSE);
+        $table_integration_array = tripal_views_get_integration_array_for_chado_table($tablename, FALSE);
         tripal_views_integration_add_entry($table_integration_array);
       }
     }
@@ -79,46 +79,46 @@ function tripal_stock_views_data()  {
  * @ingroup tripal_stock_views
  */
 function tripal_stock_views_handlers() {
- return array(
-   'info' => array(
-     'path' => drupal_get_path('module', 'tripal_stock') . '/views/handlers',
-   ),
-   'handlers' => array(
-     'views_handler_field_computed_stock_nid' => array(
-       'parent' => 'views_handler_field_numeric',
-     ),
-     'views_handler_field_stockprop_by_type' => array(
-       'parent' => 'views_handler_field_prerender_list',
-     ),
-    'views_handler_field_stockprop_all' => array(
-       'parent' => 'views_handler_field_prerender_list',
-     ),
-    'views_handler_field_stockrel_by_type' => array(
-       'parent' => 'views_handler_field_prerender_list',
-     ),
-    'views_handler_field_stockrel_all' => array(
-       'parent' => 'views_handler_field_prerender_list',
-     ),
-    'views_handler_field_stock_dbxref_by_type' => array(
-       'parent' => 'views_handler_field_prerender_list',
-     ),
-    'views_handler_field_stock_dbxref_all' => array(
-       'parent' => 'views_handler_field_prerender_list',
-     ),
-     'views_handler_filter_stockprop_id' => array(
-       'parent' => 'views_handler_filter',
-     ),
-     'views_handler_filter_stock_dbxref_id' => array(
-       'parent' => 'views_handler_filter',
-     ),
-     'views_handler_filter_stock_relationship_id' => array(
-       'parent' => 'views_handler_filter',
-     ),
-     'views_handler_argument_stockprop_id' => array(
-       'parent' => 'views_handler_argument_string',
-     ),
-   ),
- );
+  return array(
+  'info' => array(
+    'path' => drupal_get_path('module', 'tripal_stock') . '/views/handlers',
+  ),
+  'handlers' => array(
+    'views_handler_field_computed_stock_nid' => array(
+      'parent' => 'views_handler_field_numeric',
+    ),
+  'views_handler_field_stockprop_by_type' => array(
+    'parent' => 'views_handler_field_prerender_list',
+    ),
+  'views_handler_field_stockprop_all' => array(
+    'parent' => 'views_handler_field_prerender_list',
+    ),
+  'views_handler_field_stockrel_by_type' => array(
+    'parent' => 'views_handler_field_prerender_list',
+    ),
+  'views_handler_field_stockrel_all' => array(
+    'parent' => 'views_handler_field_prerender_list',
+    ),
+  'views_handler_field_stock_dbxref_by_type' => array(
+    'parent' => 'views_handler_field_prerender_list',
+    ),
+  'views_handler_field_stock_dbxref_all' => array(
+    'parent' => 'views_handler_field_prerender_list',
+    ),
+  'views_handler_filter_stockprop_id' => array(
+    'parent' => 'views_handler_filter',
+    ),
+  'views_handler_filter_stock_dbxref_id' => array(
+    'parent' => 'views_handler_filter',
+    ),
+  'views_handler_filter_stock_relationship_id' => array(
+    'parent' => 'views_handler_filter',
+    ),
+  'views_handler_argument_stockprop_id' => array(
+    'parent' => 'views_handler_argument_string',
+    ),
+  ),
+  );
 }
 
 /**
@@ -163,7 +163,7 @@ function tripal_stock_views_pre_render  (&$view) {
   if (preg_match('/stock/', $view->base_table)) {
 
     //-----Node IDs---------------------------------------------
-    // @see file: tripal_core.views.inc function: tripal_core_add_node_ids_to_view (&$view);
+    // @see tripal_core.views.inc, tripal_core_add_node_ids_to_view()
 
     // retrieve the stock_id for each record in the views current page
     $stock_ids = array();
@@ -183,7 +183,7 @@ function tripal_stock_views_pre_render  (&$view) {
           ."WHERE stockprop.stock_id IN (" . implode(',', $stock_ids) . ")";
         $previous_db = tripal_db_set_active('chado');
         $resource = db_query($sql);
-       tripal_db_set_active($previous_db);
+        tripal_db_set_active($previous_db);
 
         $view->result[$key]->properties = array();
         while ($r = db_fetch_object($resource)) {
@@ -206,7 +206,7 @@ function tripal_stock_views_pre_render  (&$view) {
           ."OR stock_relationship.object_id IN (" . implode(',', $stock_ids) . ") ";
         $previous_db = tripal_db_set_active('chado');
         $resource = db_query($sql);
-       tripal_db_set_active($previous_db);
+        tripal_db_set_active($previous_db);
 
         while ($r = db_fetch_object($resource)) {
           if (in_array($r->subject_id, $stock_ids)) {
@@ -234,7 +234,7 @@ function tripal_stock_views_pre_render  (&$view) {
           ."WHERE stock_dbxref.stock_id IN (" . implode(',', $stock_ids) . ")";
         $previous_db = tripal_db_set_active('chado');
         $resource = db_query($sql);
-       tripal_db_set_active($previous_db);
+        tripal_db_set_active($previous_db);
 
         $view->result[$key]->dbxref = array();
         while ($r = db_fetch_object($resource)) {

+ 9 - 16
tripal_views/tripal_views.coder_ignores.txt

@@ -2,25 +2,18 @@
 ; file:line:warning-type
 ; where warning-type is one of security, style, sql, i18n, comment, etc.
 
-; All <?php should be closed with a ?> in theme template files
-tripal_views_integration_fields_form.tpl.php:48:style
-tripal_views_data_export_download_form.tpl.php:8:style
-
-; All variables are set through the code and thus don't need to be filtered
-tripal_views_integration.inc:809:security
+; All variables are filtered
+tripal_views_integration.inc:814:security
 
 ; SQL queries the chado database which does not use the drupal prefixing functionality
 ; therefore, curly brackets ({}) are not appropriate.
-views/handlers/views_handler_filter_chado_select_cvterm_name.inc:53:sql
-views/handlers/views_handler_filter_chado_select_cvterm_name.inc:61:sql
-views/handlers/views_handler_field_dbxref_accession_link.inc:31:sql
-views/handlers/views_handler_filter_stockprop_id.inc:78:sql
-views/handlers/views_handler_filter_stockprop_id.inc:104:sql
-views/handlers/views_handler_filter_stock_relationship_id.inc:23:sql
-views/handlers/views_handler_filter_stock_relationship_id.inc:72:sql
-views/handlers/views_handler_filter_stock_relationship_id.inc:79:sql
-views/handlers/views_handler_filter_stock_relationship_id.inc:160:sql
-views/handlers/views_handler_argument_stockprop_id.inc:21:sql
+views/handlers/views_handler_filter_chado_select_cvterm_name.inc:62:sql
+views/handlers/views_handler_field_dbxref_accession_link.inc:32:sql
+views/handlers/views_handler_filter_stockprop_id.inc:105:sql
+views/handlers/views_handler_filter_stock_relationship_id.inc:24:sql
+views/handlers/views_handler_filter_stock_relationship_id.inc:74:sql
+views/handlers/views_handler_filter_stock_relationship_id.inc:82:sql
+views/handlers/views_handler_argument_stockprop_id.inc:22:sql
 
 ; SQL queries the pg_tables table to check if a table exists in chado; drupal
 ; prefixing is not appropriate

+ 7 - 0
tripal_views/tripal_views.views.inc

@@ -718,8 +718,15 @@ function tripal_views_data_export_download_form(&$form_state, $view, $display_id
   $displays = $view->display;
   $options = array();
   $default = '';
+  $current_display = $view->current_display;
   foreach ($displays as $name => $display) {
     if (preg_match("/^views_data_export/", $name)) {
+    
+      // only add this display to the form if it is attached 
+      $display_options = $display->display_options;
+      if(strcmp($display_options['displays'][$current_display],$current_display)!=0){
+         continue;
+      } 
 
       // set the first item as default
       if (!$default) {

+ 6 - 6
tripal_views/tripal_views_integration.inc

@@ -394,10 +394,10 @@ function tripal_views_integration_form(&$form_state, $setup_id = NULL) {
     $mview_id = $form_state['storage']['mview_id'];
     $table_name = $form_state['storage']['table_name'];
     $form['view_setup_table'] = array(
-     '#type' => 'fieldset',
-     '#title' => 'Join Selection',
-     '#prefix' => '<div id="fieldset-table-rows-wrapper">',
-     '#suffix' => '</div>',
+      '#type' => 'fieldset',
+      '#title' => 'Join Selection',
+      '#prefix' => '<div id="fieldset-table-rows-wrapper">',
+      '#suffix' => '</div>',
     );
 
     // get the columns in this materialized view.  They are separated by commas
@@ -499,8 +499,8 @@ function tripal_views_integration_form(&$form_state, $setup_id = NULL) {
       $form['view_setup_table']["$table_id-$i"]["fields_name_$table_id-$i"] = array(
         '#type' => 'markup',
         '#prefix' => "<div class=\"column-one\">",
-        '#value' => "<span class=\"column-name\">$column_name</span>".
-                    "<br /><span class=\"column-type\">$column_type</span>",
+        '#value' => "<span class=\"column-name\">" . filter_xss($column_name) . "</span>".
+                    "<br /><span class=\"column-type\">" . filter_xss($column_type) . "</span>",
         '#suffix' => "</div>",
       );
       $data['field_types'][$column_name] = $column_type;

+ 4 - 3
tripal_views/views/chado_linking.TMP.inc

@@ -1,6 +1,7 @@
 <?php
 
 /**
+ * @file
  * This is a temporary function holding all the old-style views integration
  * needed to link the base tables to their node. This will remain to keep things working
  * until it has been best determined how to do this via the new tripal_views integration
@@ -13,9 +14,9 @@ function tripal_views_TEMPORARY_chado_linking_data($data) {
   // if the chado database is not local to the drupal database
   // then we need to set the database name.  This should always
   // be 'chado'.
-  if(is_array($db_url) and array_key_exists('chado',$db_url)){
-     // return empty data array b/c if chado is external then no join to the nodetable can be made
-     return $data;
+  if (is_array($db_url) and array_key_exists('chado', $db_url)) {
+    // return empty data array b/c if chado is external then no join to the nodetable can be made
+    return $data;
   }
 
   // FEATURE ====================================

+ 1 - 0
tripal_views/views/handlers/views_handler_field_dbxref_accession_link.inc

@@ -28,6 +28,7 @@ class views_handler_field_dbxref_accession_link extends views_handler_field {
 
     if (!empty($db_id) AND !empty($accession)) {
       $previous_db = tripal_db_set_active('chado');
+      // @coder-ignore: non-drupal schema therefore table prefixing does not apply
       $result = db_fetch_object(db_query('SELECT urlprefix FROM db WHERE db_id=%d', $db_id));
       tripal_db_set_active($previous_db);
       $urlprefix = $result->urlprefix;

+ 1 - 0
tripal_views/views/handlers/views_handler_filter_chado_select_cvterm_name.inc

@@ -58,6 +58,7 @@ class views_handler_filter_chado_select_cvterm_name extends views_handler_filter
 
     }
     else {
+      // @coder-ignore: non-drupal schema therefore table prefixing does not apply
       $sql = "SELECT cvterm_id, name FROM cvterm WHERE cvterm_id IN (SELECT distinct(type_id) FROM %s)";
       $previous_db = tripal_db_set_active('chado');
       $resource = db_query($sql, $this->view->base_table);

+ 35 - 5
tripal_views/views/handlers/views_handler_filter_chado_select_string.inc

@@ -44,6 +44,12 @@ class views_handler_filter_chado_select_string extends views_handler_filter_stri
       '#default_value' => (isset($this->options['max_length'])) ? $this->options['max_length'] : 40,
 
     );
+    $form['max_length'] = array(
+      '#type' => 'markup',
+      '#value' => t('<strong><font color="red">Note:</font></strong> If another filter exists for the same table then '.
+                    'the values shown in the drop box will only include those from rows that are not filtered.'),
+
+    );
 
   }
 
@@ -64,19 +70,43 @@ class views_handler_filter_chado_select_string extends views_handler_filter_stri
     }
     else {
 
-      // Get Options
-      if ($this->options['optional']) {
-        //$options['<select '.$this->table.'>'] = '--None--';
-        $options['All'] = '--Any--';
+      // build a where clause that will filter the list in the drop box
+      // using fields that are not exposed and that are for the table
+      // from whcih the values in the drop box will be slected and
+      // we only want to use non-exposed fields because these are not
+      // available to the user to edit--their fixed.
+      $where = '';
+      $filters = $this->view->filter;
+      foreach($filters as $filter_name => $details){
+         // we only want to inclue non-exposed filters 
+         if($details->options['exposed'] == FALSE){
+            // we only want to filter on the table we're getting the list from
+            if(strcmp($details->table,$this->table)==0){
+              $where .= "$details->field $details->operator ". $details->value['value'];
+              $where .= ' AND ';
+            }
+         }
+      } 
+      if($where){
+         $where = "WHERE $where";
+         $where = substr($where,0,-5); # remove the final ' AND '
       }
-      $sql = "SELECT $this->field FROM $this->table ORDER BY $this->field ASC";
+
+      // get the values from the table
+      $sql = "SELECT $this->real_field FROM $this->table $where ORDER BY $this->field ASC";
       $previous_db = tripal_db_set_active('chado');  // use chado database
       $results = db_query($sql);
       tripal_db_set_active($previous_db);  // now use drupal database
+
+      // Build the select box options
       $max_length = $this->options['max_length'];
       if (!$max_length) {
         $max_length = 40;
       }
+      if ($this->options['optional']) {
+        //$options['<select '.$this->table.'>'] = '--None--';
+        $options['All'] = '--Any--';
+      }
       while ($r = db_fetch_object($results)) {
         if (drupal_strlen($r->{$this->field}) > $max_length) {
           $options[$r->{$this->field}] = drupal_substr($r->{$this->field}, 0, $max_length) . '...';

Kaikkia tiedostoja ei voida näyttää, sillä liian monta tiedostoa muuttui tässä diffissä