Tripal 0.3b
tripal_library/tripal_library.module
Go to the documentation of this file.
00001 <?php
00002 
00003 /**
00004  * @defgroup tripal_library Library
00005  * @{
00006  * Provides functions for managing chado libraries including creating details pages for each library
00007  * @}
00008  * @ingroup tripal_modules
00009  */
00010  
00011 require('tripal_library.api.inc');
00012 
00013 /**
00014  * Display help and module information
00015  * @param path which path of the site we're displaying help
00016  * @param arg array that holds the current path as would be returned from arg()
00017  * function
00018  * @return help text for the path
00019  *
00020  * @ingroup tripal_library
00021  */
00022 function tripal_library_help($path, $arg) {
00023    $output = '';
00024    switch ($path) {
00025       case "admin/help#tripal_library":
00026          $output = '<p>'.
00027          t("Displays links to nodes created on this date").
00028                    '</p>';
00029          break;
00030    }
00031    return $output;
00032 }
00033 
00034 /**
00035  * Provide information to drupal about the node types that we're creating
00036  * in this module
00037  *
00038  * @ingroup tripal_library
00039  */
00040 function tripal_library_node_info() {
00041    $nodes = array();
00042    $nodes['chado_library'] = array(
00043       'name' => t('Library'),
00044       'module' => 'chado_library',
00045       'description' => t('A library from the chado database'),
00046       'has_title' => FALSE,
00047       'title_label' => t('Library'),
00048       'has_body' => FALSE,
00049       'body_label' => t('Library Description'),
00050       'locked' => TRUE
00051    );
00052    return $nodes;
00053 }
00054 
00055 /**
00056  * Set the permission types that the chado module uses.  Essentially we
00057  * want permissionis that protect creation, editing and deleting of chado
00058  * data objects
00059  *
00060  * @ingroup tripal_library
00061  */
00062 function tripal_library_perm(){
00063    return array(
00064       'access chado_library content',
00065       'create chado_library content',
00066       'delete chado_library content',
00067       'edit chado_library content',
00068    );
00069 }
00070 /**
00071  *  Set the permission types that the module uses.
00072  *
00073  * @ingroup tripal_library
00074  */
00075 function chado_library_access($op, $node, $account) {
00076    if ($op == 'create') {
00077       return user_access('create chado_library content', $account);
00078    }
00079 
00080    if ($op == 'update') {
00081       if (user_access('edit chado_library content', $account)) {
00082          return TRUE;
00083       }
00084    }
00085    if ($op == 'delete') {
00086       if (user_access('delete chado_library content', $account)) {
00087          return TRUE;
00088       }
00089    }
00090    if ($op == 'view') {
00091       if (user_access('access chado_library content', $account)) {
00092          return TRUE;
00093       }
00094    }
00095    return FALSE;
00096 }
00097 /**
00098  * Menu items are automatically added for the new node types created
00099  * by this module to the 'Create Content' Navigation menu item.  This function
00100  * adds more menu items needed for this module.
00101  *
00102  * @ingroup tripal_library
00103  */
00104 function tripal_library_menu() {
00105    $items = array();
00106    // The administative settings menu
00107    $items['admin/tripal/tripal_library'] = array(
00108       'title' => 'Libraries',
00109       'description' => 'Basic Description of Tripal Library Module Functionality',
00110       'page callback' => 'tripal_library_module_description_page',
00111       'access arguments' => array('access administration pages'),
00112       'type' => MENU_NORMAL_ITEM,
00113    );
00114    
00115    $items['admin/tripal/tripal_library/configuration'] = array(
00116       'title' => 'Configuration',
00117       'description' => 'Manage integration of Chado libraries including associated features.',
00118       'page callback' => 'drupal_get_form',
00119       'page arguments' => array('tripal_library_admin'),
00120       'access arguments' => array('access administration pages'),
00121       'type' => MENU_NORMAL_ITEM,
00122    );
00123    
00124    // Synchronizing libraries from Chado to Drupal
00125    $items['chado_sync_libraries'] = array(
00126       'title' => t('Sync Data'),
00127       'page callback' => 'tripal_library_sync_libraries',
00128       'access arguments' => array('access administration pages'),
00129       'type' => MENU_CALLBACK
00130    );
00131    // Displaying libraries
00132    $items['libraries'] = array(
00133       'menu_name' => ('primary-links'), //Enable the 'Library' primary link
00134       'title' => t('DNA Libraries'),
00135       'page callback' => 'tripal_library_show_libraries',
00136       'access arguments' => array('access chado_library content'),
00137       'type' => MENU_NORMAL_ITEM
00138    );
00139 
00140    return $items;
00141 }
00142 
00143 /**
00144  * Implements hook_views_api()
00145  * Purpose: Essentially this hook tells drupal that there is views support for
00146  *  for this module which then includes tripal_db.views.inc where all the
00147  *  views integration code is
00148  *
00149  * @ingroup tripal_library
00150  */ 
00151 function tripal_library_views_api() {
00152    return array(
00153       'api' => 2.0,
00154    );
00155 }
00156 
00157 /**
00158  * Purpose: Provide Guidance to new Tripal Admin
00159  *
00160  * @return HTML Formatted text
00161  *
00162  * @ingroup tripal_library
00163  */
00164 function tripal_library_module_description_page() {
00165   $text = '';
00166   
00167   $text .= '<h3>Module Description:</h3>';
00168   $text .= '<p>The Tripal Library module is an interface for the Chado Library module which groups features (sequences) into genetic libraries. 
00169     This module provides support for visualization of "library" pages, editing and updating.</p>';
00170 
00171   $text .= '<h3>Setup Instructions:</h3>';
00172   $text .= '<ol>';
00173   $text .= '<li><p><b>Set Permissions</b>: The library module supports the Drupal user permissions interface for 
00174                controlling access to library content and functions. These permissions include viewing, 
00175                creating, editing or administering of
00176                library content. The default is that only the original site administrator has these 
00177                permissions.  You can <a href="'.url('admin/user/roles').'">add roles</a> for classifying users, 
00178                <a href="'.url('admin/user/user').'">assign users to roles</a> and
00179                <a href="'.url('admin/user/permissions').'">assign permissions</a> for the library content to 
00180                those roles.  For a simple setup, allow anonymous users access to view organism content and 
00181                allow the site administrator all other permissions.</p></li>';
00182   $text .= '<li><p><b>Sync any Existing Libraries</b>: Near the top of the '.l('Library Configuration page','admin/tripal/tripal_library/configuration').' there is 
00183               a Sync Libraries section which provides list of libraries currently in chado which can be sync\'d. 
00184               Simply select the libraries you would like to create Drupal/Tripal pages for and click Sync Libraries.</p></li>';          
00185   $text .= '</ol>';
00186   
00187   
00188   $text .= '<h3>Features of this Module:</h3>';
00189   $text .= '<ul>';
00190     $text .= '<li><b>Add/Edit/Delete Libraries</b>: Libraries with no associated features can be created '.l('here', 'node/add/chado-library').' but it is 
00191               recommended to create the library using the feature loader. For example, when you load FASTA files using the Tripal loader you are
00192               given the option of specifying a library for all created features. Existing Libraries (regardless of the method used to create them) can be 
00193               edited or deleted by clicking the Edit tab at the top of the Library Page.</li>';  
00194     $text .= '<li><p><b>Integration with Drupal Views</b>: <a href="http://drupal.org/project/views">Drupal Views</a> is
00195               a powerful tool that allows the site administrator to create lists or basic searching forms of Chado content.
00196               It provides a graphical interface within Drupal to allow the site admin to directly query the Chado database
00197               and create custom lists without PHP programming or customization of Tripal source code.  Views can also
00198               be created to filter content that has not yet been synced with Druapl in order to protect access to non
00199               published data (only works if Chado was installed using Tripal).  You can see a list of available pre-existing
00200               Views <a href="'.url('admin/build/views/').'">here</a>, as well as create your own. </p></li>';  
00201     $text .= '<li><b>Basic Listing</b>: This module provides a basic <a href="'.url('libraries').'">library display 
00202               tool</a> for finding or listing libraries in Chado. It does not require indexing for Drupal searching but relies
00203               on Drupal Views.  <a href="http://drupal.org/project/views">Drupal Views</a> must be installed.</li>';  
00204   $text .= '</ul>';
00205   
00206    $text .= '<h3>Page Customizations</h3>';
00207    $text .= '<p>There are several ways to customize the look-and-feel for the way Chado data is presented through Tripal. 
00208              Below is a description of several methods.  These methods may be used in conjunction with one another to
00209              provide fine-grained control. 
00210              <ul>
00211 
00212              <li><p><b>Integration with Drupal Panels</b>:  <a href="http://drupal.org/project/views">Drupal Panels</a> 
00213               allows for customization of a page layout if you don\'t want to do PHP/Javascript/CSS programming.  Tripal comes with pre-set layouts for library pages.  However, 
00214               Panels become useful if you prefer a layout that is different from the pre-set layouts.  Chado content
00215               is provided to Panels in the form of Drupal "blocks" which you can then place anywhere on a page using the 
00216               Panel\'s GUI.</p></li>
00217 
00218              <li><p><b>Drupal\'s Content Construction Kit (CCK)</b>: the 
00219              <a href="http://drupal.org/project/cck">Content Construction Kit (CCK) </a> is a powerful way to add non-Chado content
00220              to any page without need to edit template files or knowing PHP.  You must first download and install CCK.
00221              With CCK, the site administartor can create a new field to appear on the page.  For example, currently,
00222              the Chado publication module is not yet supported by Tripal.  Therefore, the site administrator can add a text 
00223              field to the library pages.  This content is not stored in Chado, but will appear on the library page.  A field
00224              added by CCK will also appear in the form when editing a library to allow users to manually enter the appropriate
00225              text.  If the default pre-set layout and themeing for Tripal is used, it is better to create the CCK element,
00226              indicate that it is not to be shown (using the CCK interface), then manually add the new content type 
00227              where desired by editing the templates (as described below).  If using Panels, the CCK field can be added to the
00228              location desired using the Panels interface.</p></li>
00229 
00230              <li><p><b>Drupal Node Templates</b>:  The Tripal packages comes with a "theme_tripal" directory that contains the
00231              themeing for Chado content.    The library module has a template file for library "nodes" (Tripal library pages).  This file
00232              is named "node-chado_library.tpl.php", and provides javascript, HTML and PHP code for display of the library
00233              pages.  You can edit this file to control which types of information (or which library "blocks") are displayed for libraries. Be sure to 
00234              copy these template to your primary theme directory for editing. Do not edit them in the "theme_tripal" directory as
00235              future Tripal updates may overwrite your customizations. See the <a href="http://tripal.sourceforge.net/">Tripal website </a>
00236              for instructions on how to access variables and other Chado content within the template file.</p></li>
00237 
00238              <li><p><b>Library "Block" Templates</b>:  In the "theme_tripal" directory is a subdirectory named "tripal_library".
00239              Inside this directory is a set of templates that control distinct types of information for libraries.  For example,
00240              there is a "base" template for displaying of data directly from the Chado library table.  These templates are used both by Drupal blocks
00241              for use in Drupal Panels (as described above) or for use in the default pre-set layout that the node template 
00242              provides (also desribed above).  You can customize this template as you desire.  Be sure to copy the
00243              template to your primary theme directory for editing. Do not edit them in the "theme_tripal" directory as
00244              future Tripal updates may overwrite your customizations.  See the <a href="http://tripal.sourceforge.net/">Tripal website </a>
00245              for instructions on how to access variables and other Chado content within the template files.</p></li>
00246              </li>
00247 
00248              <li><p><b>Adding Links to the "Resources" Sidebar</b>: If you use the pre-set default Tripal layout for theming, you
00249              will see a "Resources" sidebar on each page.  The links that appear on the sidebar are automatically generated
00250              using Javascript for all of the library "Blocks" that appear on the page. If you want to add additional links 
00251              (e.g. a link to a views table showing all features of the current library) and you want that link to appear in the 
00252              "Resources" sidebar, simply edit the Drupal Node Template (as described above) and add the link to the 
00253              section at the bottom of the template file where the resources section is found.</p></li>
00254 
00255              </ul>
00256              </p>';
00257              
00258   return $text;
00259 }
00260 
00261 /**
00262  * Administrative settings form
00263  *
00264  * @ingroup tripal_library
00265  */
00266 function tripal_library_admin () {
00267    $form = array();
00268 
00269    // before proceeding check to see if we have any
00270    // currently processing jobs. If so, we don't want
00271    // to give the opportunity to sync libraries
00272    $active_jobs = FALSE;
00273    if(tripal_get_module_active_jobs('tripal_library')){
00274       $active_jobs = TRUE;
00275    }
00276 
00277    // add the field set for syncing libraries
00278    if(!$active_jobs){
00279       get_tripal_library_admin_form_sync_set ($form);
00280       get_tripal_library_admin_form_reindex_set($form);
00281       get_tripal_library_admin_form_taxonomy_set($form);
00282       get_tripal_library_admin_form_cleanup_set($form);
00283       get_tripal_library_admin_form_menu_set($form);
00284    } else {
00285       $form['notice'] = array(
00286        '#type' => 'fieldset',
00287        '#title' => t('Library Management Temporarily Unavailable')
00288       );
00289       $form['notice']['message'] = array(
00290           '#value' => t('Currently, library 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.'),
00291       );
00292    }
00293 
00294    return system_settings_form($form);
00295 }
00296 
00297 /**
00298  * HOOK: Implementation of hook_nodeapi()
00299  * Display library information for associated features or organisms
00300  * This function also provides contents for indexing
00301  *
00302  * @ingroup tripal_library
00303  */
00304 function tripal_library_nodeapi(&$node, $op, $teaser, $page) {
00305 
00306    switch ($op) {
00307       // Note that this function only adds library view to an organism/feature
00308       // node. 
00309       case 'view':
00310          // add the library to the organism/feature search indexing
00311          if($node->build_mode == NODE_BUILD_SEARCH_INDEX){
00312             $node->content['tripal_library_index_version'] = array(
00313           '#value' => theme('tripal_library_search_index',$node),
00314             );
00315          } else if ($node->build_mode == NODE_BUILD_SEARCH_RESULT) {
00316             $node->content['tripal_library_index_version'] = array(
00317           '#value' => theme('tripal_library_search_result',$node),
00318             );
00319          } else {
00320             switch($node->type){
00321                case 'chado_organism':
00322                   // Show library if the organism/feature is not at teaser view
00323                   $node->content['tripal_organism_libraries'] = array(
00324                 '#value' => theme('tripal_organism_libraries', $node),
00325                   );
00326                   break;
00327                case 'chado_feature':
00328                   // Show library if the organism/feature is not at teaser view
00329                   $node->content['tripal_feature_libraries'] = array(
00330                 '#value' => theme('tripal_feature_libraries', $node),
00331                   );
00332                   break;
00333             }
00334          }
00335          break;
00336    }
00337 }
00338 
00339 /**
00340  *  We need to let drupal know about our theme functions and their arguments.
00341  *  We create theme functions to allow users of the module to customize the
00342  *  look and feel of the output generated in this module
00343  *
00344  * @ingroup tripal_library
00345  */
00346 function tripal_library_theme () {
00347    return array(
00348      'tripal_library_library_table' => array (
00349          'arguments' => array('libraries'),
00350       ),
00351       'tripal_library_search_index' => array (
00352          'arguments' => array('node'),
00353       ),
00354       'tripal_library_search_result' => array (
00355          'arguments' => array('node'),
00356       ),
00357 
00358       'tripal_organism_libraries' => array (
00359          'arguments' => array('node'=> null),
00360          'template' => 'tripal_organism_libraries',
00361       ),
00362       'tripal_feature_libraries' => array (
00363          'arguments' => array('node'=> null),
00364          'template' => 'tripal_feature_libraries',
00365       ),
00366 
00367       'tripal_library_base' => array (
00368          'arguments' => array('node'=> null),
00369          'template' => 'tripal_library_base',
00370       ),
00371       'tripal_library_synonyms' => array (
00372          'arguments' => array('node'=> null),
00373          'template' => 'tripal_library_synonyms',
00374       ),
00375       'tripal_library_references' => array (
00376          'arguments' => array('node'=> null),
00377          'template' => 'tripal_library_references',
00378       ),
00379       'tripal_library_properties' => array (
00380          'arguments' => array('node'=> null),
00381          'template' => 'tripal_library_properties',
00382       ),
00383    );
00384 }
00385 
00386 /**
00387  * This function is an extension of the chado_feature_view and
00388  * chado_organism_view by providing the markup for the library object
00389  * THAT WILL BE INDEXED.
00390  *
00391  * @ingroup tripal_library
00392  */
00393 function theme_tripal_library_search_index ($node) {
00394 
00395    if ($node->type == 'chado_organism') {
00396       $content = "";
00397       // get the libraries for the organism
00398       $previous_db = tripal_db_set_active('chado');
00399       $sql = "SELECT * FROM {library} L ".
00400              "WHERE L.Organism_id = $node->organism_id";
00401       $libraries = array();
00402       $results = db_query($sql);
00403       while($library = db_fetch_object($results)){
00404          // get the description
00405          $sql = "SELECT * FROM {libraryprop} LP ".
00406                 "  INNER JOIN CVTerm CVT ON CVT.cvterm_id = LP.type_id ".
00407                 "WHERE LP.library_id = $library->library_id ".
00408                 "  AND CVT.name = 'library_description'";
00409          $desc = db_fetch_object(db_query($sql));
00410          $library->description = $desc->value;
00411          $libraries[] = $library;
00412       }
00413       tripal_db_set_active($previous_db);
00414       if(count($libraries) > 0){
00415          foreach ($libraries as $library){
00416             $content .= "$library->name ";
00417             $content .= "$library->description";
00418          };
00419       }
00420       // Provide library names to show in a feature page
00421    } else if ($node->type == 'chado_feature') {
00422       $content = "";
00423       $organism_id = $node->feature->organism_id;
00424       $previous_db = tripal_db_set_active('chado');
00425       $sql = "SELECT * FROM {library} L ".
00426              "  INNER JOIN Library_feature LF ON L.library_id = LF.library_id ".
00427              "WHERE LF.feature_id = " . $node->feature->feature_id;
00428       $libraries = array();
00429       $results = db_query($sql);
00430       while($library = db_fetch_object($results)){
00431          $libraries[] = $library;
00432       }
00433       tripal_db_set_active($previous_db);
00434       if(count($libraries) > 0){
00435          $lib_additions = array();
00436          foreach ($libraries as $library){
00437             $content .= $library->name;
00438          };
00439       }
00440    }
00441    return $content;
00442 }
00443 
00444 /**
00445  * This function shows library information on an organism/feature node
00446  *
00447  * @ingroup tripal_library
00448  */
00449 function theme_tripal_library_node_libraries($node) {
00450    $content = "";
00451 
00452    // Show library information in a expandable box for a organism page.
00453    // Make sure we have $node->organism_id. In the case of creating a new
00454    // organism, the organism_id is not created until we save. This will cause
00455    // an error when users preview the creation without a $node->organism_id
00456    if ($node->type == 'chado_organism' && $node->organism_id) {
00457       $box_status = variable_get("tripal_library-box-libraries","menu_off");
00458       
00459       if(strcmp($box_status,"menu_off")==0){
00460          return get_tripal_library_organism_libraries($node->nid);
00461       }
00462    }
00463    // Provide library names to show in a feature page.
00464    // Make sure we have $node->feature->feature_id or there will be an error
00465    // when a feature is previewed at its creation
00466    else if ($node->type == 'chado_feature' && $node->feature->feature_id) {
00467       $organism_id = $node->feature->organism_id;
00468       $previous_db = tripal_db_set_active('chado');
00469       $sql = "SELECT * FROM {library} L ".
00470              " INNER JOIN Library_feature LF ON L.library_id = LF.library_id ".
00471              "WHERE LF.feature_id = " . $node->feature->feature_id;
00472       $libraries = array();
00473       $results = db_query($sql);
00474       while($library = db_fetch_object($results)){
00475          $libraries[] = $library;
00476       }
00477       tripal_db_set_active($previous_db);
00478       if(count($libraries) > 0){
00479          $lib_additions = array();
00480          foreach ($libraries as $library){
00481             $sql = "SELECT nid FROM {chado_library} WHERE library_id = %d";
00482             $lib_nid = db_result(db_query($sql, $library->library_id));
00483             if ($lib_nid) {
00484                $lib_url = url("node/$lib_nid");
00485             }
00486             $lib_additions[$lib_url] = $library->name;
00487          };
00488          $node->lib_additions = $lib_additions;
00489       }
00490    }
00491    return $content;
00492 }
00493 
00494 /**
00495  *
00496  *
00497  * @ingroup tripal_library
00498  */
00499 function get_tripal_library_admin_form_menu_set(&$form){
00500    $form['menu'] = array(
00501       '#type' => 'fieldset',
00502       '#title' => t('Set Menu')
00503    );
00504 
00505    
00506    $types = array(
00507       'tripal_organism' => t('Organism Page'),
00508       'tripal_feature' => t('Feature Page'),
00509    );
00510 
00511    $defaults = variable_get('tripal_lib_menu_node_types','');
00512 
00513    $form['menu']['tripal_lib_menu_node_types'] = array(
00514       '#title' => 'Page Types',
00515       '#type'  => 'checkboxes',
00516       '#description' => t("Libraries can be associated with other data types ".
00517          "such as organisms, features, analyses, etc.  The library module ".
00518          "will add to the respective pages a box or menu item with a ".
00519          "list of libraries associated with the data type.  This list ".
00520          "will appear in a box on the page by default.  To place this ".
00521          "list as a menu item rather than a box, check the appropriate boxes ".
00522          "above"),
00523       '#options' => $types,
00524       '#default_value' => $defaults,
00525       '#weight' => 1,
00526    );
00527 }
00528 /**
00529  *
00530  *
00531  * @ingroup tripal_library
00532  */
00533 function get_tripal_library_admin_form_cleanup_set(&$form) {
00534    $form['cleanup'] = array(
00535       '#type' => 'fieldset',
00536       '#title' => t('Clean Up')
00537    );
00538    $form['cleanup']['description'] = array(
00539        '#type' => 'item',
00540        '#value' => t("With Drupal and chado residing in different databases ".
00541           "it is possible that nodes in Drupal and libraries in Chado become ".
00542           "\"orphaned\".  This can occur if an library node in Drupal is ".
00543           "deleted but the corresponding chado library is not and/or vice ".
00544           "versa. Click the button below to resolve these discrepancies."),
00545        '#weight' => 1,
00546    );
00547    $form['cleanup']['button'] = array(
00548       '#type' => 'submit',
00549       '#value' => t('Clean up orphaned libraries'),
00550       '#weight' => 2,
00551    );
00552 }
00553 /**
00554  *
00555  *
00556  * @ingroup tripal_library
00557  */
00558 function get_tripal_library_admin_form_taxonomy_set(&$form) {
00559    $form['taxonify'] = array(
00560       '#type' => 'fieldset',
00561       '#title' => t('Assign Drupal Taxonomy to Library Features')
00562    );
00563 
00564    // get the list of libraries
00565    $sql = "SELECT * FROM {Library} ORDER BY uniquename";
00566    $previous_db = tripal_db_set_active('chado');  // use chado database
00567    $lib_rset = db_query($sql);
00568    tripal_db_set_active($previous_db);  // now use drupal database
00569 
00570    // iterate through all of the libraries
00571    $lib_boxes = array();
00572    while($library = db_fetch_object($lib_rset)){
00573       $lib_boxes[$library->library_id] = "$library->name";
00574    }
00575 
00576    $form['taxonify']['description'] = array(
00577        '#type' => 'item',
00578        '#value' => t("Drupal allows for assignment of \"taxonomy\" or catagorical terms to " .
00579                      "nodes. These terms allow for advanced filtering during searching. This option allows ".
00580                      "for setting taxonomy only for features that belong to the selected libraries below.  All other features will be unaffected.  To set taxonomy for all features in the site see the Feature Administration page."),
00581      '#weight' => 1,
00582    );
00583 
00584    $form['taxonify']['tx-libraries'] = array (
00585      '#title'       => t('Libraries'),
00586      '#type'        => t('checkboxes'),
00587      '#description' => t("Check the libraries whose features you want to reset taxonomy.  Note: this list contains all libraries, even those that may not be synced."),
00588      '#required'    => FALSE,
00589      '#prefix'      => '<div id="lib_boxes">',
00590      '#suffix'      => '</div>',
00591      '#options'     => $lib_boxes,
00592      '#weight'      => 2
00593    );
00594    $form['taxonify']['tx-button'] = array(
00595       '#type' => 'submit',
00596       '#value' => t('Set Feature Taxonomy'),
00597       '#weight'      => 3
00598    );
00599 }
00600 /**
00601  *
00602  * @ingroup tripal_library
00603  */
00604 function get_tripal_library_admin_form_reindex_set(&$form) {
00605    // define the fieldsets
00606    $form['reindex'] = array(
00607       '#type' => 'fieldset',
00608       '#title' => t('Reindex Library Features')
00609    );
00610 
00611    // get the list of libraries
00612    $sql = "SELECT * FROM {Library} ORDER BY uniquename";
00613    $previous_db = tripal_db_set_active('chado');  // use chado database
00614    $lib_rset = db_query($sql);
00615    tripal_db_set_active($previous_db);  // now use drupal database
00616 
00617    // iterate through all of the libraries
00618    $lib_boxes = array();
00619    while($library = db_fetch_object($lib_rset)){
00620       $lib_boxes[$library->library_id] = "$library->name";
00621    }
00622    $form['reindex']['description'] = array(
00623        '#type' => 'item',
00624        '#value' => t("This option allows for reindexing of only those features that belong to the selected libraries below. All other features will be unaffected.  To reindex all features in the site see the Feature Administration page."),
00625      '#weight' => 1,
00626    );
00627 
00628    $form['reindex']['re-libraries'] = array (
00629      '#title'       => t('Libraries'),
00630      '#type'        => t('checkboxes'),
00631      '#description' => t("Check the libraries whoee features you want to reindex. Note: this list contains all libraries, even those that may not be synced."),
00632      '#required'    => FALSE,
00633      '#prefix'      => '<div id="lib_boxes">',
00634      '#suffix'      => '</div>',
00635      '#options'     => $lib_boxes,
00636      '#weight' => 2,
00637    );
00638    $form['reindex']['re-button'] = array(
00639       '#type' => 'submit',
00640       '#value' => t('Reindex Features'),
00641       '#weight' => 3,
00642    );
00643 }
00644 /**
00645  *
00646  * @ingroup tripal_library
00647  */
00648 function get_tripal_library_admin_form_sync_set (&$form) {
00649    // define the fieldsets
00650    $form['sync'] = array(
00651       '#type' => 'fieldset',
00652       '#title' => t('Sync Libraries')
00653    );
00654 
00655 
00656    // get the list of libraries
00657    $sql = "SELECT * FROM {Library} ORDER BY uniquename";
00658    $previous_db = tripal_db_set_active('chado');  // use chado database
00659    $lib_rset = db_query($sql);
00660    tripal_db_set_active($previous_db);  // now use drupal database
00661 
00662    // if we've added any libraries to the list that can be synced
00663    // then we want to build the form components to allow the user
00664    // to select one or all of them.  Otherwise, just present
00665    // a message stating that all libraries are currently synced.
00666    $lib_boxes = array();
00667    $added = 0;
00668    while($library = db_fetch_object($lib_rset)){
00669       // check to see if the library is already present as a node in drupal.
00670       // if so, then skip it.
00671       $sql = "SELECT * FROM {chado_library} WHERE library_id = %d";
00672       if(!db_fetch_object(db_query($sql,$library->library_id))){
00673          $lib_boxes[$library->library_id] = "$library->name";
00674          $added++;
00675       }
00676    }
00677 
00678    // if we have libraries we need to add to the checkbox then
00679    // build that form element
00680    if($added > 0){
00681       $lib_boxes['all'] = "All Libraries";
00682 
00683       $form['reindex']['description'] = array(
00684        '#type' => 'item',
00685        '#value' => t("This option allows for the creation of Drupal content for libraries in chado. Only the selected libraries will be synced."),
00686      '#weight' => 1,
00687       );
00688 
00689 
00690       $form['sync']['libraries'] = array (
00691         '#title'       => t('Available Libraries'),
00692         '#type'        => t('checkboxes'),
00693         '#description' => t("Check the libraries you want to sync.  Drupal content will be created for each of the libraries listed above.  Select 'All Libraries' to sync all of them."),
00694         '#required'    => FALSE,
00695         '#prefix'      => '<div id="lib_boxes">',
00696         '#suffix'      => '</div>',
00697         '#options'     => $lib_boxes,
00698       '#weight' => 2,
00699       );
00700       $form['sync']['button'] = array(
00701          '#type' => 'submit',
00702          '#value' => t('Sync Libraries'),
00703        '#weight' => 3,
00704       );
00705    }
00706    // we don't have any libraries to select from
00707    else {
00708       $form['sync']['value'] = array(
00709          '#value' => t('All libraries in Chado are currently synced with Drupal.')
00710       );
00711    }
00712 }
00713 /**
00714  *
00715  * @ingroup tripal_library
00716  */
00717 function tripal_library_admin_validate($form, &$form_state) {
00718    global $user;  // we need access to the user info
00719    $job_args = array();
00720 
00721    // Submit the Sync Job if selected
00722    if ($form_state['values']['op'] == t('Sync Libraries')) {
00723 
00724       // check to see if the user wants to sync chado and drupal.  If
00725       // so then we need to register a job to do so with tripal
00726       $libraries = $form_state['values']['libraries'];
00727       $do_all = FALSE;
00728       $to_sync = array();
00729 
00730       foreach ($libraries as $library_id){
00731          if(preg_match("/^all$/i",$library_id)){
00732             $do_all = TRUE;
00733          }
00734          if($library_id and preg_match("/^\d+$/i",$library_id)){
00735             // get the library info
00736             $sql = "SELECT * FROM {Library} WHERE library_id = %d";
00737             $previous_db = tripal_db_set_active('chado');  // use chado database
00738             $library = db_fetch_object(db_query($sql,$library_id));
00739             tripal_db_set_active($previous_db);  // now use drupal database
00740             $to_sync[$library_id] = $library->name;
00741          }
00742       }
00743 
00744       // submit the job to the tripal job manager
00745       if($do_all){
00746          tripal_add_job('Sync all libraries','tripal_library','tripal_library_sync_libraries',$job_args,$user->uid);
00747       }
00748       else{
00749          foreach($to_sync as $library_id => $name){
00750             $job_args[0] = $library_id;
00751             tripal_add_job("Sync library: $name",'tripal_library','tripal_library_sync_libraries',$job_args,$user->uid);
00752          }
00753       }
00754    }
00755 
00756    // -------------------------------------
00757    // Submit the Reindex Job if selected
00758    if ($form_state['values']['op'] == t('Reindex Features')) {
00759       $libraries = $form_state['values']['re-libraries'];
00760       foreach ($libraries as $library_id){
00761          if($library_id and preg_match("/^\d+$/i",$library_id)){
00762             // get the library info
00763             $sql = "SELECT * FROM {Library} WHERE library_id = %d";
00764             $previous_db = tripal_db_set_active('chado');  // use chado database
00765             $library = db_fetch_object(db_query($sql,$library_id));
00766             tripal_db_set_active($previous_db);  // now use drupal database
00767             $job_args[0] = $library_id;
00768             tripal_add_job("Reindex features for library: $library->name",'tripal_library',
00769              'tripal_library_reindex_features',$job_args,$user->uid);
00770          }
00771       }
00772    }
00773 
00774    // -------------------------------------
00775    // Submit the Taxonomy Job if selected
00776    if ($form_state['values']['op'] == t('Set Feature Taxonomy')) {
00777       $libraries = $form_state['values']['tx-libraries'];
00778       foreach ($libraries as $library_id){
00779          if($library_id and preg_match("/^\d+$/i",$library_id)){
00780             // get the library info
00781             $sql = "SELECT * FROM {Library} WHERE library_id = %d";
00782             $previous_db = tripal_db_set_active('chado');  // use chado database
00783             $library = db_fetch_object(db_query($sql,$library_id));
00784             tripal_db_set_active($previous_db);  // now use drupal database
00785             $job_args[0] = $library_id;
00786             tripal_add_job("Set taxonomy for features in library: $library->name",'tripal_library',
00787              'tripal_library_taxonify_features',$job_args,$user->uid);
00788          }
00789       }
00790    }
00791    // -------------------------------------
00792    // Submit the Cleanup Job if selected
00793    if ($form_state['values']['op'] == t('Clean up orphaned libraries')) {
00794       tripal_add_job('Cleanup orphaned libraries','tripal_library',
00795          'tripal_library_cleanup',$job_args,$user->uid);
00796    }
00797 }
00798 /**
00799  *
00800  * @ingroup tripal_library
00801  */
00802 function tripal_library_show_libraries (){
00803    // Show libraries stored in Drupal's {chado_library} table
00804    $sql = "SELECT COUNT(library_id) FROM {chado_library}";
00805    $no_libs = db_result(db_query ($sql));
00806    if($no_libs != 0) {
00807       $libraries = get_chado_libraries ();
00808       if($no_libs != count($libraries)) {
00809          drupal_set_message("Synchronization needed.");
00810       }
00811       return theme('tripal_library_library_table', &$libraries);
00812    } else {
00813       return t("No library exists. Please contact administrators to ".
00814                "synchronize libraries.");
00815    }
00816 }
00817 
00818 /**
00819  *
00820  * @ingroup tripal_library
00821  */
00822 function tripal_library_cron (){
00823 
00824 }
00825 /**
00826  *
00827  *                  CHADO_LIBRARY NODE FUNCTIONS
00828  *
00829  *  The following function proves access control for users trying to
00830  *  perform actions on data managed by this module
00831  *
00832  * @ingroup tripal_library
00833  */
00834 function tripal_library_library_access($op, $node, $account){
00835    if ($op == 'create') {
00836       return user_access('create chado_library content', $account);
00837    }
00838 
00839    if ($op == 'update') {
00840       if (user_access('edit any chado_library content', $account) ||
00841       (user_access('edit own chado_library content', $account) &&
00842       ($account->uid == $node->uid))){
00843          return TRUE;
00844       }
00845    }
00846 
00847    if ($op == 'delete') {
00848       if (user_access('delete any chado_library content', $account) ||
00849       (user_access('delete own chado_library content', $account) &&
00850       ($account->uid == $node->uid))) {
00851          return TRUE;
00852       }
00853    }
00854 }
00855 /**
00856  *  validates submission of form when adding or updating a library node
00857  *
00858  * @ingroup tripal_library
00859  */
00860 function chado_library_validate($node){
00861    $lib = 0;
00862    // check to make sure the unique name on the library is unique
00863    // before we try to insert into chado.
00864    if($node->library_id){
00865       $sql = "SELECT * FROM ".
00866              "{Library} WHERE ".
00867              "uniquename = '%s' ".
00868              "AND NOT library_id = %d";
00869       $previous_db = tripal_db_set_active('chado');
00870       $lib = db_fetch_object(db_query($sql, $node->uniquename,
00871       $node->library_id));
00872       tripal_db_set_active($previous_db);
00873    } else {
00874       $sql = "SELECT * FROM ".
00875              "{Library} ".
00876              "WHERE uniquename = '%s'";
00877       $previous_db = tripal_db_set_active('chado');
00878       $lib = db_fetch_object(db_query($sql, $node->uniquename));
00879       tripal_db_set_active($previous_db);
00880    }
00881    if($lib){
00882       form_set_error('uniquename',t('The unique library name already exists. '.
00883                                     'Please choose another'));
00884    }
00885 }
00886 
00887 /**
00888  *  When a new chado_library node is created we also need to add information
00889  *  to our chado_library table.  This function is called on insert of a new node
00890  *  of type 'chado_library' and inserts the necessary information.
00891  *
00892  * @ingroup tripal_library
00893  */
00894 function chado_library_insert($node){
00895 
00896    // get the library type id
00897    $values = array(
00898       'cv_id' => array(
00899          'name' => 'tripal'
00900       ),
00901       'name' => $node->library_type
00902    );
00903    $type = tripal_core_chado_select('cvterm',array('cvterm_id'),$values);
00904 
00905    $values = array(
00906       'name' => $node->title,
00907       'uniquename' => $node->uniquename,
00908       'organism_id' => $node->organism_id,
00909       'type_id' => $type[0]->cvterm_id
00910    );
00911    $library = tripal_core_chado_insert('library', $values);
00912    if ($library) {
00913        // add the description property
00914       tripal_library_insert_property($library['library_id'],'library_description',$node->library_description);
00915 
00916       // make sure the entry for this feature doesn't already exist in the chado_feature table
00917       // if it doesn't exist then we want to add it.
00918       $library_id = chado_get_id_for_node('library',$node) ;
00919       if(!$library_id){
00920          // next add the item to the drupal table
00921          $sql = "INSERT INTO {chado_library} (nid, vid, library_id) ".
00922                 "VALUES (%d, %d, %d)";
00923          db_query($sql,$node->nid,$node->vid,$library['library_id']);
00924       }
00925    } else {
00926     drupal_set_message('Unable to add library.', 'warning');
00927     watchdog('tripal_library', 
00928       'Insert feature: Unable to create library where values: %values', 
00929       array('%values' => print_r($values, TRUE)),
00930       WATCHDOG_WARNING
00931     );
00932   }
00933 }
00934 /**
00935  * Update nodes
00936  *
00937  * @ingroup tripal_library
00938  */
00939 function chado_library_update($node){
00940    if($node->revision){
00941       // TODO -- decide what to do about revisions
00942    } else {
00943       $library_id = chado_get_id_for_node('library',$node) ;
00944 
00945       // get the library type id
00946       $values = array(
00947          'cv_id' => array(
00948             'name' => 'tripal'
00949          ),
00950          'name' => $node->library_type
00951       );
00952       $type = tripal_core_chado_select('cvterm',array('cvterm_id'),$values);
00953 
00954       // update the library record
00955       $match = array(
00956          'library_id' => $library_id,
00957       );
00958       $values = array(
00959          'name' => $node->title,
00960          'uniquename' => $node->uniquename,
00961          'organism_id' => $node->organism_id,
00962          'type_id' => $type[0]->cvterm_id
00963       );
00964       $status = tripal_core_chado_update('library', $match,$values); 
00965 
00966       tripal_library_update_property($library_id,'library_description',$node->library_description);
00967    }
00968 }
00969 
00970 
00971 /**
00972  * Add the library as a taxonomy term for associating with library_features
00973  *
00974  * @ingroup tripal_library
00975  */
00976 function tripal_library_add_taxonomy ($node,$library_id){
00977 
00978    //include the file containing the required functions.  We only have to
00979    // do this because Drupal 6 fails to do this globally for us and
00980    // the drupal_execute function below won't work
00981    module_load_include('inc', 'taxonomy', 'taxonomy.admin');
00982 
00983    /*   // get the vocabulary id
00984     $vocabularies = taxonomy_get_vocabularies();
00985     $vid = NULL;
00986     foreach($vocabularies as $vocab){
00987     if($vocab->name == 'DNA Libraries'){
00988     $vid = $vocab->vid;
00989     }
00990     }
00991 
00992     if(!$vid){  */
00993    // add the vocabulary
00994    $vocab_form['values']['name'] = 'DNA Libraries';
00995    $vocab_form['values']['description'] = 'Allows for associating/searching of library features by library name';
00996    $vocab_form['values']['help'] = '';
00997    $vocab_form['values']['module'] = 'taxonomy';
00998    drupal_execute('taxonomy_form_vocabulary',$vocab_form);
00999    return;
01000    //   }
01001 
01002    // make sure this term doesn't already exist.  If it doesn't then add it
01003    if($vid){
01004       $tree = taxonomy_get_tree($vid);
01005       $found = 0;
01006       foreach ($tree as $term) {
01007          if($term->name == $node->title){
01008             $found = 1;
01009          }
01010       }
01011 
01012       // add the term to the vocabulary
01013       if(!$found){
01014          $form_state = array();
01015          $form_state['values']['name'] = $node->title;
01016          $form_state['values']['description'] = $library_id;
01017          drupal_execute('taxonomy_form_term',$form_state,$vid);
01018       }
01019    }
01020 }
01021 
01022 /**
01023  *  When editing or creating a new node of type 'chado_library' we need
01024  *  a form.  This function creates the form that will be used for this.
01025  *
01026  * @ingroup tripal_library
01027  */
01028 function chado_library_form ($node){
01029    $form = array();
01030 
01031    $library = $node->library;
01032    
01033    // get the default values
01034    $uniquename = $node->uniquename;
01035    if(!$uniquename){
01036      $uniquename = $library->uniquename;
01037    }
01038    $library_type = $node->library_type;
01039    if(!$library_type){
01040       $library_type = $library->type_id->name;
01041    }
01042    $organism_id = $node->organism_id;
01043    if(!$organism_id){
01044       $organism_id = $library->organism_id->organism_id;
01045    }
01046    $library_description = $node->library_description;
01047    if(!$library_description){
01048      $libprop = tripal_library_get_property($library->library_id,'library_description');
01049      $library_description = $libprop->value;
01050    }
01051 
01052    // keep track of the library id if we have.  If we do have one then
01053    // this is an update as opposed to an insert.
01054    $form['library_id'] = array(
01055       '#type' => 'value',
01056       '#value' => $library->library_id,
01057    );
01058 
01059    $form['title']= array(
01060       '#type'          => 'textfield',
01061       '#title'         => t('Library Title'),
01062       '#description'   => t('Please enter the title for this library. '.
01063                             'This appears at the top of the library page.'),
01064       '#required'      => TRUE,
01065       '#default_value' => $node->title,
01066       '#weight'        => 1
01067    );
01068 
01069    $form['uniquename']= array(
01070       '#type'          => 'textfield',
01071       '#title'         => t('Unique Library Name'),
01072       '#description'   => t('Please enter a unique name for this library'),
01073       '#required'      => TRUE,
01074       '#default_value' => $uniquename,
01075       '#weight'        => 2
01076    );
01077 
01078    // These library types should not be hard coded, but for now the are...
01079    $library_types = array();
01080    $library_types[''] = '';
01081    $library_types['cdna_library'] = 'cDNA Library';
01082    $library_types['bac_library'] = 'BAC Library';
01083    $library_types['fosmid_library'] = 'FOSMID Library';
01084    $library_types['cosmid_library'] = 'COSMID Library';
01085    $library_types['yac_library'] = 'YAC Library';
01086      
01087    
01088    $form['library_type'] = array (
01089       '#title'       => t('Library Type'),
01090       '#type'        => t('select'),
01091       '#description' => t("Choose the library type."),
01092       '#required'    => TRUE,
01093       '#default_value' => $library_type,
01094       '#options'     => $library_types,
01095       '#weight'      => 3
01096    );
01097 
01098    // get the list of organisms
01099    $sql = "SELECT * FROM {Organism}";
01100    $previous_db = tripal_db_set_active('chado');  // use chado database
01101    $org_rset = db_query($sql);
01102    tripal_db_set_active($previous_db);  // now use drupal database
01103 
01104    $organisms = array();
01105    $organisms[''] = '';
01106    while($organism = db_fetch_object($org_rset)){
01107       $organisms[$organism->organism_id] =
01108       "$organism->genus $organism->species ($organism->common_name)";
01109    }
01110 
01111    $form['organism_id'] = array (
01112      '#title'       => t('Organism'),
01113      '#type'        => t('select'),
01114      '#description' => t("Choose the organism with which this library is ".
01115                          "associated."),
01116      '#required'    => TRUE,
01117      '#default_value' => $organism_id,
01118      '#options'     => $organisms,
01119      '#weight'      => 4,
01120    );
01121 
01122    $form['library_description']= array(
01123       '#type'          => 'textarea',
01124       '#title'         => t('Library Description'),
01125       '#description'   => t('A brief description of the library'),
01126       '#required'      => TRUE,
01127       '#default_value' => $library_description,
01128       '#weight'        => 5
01129    );
01130 
01131    return $form;
01132 }
01133 /**
01134  *
01135  *
01136  * @ingroup tripal_library
01137  */
01138 function tripal_library_sync_libraries ($library_id = NULL, $job_id = NULL){
01139 
01140    global $user;
01141    $page_content = '';
01142 
01143    // get the list of libraries and create new nodes
01144    if(!$library_id){
01145       $sql = "SELECT * FROM {Library} L";
01146       $previous_db = tripal_db_set_active('chado');  // use chado database
01147       $results = db_query($sql);
01148       tripal_db_set_active($previous_db);  // now use drupal database
01149    } else {
01150       $sql = "SELECT * FROM {Library} L WHERE library_id = %d";
01151       $previous_db = tripal_db_set_active('chado');  // use chado database
01152       $results = db_query($sql,$library_id);
01153       tripal_db_set_active($previous_db);  // now use drupal database
01154    }
01155 
01156    // We'll use the following SQL statement for checking if the library
01157    // already exists as a drupal node.
01158    $sql = "SELECT * FROM {chado_library} ".
01159           "WHERE library_id = %d";
01160 
01161    while($library = db_fetch_object($results)){
01162       // check if this library already exists in the drupal database. if it
01163       // does then skip this library and go to the next one.
01164       if(!db_fetch_object(db_query($sql,$library->library_id))){
01165 
01166          $new_node = new stdClass();
01167          $new_node->type = 'chado_library';
01168          $new_node->uid = $user->uid;
01169          $new_node->title = "$library->name";
01170          $new_node->library_id = $library->library_id;
01171          $new_node->organism_id = $library->organism_id;
01172          $new_node->uniquename = $library->uniquename;
01173          $new_node->type_id = $library->type_id;
01174 
01175          node_validate($new_node);
01176          if(!form_get_errors()){
01177             $node = node_submit($new_node);
01178             node_save($node);
01179             if($node->nid){
01180                $page_content .= "Added $library->name<br>";
01181             }
01182          }
01183       } else {
01184          $page_content .= "Skipped $library->name<br>";
01185       }
01186    }
01187    return $page_content;
01188 }
01189 
01190 /**
01191  *  When a node is requested by the user this function is called to allow us
01192  *  to add auxiliary data to the node object.
01193  *
01194  * @ingroup tripal_library
01195  */
01196 function chado_library_load($node){
01197    // get the feature details from chado
01198    $library_id = chado_get_id_for_node('library',$node);
01199 
01200    $values = array('library_id' => $library_id);
01201    $library = tripal_core_generate_chado_var('library',$values);
01202 
01203    $additions->library = $library;
01204    return $additions;
01205 
01206 }
01207 /**
01208  *  This function customizes the view of the chado_library node.  It allows
01209  *  us to generate the markup. This function is required for node [Preview]
01210  *
01211  * @ingroup tripal_library
01212  */
01213 function chado_library_view ($node, $teaser = FALSE, $page = FALSE) {
01214    // use drupal's default node view:
01215    if (!$teaser) {
01216 
01217       $node = node_prepare($node, $teaser);
01218 
01219       // If Hook_view() is called by Hook_form(), we'll only have orgnism_id
01220       // but not genus/species/common_name. We need to get those from chado
01221       // database so they will show up in preview
01222       if(!$node->genus) {
01223          $previous_db = tripal_db_set_active('chado');
01224          $sql = "SELECT * FROM {organism} WHERE organism_id = %d";
01225          $data = db_fetch_object(db_query($sql, $node->organism_id));
01226          $node->genus = $data->genus;
01227          $node->species = $data->species;
01228          $node->common_name = $data->common_name;
01229          tripal_db_set_active($previous_db);
01230       }
01231    }
01232    return $node;
01233 }
01234 
01235 /**
01236  *  This function creates the html markup for the library table.
01237  *  It can be overridden in the theme for the site by adding a php
01238  *  method in the template.php file named
01239  *  [theme_name]_tripal_library_library_table(&$libraries)
01240  *
01241  * @ingroup tripal_library
01242  */
01243 
01244 function theme_tripal_library_library_table ($libraries) {
01245 
01246    // cycle through the libraries and build the libraries page
01247    $output = "<div id=\"libraries\">";
01248    $output .= '<table>';
01249    $output .= "<tr>";
01250    $output .= "<th>Name</th>";
01251    $output .= "<th>Type</th>";
01252    $output .= "<th>Organism</th>";
01253    $output .= "<th>Description</th>";
01254    $output .= "</tr>";
01255 
01256    foreach($libraries as $library){
01257       $lib_url = url("node/$library->node_id");
01258       $output .= "<tr>";
01259       $output .= "<td>".
01260                  "  <a href=\"$lib_url\">$library->name</a>".
01261                  "</td>";
01262 
01263       if(strcasecmp($library->type_name, 'bac_library') == 0){
01264          $output .= "<td>BAC</td>";
01265       }
01266       elseif(strcasecmp($library->type_name, 'cdna_library') == 0){
01267          $output .= "<td>cDNA</td>";
01268       }
01269       else{
01270          $output .= "<td>$library->type_name</td>";
01271       }
01272       $output .= "<td nowrap>".
01273                  " $library->common_name".
01274                  "</td>";
01275       $description = $library->library_description;
01276       $output .= "<td>$description</td>";
01277 
01278       $output .= "</tr>";
01279    }
01280    $output .= "</table>";
01281    $output .= "</div>";
01282 
01283    return $output;
01284 }
01285 
01286 /**
01287  *
01288  * @ingroup tripal_library
01289  */
01290 function tripal_library_feature_set_taxonomy($library_id = NULL){
01291 
01292    //TO DO : return usable error if vocabs don't exist
01293    // get the list of vocabularies and find our two vocabularies of interest
01294    $vocabularies = taxonomy_get_vocabularies();
01295    $vid = NULL;
01296    foreach($vocabularies as $vocab){
01297       if($vocab->name == 'Library'){
01298          $vid = $vocab->vid;
01299       }
01300    }
01301    if(!$vid){
01302       return;
01303    }
01304 
01305    // We'll use the following SQL statement for getting the node info
01306    if($library_id){
01307       print "Finding features for library with ID: $library_id\n";
01308       $sql = "SELECT LF.feature_id, L.library_id, L.name as libname ".
01309              "FROM {library_feature} LF ".
01310              "INNER JOIN Library L ON LF.library_id = L.library_id ".
01311              "WHERE L.library_id = $library_id ".
01312              "ORDER BY LF.feature_id";
01313       $previous_db = tripal_db_set_active('chado');  // use chado database
01314       $features = db_query($sql);
01315       tripal_db_set_active($previous_db);  // now use drupal database
01316    } else {
01317       print "Finding features for all libraries\n";
01318       $sql = "SELECT LF.feature_id, L.library_id, L.name as libname ".
01319              "FROM {library_feature} LF ".
01320              "INNER JOIN Library L ON LF.library_id = L.library_id ".
01321              "ORDER BY LF.feature_id";
01322       $previous_db = tripal_db_set_active('chado');  // use chado database
01323       $features = db_query($sql);
01324       tripal_db_set_active($previous_db);  // now use drupal database
01325    }
01326 
01327    $node_sql = "SELECT * FROM {chado_feature} CF ".
01328                "  INNER JOIN {node} N ON CF.nid = N.nid ".
01329                "WHERE feature_id = %d";
01330 
01331    // iterate through the features and add the taxonomy
01332    while($feature = db_fetch_object($features)){
01333       $node = db_fetch_object(db_query($node_sql,$feature->feature_id));
01334       $tags["$vid"] = $feature->libname;
01335       $terms['tags'] = $tags;
01336       taxonomy_node_save($node,$terms);
01337       print "Updated $feature->feature_id as $feature->libname\n";
01338    }
01339 }
01340 /**
01341  *
01342  * @ingroup tripal_library
01343  */
01344 function tripal_library_reindex_features ($library_id = NULL, $job_id = NULL){
01345    $i = 0;
01346 
01347    // if the caller provided a library_id then get all of the features
01348    // associated with the library. Otherwise get all sequences assoicated
01349    // with all libraries.
01350    if($library_id){
01351       $sql = "SELECT LF.feature_id, L.library_id, L.name as libname ".
01352              " FROM {library_feature} LF ".
01353              "  INNER JOIN Library L ON LF.library_id = L.library_id ".
01354              "WHERE L.library_id = $library_id ".
01355              "ORDER BY LF.feature_id";
01356       $previous_db = tripal_db_set_active('chado');  // use chado database
01357       $results = db_query($sql);
01358       tripal_db_set_active($previous_db);  // now use drupal database
01359    }
01360    else {
01361       $sql = "SELECT LF.feature_id, L.library_id, L.name as libname ".
01362              " FROM {library_feature} LF ".
01363              "  INNER JOIN Library L ON LF.library_id = L.library_id ".
01364              "ORDER BY LF.feature_id";
01365       $previous_db = tripal_db_set_active('chado');  // use chado database
01366       $results = db_query($sql);
01367       tripal_db_set_active($previous_db);  // now use drupal database
01368    }
01369 
01370    // load into ids array
01371    $count = 0;
01372    $ids = array();
01373    while($id = db_fetch_object($results)){
01374       $ids[$count] = $id->feature_id;
01375       $count++;
01376    }
01377 
01378    $interval = intval($count * 0.01);
01379    foreach($ids as $feature_id){
01380       // update the job status every 1% features
01381       if($job_id and $i % interval == 0){
01382          tripal_job_set_progress($job_id,intval(($i/$count)*100));
01383       }
01384       tripal_feature_sync_feature ($feature_id);
01385       $i++;
01386    }
01387 }
01388 /**
01389  *
01390  * @ingroup tripal_library
01391  */
01392 function tripal_library_taxonify_features ($library_id = NULL, $job_id = NULL){
01393    $i = 0;
01394 
01395    // if the caller provided a library_id then get all of the features
01396    // associated with the library. Otherwise get all sequences assoicated
01397    // with all libraries.
01398    if($library_id){
01399       $sql = "SELECT LF.feature_id, L.library_id, L.name as libname ".
01400              " FROM {library_feature} LF ".
01401              "  INNER JOIN Library L ON LF.library_id = L.library_id ".
01402              "WHERE L.library_id = $library_id ".
01403              "ORDER BY LF.feature_id";
01404       $previous_db = tripal_db_set_active('chado');  // use chado database
01405       $results = db_query($sql);
01406       tripal_db_set_active($previous_db);  // now use drupal database
01407    }
01408    else {
01409       $sql = "SELECT LF.feature_id, L.library_id, L.name as libname ".
01410              " FROM {library_feature} LF ".
01411              "  INNER JOIN Library L ON LF.library_id = L.library_id ".
01412              "ORDER BY LF.feature_id";
01413       $previous_db = tripal_db_set_active('chado');  // use chado database
01414       $results = db_query($sql);
01415       tripal_db_set_active($previous_db);  // now use drupal database
01416    }
01417 
01418    // load into ids array
01419    $count = 0;
01420    $ids = array();
01421    while($id = db_fetch_object($results)){
01422       $ids[$count] = $id->feature_id;
01423       $count++;
01424    }
01425 
01426    // make sure our vocabularies are set before proceeding
01427    tripal_feature_set_vocabulary();
01428 
01429    // use this SQL for getting the nodes
01430    $nsql =  "SELECT * FROM {chado_feature} CF ".
01431             "  INNER JOIN {node} N ON N.nid = CF.nid ".
01432             "WHERE feature_id = %d";
01433 
01434    // iterate through the features and set the taxonomy
01435    $interval = intval($count * 0.01);
01436    foreach($ids as $feature_id){
01437       // update the job status every 1% features
01438       if($job_id and $i % interval == 0){
01439          tripal_job_set_progress($job_id,intval(($i/$count)*100));
01440       }
01441       $node = db_fetch_object(db_query($nsql,$feature_id));
01442       tripal_feature_set_taxonomy($node,$feature_id);
01443       $i++;
01444    }
01445 }
01446 /**
01447  * Delete data from drupal and chado databases when a node is deleted
01448  * @ingroup tripal_library
01449  */
01450 function chado_library_delete(&$node){
01451    // Before removing, get library_id so we can remove it from chado database
01452    // later
01453    $sql_drupal = "SELECT library_id ".
01454                  "FROM {chado_library} ".
01455                  "WHERE nid = %d AND vid = %d";
01456    $library_id = db_result(db_query($sql_drupal, $node->nid, $node->vid));
01457 
01458    // Remove data from {chado_library}, {node} and {node_revisions} tables of
01459    // drupal database
01460    $sql_del = "DELETE FROM {chado_library} ".
01461               "WHERE nid = %d ".
01462               "AND vid = %d";
01463    db_query($sql_del, $node->nid, $node->vid);
01464    $sql_del = "DELETE FROM {node} ".
01465               "WHERE nid = %d ".
01466               "AND vid = %d";
01467    db_query($sql_del, $node->nid, $node->vid);
01468    $sql_del = "DELETE FROM {node_revisions} ".
01469               "WHERE nid = %d ".
01470               "AND vid = %d";
01471    db_query($sql_del, $node->nid, $node->vid);
01472 
01473    // Remove data from library and libraryprop tables of chado database as well
01474    $previous_db = tripal_db_set_active('chado');
01475    db_query("DELETE FROM {library} WHERE library_id = %d", $library_id);
01476    db_query("DELETE FROM {libraryprop} WHERE library_id = %d", $library_id);
01477    tripal_db_set_active($previous_db);
01478 }
01479 
01480 /**
01481  * Display block with libraries
01482  * @param op    - parameter to define the phase being called for the block
01483  * @param delta - id of the block to return (ignored when op is list)
01484  * @param edit  - when op is save, contains the submitted form data
01485  *
01486  * @ingroup tripal_library
01487  */
01488 function tripal_library_block($op = 'list', $delta = '0', $edit = array()){
01489    switch($op){
01490       case 'list':
01491 
01492          $blocks['libreferences']['info'] = t('Tripal Library References');
01493          $blocks['libreferences']['cache'] = BLOCK_NO_CACHE;
01494 
01495          $blocks['libbase']['info'] = t('Tripal Library Details');
01496          $blocks['libbase']['cache'] = BLOCK_NO_CACHE;
01497 
01498          $blocks['libsynonyms']['info'] = t('Tripal Library Synonyms');
01499          $blocks['libsynonyms']['cache'] = BLOCK_NO_CACHE;
01500 
01501          $blocks['libproperties']['info'] = t('Tripal Library Properties');
01502          $blocks['libproperties']['cache'] = BLOCK_NO_CACHE;
01503 
01504          $blocks['featurelibs']['info'] = t('Tripal Feature Libraries');
01505          $blocks['featurelibs']['cache'] = BLOCK_NO_CACHE;
01506 
01507          $blocks['orglibs']['info'] = t('Tripal Organism Libraries');
01508          $blocks['orglibs']['cache'] = BLOCK_NO_CACHE;
01509 
01510          return $blocks;
01511 
01512       case 'view':
01513          if(user_access('access chado_library content') and arg(0) == 'node' and is_numeric(arg(1))) {
01514             $nid = arg(1);
01515             $node = node_load($nid);
01516  
01517             $block = array();
01518             switch($delta){
01519                case 'libreferences':
01520                   $block['subject'] = t('References');
01521                   $block['content'] = theme('tripal_library_references',$node);
01522                   break;
01523                case 'libbase':
01524                   $block['subject'] = t('Library Details');
01525                   $block['content'] = theme('tripal_library_base',$node);
01526                   break;
01527                case 'libsynonyms':
01528                   $block['subject'] = t('Synonyms');
01529                   $block['content'] = theme('tripal_library_synonyms',$node);
01530                   break;
01531                case 'libproperties':
01532                   $block['subject'] = t('Properties');
01533                   $block['content'] = theme('tripal_library_properties',$node);
01534                   break;
01535                case 'featurelibs':
01536                   $block['subject'] = t('Libraries');
01537                   $block['content'] = theme('tripal_feature_libraries',$node);
01538                   break;
01539                case 'orglibs':
01540                   $block['subject'] = t('Libraries');
01541                   $block['content'] = theme('tripal_organism_libraries',$node);
01542                   break;
01543                default :
01544             }
01545             return $block;
01546          }
01547    }
01548 }
01549 
01550 /**
01551  * This function uses library_id's of all drupal library nodes as input and
01552  * pull the library information (name, uniquename, type, genus, species,
01553  * common_name, description) from chado database. The return type is an object
01554  * array that stores sorted $library objects
01555  *
01556  * This function is DEPRECATED
01557  * Please use tripal_core_chado_generate_vars
01558  * 
01559  * @ingroup tripal_library_api
01560  */
01561 function get_chado_libraries() {
01562    $sql_drupal = "SELECT COUNT (library_id) FROM {chado_library}";
01563    $no_libs = db_result(db_query($sql_drupal));
01564    if ($no_libs != 0) {
01565       // Get library_id's from drupal
01566       $sql = "SELECT library_id, nid FROM {chado_library}";
01567       $result = db_query($sql);
01568       $previous_db = tripal_db_set_active('chado');
01569       // Get library info from chado's library, organism, and cvterm tables
01570       $sql_info = "SELECT L.name, uniquename, genus, species, common_name, ".
01571                   "  CVT.name as type_name ".
01572                   "FROM {Library} L ".
01573                   "INNER JOIN Organism O ON L.organism_id = O.organism_id ".
01574                   "INNER JOIN CVTerm CVT ON L.type_id = CVT.cvterm_id ".
01575                   "WHERE library_id=%d";
01576       // Get library description from libraryprop if there is any
01577       $sql_desc = "SELECT value ".
01578                   "FROM {Libraryprop} LP ".
01579                   "INNER JOIN CVTerm CVT ON LP.type_id = CVT.cvterm_id ".
01580                   "WHERE library_id = %d AND CVT.name = 'library_description'";
01581       $libraries = array();
01582       while ($data = db_fetch_object($result)) {
01583          $library = db_fetch_object(db_query($sql_info, $data->library_id));
01584          $library->node_id = $data->nid;
01585          $desc = db_fetch_object(db_query($sql_desc, $data->library_id))->value;
01586          if ($desc) {
01587             $library->library_description = $desc;
01588          } else {
01589             $library->library_description = "NA";
01590          }
01591          // Use uniquename as the key so we can sort by uniquename later
01592          $key = strtolower($library->uniquename);
01593          $libraries [$key] = $library;
01594       }
01595       tripal_db_set_active($previous_db);
01596 
01597       //Sort libraries by uniquename
01598       ksort($libraries, SORT_STRING);
01599       return $libraries;
01600    }
01601 }
01602 /**
01603  *
01604  * @ingroup tripal_library
01605  */
01606 function tripal_library_cleanup($dummy = NULL, $job_id = NULL) {
01607 
01608    // build the SQL statments needed to check if nodes point to valid analyses
01609    $dsql = "SELECT * FROM {node} WHERE type = 'chado_library' order by nid";
01610    $nsql = "SELECT * FROM {node} WHERE nid = %d";
01611    $csql = "SELECT * FROM {chado_library} where nid = %d ";
01612    $cosql= "SELECT * FROM {chado_library}";
01613    $tsql = "SELECT * FROM {library} L WHERE library_id = %d";
01614 
01615    // load into nodes array
01616    $results = db_query($dsql);
01617    $count = 0;
01618    $nodes = array();
01619    while($node = db_fetch_object($results)){
01620       $nodes[$count] = $node;
01621       $count++;
01622    }
01623 
01624    // load the chado_analyses into an array
01625    $results = db_query($cosql);
01626    $cnodes = array();
01627    while($node = db_fetch_object($results)){
01628       $cnodes[$count] = $node;
01629       $count++;
01630    }
01631    $interval = intval($count * 0.01);
01632 
01633    // iterate through all of the chado_library nodes and delete those that aren't valid
01634    foreach($nodes as $nid){
01635 
01636       // update the job status every 1% analyses
01637       if($job_id and $i % $interval == 0){
01638          tripal_job_set_progress($job_id,intval(($i/$count)*100));
01639       }
01640 
01641       // first check to see if the node has a corresponding entry
01642       // in the chado_library table. If not then delete the node.
01643       $library = db_fetch_object(db_query($csql,$nid->nid));
01644       if(!$library){
01645          node_delete($nid->nid);
01646          $message = "Missing in chado_library table.... DELETING: $nid->nid\n";
01647          watchdog('tripal_library',$message,array(),WATCHDOG_WARNING);
01648          continue;
01649       }
01650       $i++;
01651    }
01652 
01653    // iterate through all of the chado_library nodes and delete those  that aren't valid
01654    foreach($cnodes as $nid){
01655       // update the job status every 1% analyses
01656       if($job_id and $i % $interval == 0){
01657          tripal_job_set_progress($job_id,intval(($i/$count)*100));
01658       }
01659       $node = db_fetch_object(db_query($nsql,$nid->nid));
01660       if(!$node){
01661          db_query("DELETE FROM {chado_library} WHERE nid = $nid->nid");        
01662          $message = "chado_library missing node.... DELETING: $nid->nid\n";
01663          watchdog('tripal_library',$message,array(),WATCHDOG_WARNING);
01664       }
01665 
01666       $i++;
01667    }
01668    return '';
01669 }
 All Classes Files Functions Variables