tripal_entities.admin.inc 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505
  1. <?php
  2. /**
  3. * Launchpad for feature administration.
  4. *
  5. * @ingroup tripal_feature
  6. */
  7. function tripal_entities_admin_view() {
  8. $output = '';
  9. // set the breadcrumb
  10. $breadcrumb = array();
  11. $breadcrumb[] = l('Home', '<front>');
  12. $breadcrumb[] = l('Administration', 'admin');
  13. $breadcrumb[] = l('Tripal', 'admin/tripal');
  14. $breadcrumb[] = l('Manage Data types', 'admin/tripal/data_types');
  15. drupal_set_breadcrumb($breadcrumb);
  16. /* // Add the view
  17. $view = views_embed_view('tripal_feature_admin_features','default');
  18. if (isset($view)) {
  19. $output .= $view;
  20. }
  21. else {
  22. $output .= '<p>The Feature module uses primarily views to provide an '
  23. . 'administrative interface. Currently one or more views needed for this '
  24. . 'administrative interface are disabled. <strong>Click each of the following links to '
  25. . 'enable the pertinent views</strong>:</p>';
  26. $output .= '<ul>';
  27. $output .= '<li>'.l('Features View', 'admin/tripal/chado/tripal_feature/views/features/enable').'</li>';
  28. $output .= '</ul>';
  29. }
  30. // Add a summary chart.
  31. //-----------------------------------
  32. $output .= theme('tripal_feature_bar_chart_type_organism_summary');
  33. drupal_add_js('
  34. Drupal.behaviors.tripalFeature_moveAdminSummaryChart = {
  35. attach: function (context, settings) {
  36. jQuery("#tripal-feature-admin-summary").insertBefore( jQuery(".view-filters") );
  37. }};
  38. ', 'inline'); */
  39. return $output;
  40. }
  41. /**
  42. *
  43. * @param unknown $form
  44. * @param unknown $form_state
  45. * @return multitype:
  46. */
  47. function tripal_entities_admin_publish_form($form, &$form_state) {
  48. $form = array();
  49. // Set the defaults.
  50. $cv_id = NULL;
  51. $term_name = NULL;
  52. // Set defaults using the form state.
  53. if (array_key_exists('values', $form_state)) {
  54. $cv_id = array_key_exists('cv_id', $form_state['values']) ? $form_state['values']['cv_id'] : NULL;
  55. $term_name = array_key_exists('term_name', $form_state['values']) ? $form_state['values']['term_name'] : NULL;
  56. }
  57. // Let the user select the vocabulary and tripal_data but only if they haven't
  58. // already selected a tripal_data.
  59. $sql = "
  60. SELECT CV.cv_id, CV.name
  61. FROM {tripal_entity_type} TET
  62. INNER JOIN {cv} CV on CV.cv_id = TET.cv_id
  63. ORDER BY CV.name
  64. ";
  65. $vocabs = chado_query($sql);
  66. $cvs = array();
  67. while ($vocab = $vocabs->fetchObject()) {
  68. $cvs[$vocab->cv_id] = $vocab->name;
  69. }
  70. $form['cv_id'] = array(
  71. '#type' => 'select',
  72. '#title' => t('Vocabulary'),
  73. '#options' => $cvs,
  74. '#required' => TRUE,
  75. '#description' => t('Select a vocabulary that contains the term you would like to set as publishable. Only vocabularies that are linked to data are shown.'),
  76. '#default_value' => $cv_id,
  77. '#ajax' => array(
  78. 'callback' => "tripal_entities_admin_publish_form_ajax_callback",
  79. 'wrapper' => 'tripal_entities_admin_publish_form',
  80. 'effect' => 'fade',
  81. 'method' => 'replace'
  82. )
  83. );
  84. // If we have a CV ID then we want to provide an autocomplete field
  85. if ($cv_id) {
  86. $form['cvterm_select']['term_name'] = array(
  87. '#title' => t('Data Type'),
  88. '#type' => 'textfield',
  89. '#description' => t("Please enter the name of the data type to set as publishable. The data type must be a valid term in the selected vocabulary. This field will autopopulate as you type to help find available data types."),
  90. '#required' => TRUE,
  91. '#default_value' => $term_name,
  92. '#autocomplete_path' => "admin/tripal/chado/tripal_cv/cvterm/auto_name/$cv_id",
  93. );
  94. $form['cvterm_select']['select_button'] = array(
  95. '#type' => 'submit',
  96. '#value' => t('Publish Data'),
  97. '#name' => 'publish',
  98. );
  99. }
  100. $form['#prefix'] = '<div id="tripal_entities_admin_publish_form">';
  101. $form['#suffix'] = '</div>';
  102. return $form;
  103. }
  104. /**
  105. * An Ajax callback for the tripal_entities_admin_publish_form..
  106. */
  107. function tripal_entities_admin_publish_form_ajax_callback($form, $form_state) {
  108. // return the form so Drupal can update the content on the page
  109. return $form;
  110. }
  111. /**
  112. * Implements hook_validate() for the tripal_entities_admin_publish_form.
  113. *
  114. */
  115. function tripal_entities_admin_publish_form_validate($form, &$form_state) {
  116. $cv_id = $form_state['values']['cv_id'];
  117. $term_name = $form_state['values']['term_name'];
  118. // Make sure the term_name is a real term in the vocabulary.
  119. $type = tripal_get_cvterm(array(
  120. 'name' => $term_name,
  121. 'cv_id' => $cv_id
  122. ));
  123. if (!$type) {
  124. form_set_error('term_name', t("The data type is not a valid name for the selected vocabulary."));
  125. }
  126. // Make sure the term is used in the site:
  127. $values = array(
  128. 'cvterm_id' => $type->cvterm_id,
  129. );
  130. $bundles = chado_select_record('tripal_entity_bundle', array('bundle_id'), $values);
  131. if (count($bundles) == 0) {
  132. form_set_error('term_name', t("The data type, %type, is not associated with data on this site and thus cannot be set as publishable.", array('%type' => $term_name)));
  133. }
  134. // Make sure the term is not already published.
  135. $values = array(
  136. 'cvterm_id' => $type->cvterm_id,
  137. 'publish' => 1,
  138. );
  139. $bundles = chado_select_record('tripal_entity_bundle', array('bundle_id'), $values);
  140. if (count($bundles) > 0) {
  141. form_set_error('term_name', t("This data type is already set as publishable."));
  142. }
  143. }
  144. /**
  145. * Implements hook_submit() for the tripal_entities_admin_publish_form.
  146. *
  147. */
  148. function tripal_entities_admin_publish_form_submit($form, &$form_state) {
  149. $cv_id = $form_state['values']['cv_id'];
  150. $term_name = $form_state['values']['term_name'];
  151. // Get the data type using the $term_name and $cv_id.
  152. $type = chado_generate_var('cvterm', array('cv_id' => $cv_id, 'name' => $term_name));
  153. // Start the transaction.
  154. $transaction = db_transaction();
  155. try {
  156. // We don't need to check if the vocabulary is used because the
  157. // form only shows those vocabs that are used.
  158. // Mark this entity as published.
  159. $match = array('cv_id' => $cv_id);
  160. $values = array('publish' => 1);
  161. $success = chado_update_record('tripal_entity_type', $match, $values);
  162. if (!$success) {
  163. throw new Exception('Cannot set the vocabulary as publishable');
  164. }
  165. // We have already checked in the validate if the term already exists
  166. // as a bundle. So, if we're here we can enable it.
  167. $match = array('cvterm_id' => $type->cvterm_id);
  168. $values = array('publish' => 1);
  169. $success = chado_update_record('tripal_entity_bundle', $match, $values);
  170. if (!$success) {
  171. throw new Exception('Cannot set the data type as publishable');
  172. }
  173. // Get the bundle
  174. $records = chado_select_record('tripal_entity_bundle', array('*'), $match);
  175. $bundle = $records[0];
  176. $bundle_name = $type->dbxref_id->db_id->name . '_' . $type->dbxref_id->accession;
  177. $entity_type_name = $type->dbxref_id->db_id->name;
  178. // Get the list of tables where this cvterm is used.
  179. $values = array('bundle_id' => $bundle->bundle_id);
  180. $tables = chado_select_record('tripal_entity_bundle_source', array('*'), $values);
  181. // Iterate through the tables.
  182. foreach ($tables as $table) {
  183. $tablename = $table->data_table;
  184. // We only want to look at base tables.
  185. if ($tablename == 'cvterm_dbxref' || $tablename == 'cvterm_relationship' ||
  186. $tablename == 'cvtermpath' || $tablename == 'cvtermprop' || $tablename == 'chadoprop' ||
  187. $tablename == 'cvtermsynonym' || preg_match('/_relationship$/', $tablename) ||
  188. preg_match('/_cvterm$/', $tablename)) {
  189. continue;
  190. }
  191. // Add in the bundle's fields.
  192. tripal_entities_add_bundle_fields($tablename, $entity_type_name, $bundle_name);
  193. }
  194. drupal_set_message(t('Data type, %type, is now set as publishable.', array('%type' => $term_name)));
  195. }
  196. catch (Exception $e) {
  197. $transaction->rollback();
  198. drupal_set_message('Failure publishing this data type: ' . $e->getMessage(), 'error');
  199. watchdog_exception('trp_entities', $e);
  200. }
  201. }
  202. /**
  203. *
  204. * @param $table
  205. * @param $entity_type
  206. * @param $bundle_name
  207. */
  208. function tripal_entities_add_bundle_fields($tablename, $entity_type_name, $bundle_name) {
  209. // Iterate through the columns of the table and see if fields have been
  210. // created for each one. If not, then create them.
  211. $schema = chado_get_schema($tablename);
  212. $columns = $schema['fields'];
  213. foreach ($columns as $column_name => $details) {
  214. $field_name = $tablename . '__' . $column_name;
  215. $field = field_info_field($field_name);
  216. // Skip the primary key field.
  217. if ($column_name == $schema['primary key'][0]) {
  218. continue;
  219. }
  220. // Determine if the field is required.
  221. $is_required = 0;
  222. if (array_key_exists('not null', $details)) {
  223. $is_required = $details['not null'] ? 1 : 0;
  224. }
  225. // Determine what type of field this should be.
  226. // Drupal data types are: https://www.drupal.org/node/159605.
  227. // Field types are here: https://www.drupal.org/node/1879542
  228. $field_type = '';
  229. $widget_type = '';
  230. $settings = array();
  231. $label = '';
  232. switch($details['type']) {
  233. case 'char':
  234. // unsupported by postgres
  235. break;
  236. case 'varchar':
  237. $field_type = 'text';
  238. $widget_type = 'text_textfield';
  239. $settings['max_length'] = $details['length'];
  240. break;
  241. case 'text':
  242. $field_type = 'text';
  243. $widget_type = 'text_textarea';
  244. $settings['max_length'] = '';
  245. break;
  246. case 'blob':
  247. // not sure how to support a blob field.
  248. continue;
  249. break;
  250. case 'int':
  251. $field_type = 'number_integer';
  252. $widget_type = 'number';
  253. break;
  254. case 'float':
  255. $field_type = 'number_float';
  256. $widget_type = 'number';
  257. $settings['precision'] = 10;
  258. $settings['scale'] = 2;
  259. $settings['decimal_separator'] = '.';
  260. break;
  261. case 'numeric':
  262. $field_type = 'number_decimal';
  263. $widget_type = 'number';
  264. break;
  265. case 'serial':
  266. // Serial fields are most likely not needed as a field.
  267. break;
  268. case 'boolean':
  269. // TODO: what is the proper field for booleans?????
  270. break;
  271. case 'datetime':
  272. // TODO: What is the proper datetime fields ??????
  273. break;
  274. default:
  275. drupal_set_message(t("Unhandled field type: %type", array('%type' => $details['type'])), 'warning');
  276. $field_type = 'text';
  277. $widget_type = 'text_textarea';
  278. if (array_key_exists('length', $details)) {
  279. $settings['max_length'] = $details['length'];
  280. }
  281. }
  282. // If we don't have a field type then we don't need to create a field.
  283. if (!$field_type) {
  284. // If we don't have a field type but it is required and doesn't have
  285. // a default value then we are in trouble.
  286. if ($is_required and !array_key_exists('default', $details)) {
  287. throw new Exception(t('The %table.%field type, %type, is not yet supported for Entity fields, but it is required,',
  288. array('%table' => $tablename, '%field' => $column_name, '%type' => $details['type'])));
  289. }
  290. continue;
  291. }
  292. // If this field is a foreign key field then we will have a special custom
  293. // field provided by Tripal.
  294. $is_fk = FALSE;
  295. if (array_key_exists('foreign keys', $details)) {
  296. foreach ($details['foreign keys'] as $remote_table => $fk_details) {
  297. if (array_key_exists($field_name, $fk_details['columns'])) {
  298. $is_fk = TRUE;
  299. }
  300. }
  301. }
  302. // If this column is a FK relationship then use a custom Tripal
  303. // defined field type for it.
  304. if ($is_fk) {
  305. // TODO: We need a better way to get the fields for FK relationships.
  306. // It's not a good idea to enumerate them all here. We need some sort
  307. // of hook or something that will let us lookup the correct field.
  308. switch ($column_name) {
  309. case 'organism_id':
  310. $field_type = 'organism_id';
  311. $label = 'Organism';
  312. break;
  313. }
  314. continue;
  315. }
  316. // If the field doesn't exist then create it.
  317. if (!$field) {
  318. $field = array(
  319. 'field_name' => $field_name,
  320. 'type' => $field_type,
  321. 'cardinality' => 1,
  322. 'locked' => TRUE,
  323. 'storage' => array(
  324. 'type' => 'tripal_entities_storage'
  325. ),
  326. );
  327. field_create_field($field);
  328. }
  329. // Attach the field to the bundle.
  330. $field_instance = array(
  331. 'field_name' => $field_name,
  332. 'label' => $label ? $label : ucwords(preg_replace('/_/', ' ', $column_name)),
  333. 'widget' => array(
  334. 'type' => $widget_type
  335. ),
  336. 'entity_type' => $entity_type_name,
  337. 'required' => $is_required,
  338. 'settings' => $settings,
  339. 'bundle' => $bundle_name,
  340. );
  341. field_create_instance($field_instance);
  342. }
  343. }
  344. /**
  345. *
  346. * @param unknown $form
  347. * @param unknown $form_state
  348. * @return multitype:
  349. */
  350. function tripal_entities_admin_access_form($form, &$form_state) {
  351. $form = array();
  352. return $form;
  353. }
  354. /**
  355. * This function populates the Tripal entity tables using existing
  356. * data in the database.
  357. */
  358. function tripal_entities_populate_entity_tables() {
  359. // Get the cvterm table and look for all of the tables that link to it.
  360. $schema = chado_get_schema('cvterm');
  361. $referring = $schema['referring_tables'];
  362. // Perform this action in a transaction
  363. $transaction = db_transaction();
  364. print "\nNOTE: Populating of tripal entity tables is performed using a database transaction. \n" .
  365. "If the load fails or is terminated prematurely then the entire set of \n" .
  366. "insertions/updates is rolled back and will not be found in the database\n\n";
  367. try {
  368. // Iterate through the referring tables to see what records are there.
  369. foreach ($referring as $tablename) {
  370. // We only want to look at base tables.
  371. if ($tablename == 'cvterm_dbxref' || $tablename == 'cvterm_relationship' ||
  372. $tablename == 'cvtermpath' || $tablename == 'cvtermprop' || $tablename == 'chadoprop' ||
  373. $tablename == 'cvtermsynonym' || preg_match('/_relationship$/', $tablename) ||
  374. preg_match('/_cvterm$/', $tablename)) {
  375. continue;
  376. }
  377. print "Examining $tablename...\n";
  378. $ref_schema = chado_get_schema($tablename);
  379. $fkeys = $ref_schema['foreign keys'];
  380. foreach ($fkeys['cvterm']['columns'] as $local_id => $remote_id) {
  381. // Get the list of cvterm_ids from existing records in the table.
  382. $sql = "
  383. SELECT $local_id
  384. FROM { " . $tablename . "}
  385. GROUP BY $local_id
  386. ";
  387. $results = chado_query($sql);
  388. while ($cvterm_id = $results->fetchField()) {
  389. // Get the CV term details and add it to the tripal_entity_type table if
  390. // it doesn't already exist.
  391. $cvterm = chado_generate_var('cvterm', array('cvterm_id' => $cvterm_id));
  392. // First add a record to the tripal_entity_type table.
  393. $values = array(
  394. 'cv_id' => $cvterm->cv_id->cv_id,
  395. 'db_id' => $cvterm->dbxref_id->db_id->db_id,
  396. 'publish' => 0,
  397. );
  398. $entity_type_id = 0;
  399. $entity_type = chado_select_record('tripal_entity_type', array('entity_type_id'), $values);
  400. if (count($entity_type) == 0) {
  401. $entity_type = chado_insert_record('tripal_entity_type', $values);
  402. $entity_type_id = $entity_type['entity_type_id'];
  403. }
  404. else {
  405. $entity_type_id = $entity_type[0]->entity_type_id;
  406. }
  407. // Next add a record to the tripal_entity_bundle table.
  408. $values = array(
  409. 'entity_type_id' => $entity_type_id,
  410. 'cvterm_id' => $cvterm_id,
  411. 'publish' => 0
  412. );
  413. $bundle_id = 0;
  414. $bundle = chado_select_record('tripal_entity_bundle', array('bundle_id'), $values);
  415. if (count($bundle) == 0) {
  416. $bundle = chado_insert_record('tripal_entity_bundle', $values);
  417. $bundle_id = $bundle['bundle_id'];
  418. }
  419. else {
  420. $bundle_id = $bundle[0]->bundle_id;
  421. }
  422. // Add the table where the records are found.
  423. $values = array(
  424. 'bundle_id' => $bundle_id,
  425. 'data_table' => $tablename,
  426. 'type_table' => $tablename,
  427. 'field' => $local_id
  428. );
  429. if (!chado_select_record('tripal_entity_bundle_source', array('bundle_source_id'), $values, array('has_record' => TRUE))) {
  430. chado_insert_record('tripal_entity_bundle_source', $values);
  431. }
  432. // Add the table where the records are found.
  433. $values = array(
  434. 'entity_type_id' => $entity_type_id,
  435. 'data_table' => $tablename,
  436. 'type_table' => $tablename,
  437. 'field' => $local_id
  438. );
  439. if (!chado_select_record('tripal_entity_type_source', array('entity_type_id'), $values, array('has_record' => TRUE))) {
  440. chado_insert_record('tripal_entity_type_source', $values);
  441. }
  442. }
  443. }
  444. }
  445. }
  446. catch (Exception $e) {
  447. print "\n"; // make sure we start errors on new line
  448. $transaction->rollback();
  449. watchdog_exception('tripal_ws', $e);
  450. print "FAILED: Rolling back database changes...\n";
  451. }
  452. print "\nDone.\n";
  453. }