tripal_feature.chado_node.inc 39 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096
  1. <?php
  2. /**
  3. * @file
  4. * Implementation of hooks to create a feature content type
  5. */
  6. /**
  7. * Implements hook_node_info().
  8. *
  9. * Provide information to drupal about the node types that we're creating
  10. * in this module
  11. *
  12. * @ingroup tripal_feature
  13. */
  14. function tripal_feature_node_info() {
  15. $nodes = array();
  16. $nodes['chado_feature'] = array(
  17. 'name' => t('Feature'),
  18. 'base' => 'chado_feature',
  19. 'description' => t('A feature from the chado database'),
  20. 'has_title' => TRUE,
  21. 'locked' => TRUE,
  22. 'chado_node_api' => array(
  23. 'base_table' => 'feature',
  24. 'hook_prefix' => 'chado_feature',
  25. 'record_type_title' => array(
  26. 'singular' => t('Feature'),
  27. 'plural' => t('Features')
  28. ),
  29. 'sync_filters' => array(
  30. 'type_id' => TRUE,
  31. 'organism_id' => TRUE
  32. ),
  33. )
  34. );
  35. return $nodes;
  36. }
  37. /**
  38. * Implementation of hook_form().
  39. *
  40. * @ingroup tripal_feature
  41. */
  42. function chado_feature_form($node, &$form_state) {
  43. $form = array();
  44. // Default values can come in the following ways:
  45. //
  46. // 1) as elements of the $node object. This occurs when editing an existing feature
  47. // 2) in the $form_state['values'] array which occurs on a failed validation or
  48. // ajax callbacks from non submit form elements
  49. // 3) in the $form_state['input'[ array which occurs on ajax callbacks from submit
  50. // form elements and the form is being rebuilt
  51. //
  52. // set form field defaults
  53. $feature = null;
  54. $feature_id = null;
  55. $uniquename = '';
  56. $fname = '';
  57. $feature_type = '';
  58. $organism_id = '';
  59. $residues = '';
  60. $is_obsolete = '';
  61. $analyses = '';
  62. $references = '';
  63. $synonyms = '';
  64. // if we are editing an existing node then the feature is already part of the node
  65. if (property_exists($node, 'feature')) {
  66. $feature = $node->feature;
  67. $feature = chado_expand_var($feature, 'field', 'feature.residues');
  68. $feature_id = $feature->feature_id;
  69. $uniquename = $feature->uniquename;
  70. $fname = $feature->name;
  71. $feature_type = $feature->type_id->name;
  72. $organism_id = $feature->organism_id->organism_id;
  73. $residues = $feature->residues;
  74. $is_obsolete = $feature->is_obsolete;
  75. // get the synonyms from a previous post
  76. $synonyms = '';
  77. if(property_exists($node, 'synonyms')) {
  78. $synonyms = $node->synonyms;
  79. }
  80. // get synonyms from the database if we don't already have them
  81. if (!$synonyms) {
  82. $options = array('return_array' => 1);
  83. $feature = chado_expand_var($feature, 'table', 'feature_synonym', $options);
  84. $feature_synonyms = (isset($feature->feature_synonym)) ? $feature->feature_synonym : array();
  85. foreach ($feature_synonyms as $index => $synonym) {
  86. $synonyms .= $synonym->synonym_id->name . "\n";
  87. }
  88. }
  89. // keep track of the feature id
  90. $form['feature_id'] = array(
  91. '#type' => 'value',
  92. '#value' => $feature_id,
  93. );
  94. }
  95. // if we are re constructing the form from a failed validation or ajax callback
  96. // then use the $form_state['values'] values
  97. if (array_key_exists('values', $form_state) and isset($form_state['values']['uniquename'])) {
  98. $uniquename = $form_state['values']['uniquename'];
  99. $fname = $form_state['values']['fname'];
  100. $feature_type = $form_state['values']['feature_type'];
  101. $organism_id = $form_state['values']['organism_id'];
  102. $residues = $form_state['values']['residues'];
  103. $is_obsolete = $form_state['values']['is_obsolete'];
  104. $synonyms = $form_state['values']['synonyms'];
  105. }
  106. // if we are re building the form from after submission (from ajax call) then
  107. // the values are in the $form_state['input'] array
  108. if (array_key_exists('input', $form_state) and !empty($form_state['input'])) {
  109. $uniquename = $form_state['input']['uniquename'];
  110. $fname = $form_state['input']['fname'];
  111. $feature_type = $form_state['input']['feature_type'];
  112. $organism_id = $form_state['input']['organism_id'];
  113. $residues = $form_state['input']['residues'];
  114. $is_obsolete = array_key_exists('is_obsolete', $form_state['input']) ? $form_state['input']['is_obsolete'] : FALSE;
  115. $synonyms = $form_state['input']['synonyms'];
  116. }
  117. $form['fname']= array(
  118. '#type' => 'textfield',
  119. '#title' => t('Feature Name'),
  120. '#required' => TRUE,
  121. '#default_value' => $fname,
  122. '#description' => t('Enter the name used by humans to refer to this feature.'),
  123. '#maxlength' => 255
  124. );
  125. $form['uniquename']= array(
  126. '#type' => 'textfield',
  127. '#title' => t('Unique Feature Name'),
  128. '#required' => TRUE,
  129. '#default_value' => $uniquename,
  130. '#description' => t('Enter a unique name for this feature. This name must be unique for the organism and feature type.'),
  131. '#maxlength' => 255
  132. );
  133. $type_options = tripal_get_cvterm_default_select_options('feature', 'type_id', 'feature types');
  134. $type_options[0] = 'Select a Type';
  135. $type_cv = tripal_get_default_cv('feature', 'type_id');
  136. $cv_id = $type_cv->cv_id;
  137. $form['feature_type'] = array(
  138. '#title' => t('Feature Type'),
  139. '#type' => 'textfield',
  140. '#description' => t("Choose the feature type."),
  141. '#required' => TRUE,
  142. '#default_value' => $feature_type,
  143. '#autocomplete_path' => "admin/tripal/chado/tripal_cv/cvterm/auto_name/$cv_id",
  144. );
  145. // get the list of organisms
  146. $sql = "SELECT * FROM {Organism} ORDER BY genus, species";
  147. $org_rset = chado_query($sql);
  148. $organisms = array();
  149. $organisms[''] = '';
  150. while ($organism = $org_rset->fetchObject()) {
  151. $organisms[$organism->organism_id] = "$organism->genus $organism->species ($organism->common_name)";
  152. }
  153. $form['organism_id'] = array(
  154. '#title' => t('Organism'),
  155. '#type' => t('select'),
  156. '#description' => t("Choose the organism with which this feature is associated"),
  157. '#required' => TRUE,
  158. '#default_value' => $organism_id,
  159. '#options' => $organisms,
  160. );
  161. // Get synonyms
  162. $syn_text = '';
  163. if ($synonyms) {
  164. if (is_array($synonyms)) {
  165. foreach ($synonyms as $synonym) {
  166. $syn_text .= "$synonym->name\n";
  167. }
  168. }
  169. else {
  170. $syn_text = $synonyms;
  171. }
  172. }
  173. $form['synonyms']= array(
  174. '#type' => 'textarea',
  175. '#title' => t('Synonyms'),
  176. '#required' => FALSE,
  177. '#default_value' => $syn_text,
  178. '#description' => t('Enter alternate names (synonmys) for this feature to help in searching and identification. You may enter as many alternate names as needed each on different lines.'),
  179. );
  180. $form['residues']= array(
  181. '#type' => 'textarea',
  182. '#title' => t('Residues'),
  183. '#required' => FALSE,
  184. '#default_value' => $residues,
  185. '#description' => t('Enter the nucelotide sequences for this feature'),
  186. );
  187. $checked = '';
  188. if ($is_obsolete == 't') {
  189. $checked = '1';
  190. }
  191. $form['is_obsolete']= array(
  192. '#type' => 'checkbox',
  193. '#title' => t('Is Obsolete'),
  194. '#required' => FALSE,
  195. '#default_value' => $checked,
  196. '#description' => t('Check this box if this sequence should be retired'),
  197. );
  198. // PROPERTIES FORM
  199. //---------------------------------------------
  200. $prop_cv = tripal_get_default_cv('featureprop', 'type_id');
  201. $cv_id = $prop_cv ? $prop_cv->cv_id : NULL;
  202. $details = array(
  203. 'property_table' => 'featureprop', // the name of the prop table
  204. 'chado_id' => $feature_id, // the value of feature_id for this record
  205. 'cv_id' => $cv_id // the cv.cv_id of the cv governing featureprop.type_id
  206. );
  207. chado_add_node_form_properties($form, $form_state, $details);
  208. // ADDITIONAL DBXREFS FORM
  209. //---------------------------------------------
  210. $details = array(
  211. 'linking_table' => 'feature_dbxref', // the name of the _dbxref table
  212. 'base_foreign_key' => 'feature_id', // the name of the key in your base chado table
  213. 'base_key_value' => $feature_id // the value of feature_id for this record
  214. );
  215. chado_add_node_form_dbxrefs($form, $form_state, $details);
  216. // TODO: For some reason adding a relationship to the form breaks AJAX
  217. // for features (works for other node type)... need to debug
  218. // RELATIONSHIPS FORM
  219. //---------------------------------------------
  220. $relationship_cv = tripal_get_default_cv('feature_relationship', 'type_id');
  221. $cv_id = $relationship_cv ? $relationship_cv->cv_id : NULL;
  222. $details = array(
  223. 'relationship_table' => 'feature_relationship',
  224. 'base_table' => 'feature',
  225. 'base_foreign_key' => 'feature_id',
  226. 'base_key_value' => $feature_id,
  227. 'nodetype' => 'feature',
  228. 'cv_id' => $cv_id
  229. );
  230. chado_add_node_form_relationships($form, $form_state, $details);
  231. return $form;
  232. }
  233. /**
  234. * Implementation of hook_validate().
  235. *
  236. * This validation is being used for three activities:
  237. * CASE A: Update a node that exists in both drupal and chado
  238. * CASE B: Synchronizing a node from chado to drupal
  239. * CASE C: Inserting a new node that exists in niether drupal nor chado
  240. *
  241. * @ingroup tripal_feature
  242. */
  243. function chado_feature_validate($node, $form, &$form_state) {
  244. // if this is a delete then don't validate
  245. if($node->op == 'Delete') {
  246. return;
  247. }
  248. // we are syncing if we do not have a node ID but we do have a feature_id. We don't
  249. // need to validate during syncing so just skip it.
  250. if (is_null($node->nid) and property_exists($node, 'feature_id') and $node->feature_id != 0) {
  251. return;
  252. }
  253. // remove surrounding white-space on submitted values
  254. $node->uniquename = trim($node->uniquename);
  255. $node->fname = trim($node->fname);
  256. $node->feature_type = trim($node->feature_type);
  257. $node->residues = trim($node->residues);
  258. // Validating for an update
  259. if (property_exists($node, 'nid')) {
  260. // make sure the feature type is a real sequence ontology term
  261. $type = tripal_get_cvterm(array(
  262. 'name' => $node->feature_type,
  263. 'cv_id' => array('name' =>'sequence')
  264. ));
  265. if (!$type) {
  266. form_set_error('feature_type', t("The feature type is not a valid name from the Sequence Ontology."));
  267. }
  268. // if this is an update, we want to make sure that a different feature for
  269. // the organism doesn't already have this uniquename. We don't want to give
  270. // two sequences the same uniquename
  271. if (property_exists($node, 'feature_id') and $node->feature_id != 0) {
  272. $sql = "
  273. SELECT *
  274. FROM {feature} F
  275. INNER JOIN {cvterm} CVT ON F.type_id = CVT.cvterm_id
  276. WHERE
  277. F.uniquename = :uname AND
  278. F.organism_id = :organism_id AND
  279. CVT.name = :cvtname AND
  280. NOT f.feature_id = :feature_id
  281. ";
  282. $args = array(':uname' => $node->uniquename, ':organism_id' => $node->organism_id,
  283. ':cvtname' => $node->feature_type, ':feature_id' => $node->feature_id);
  284. $result = chado_query($sql, $args)->fetchObject();
  285. if ($result) {
  286. form_set_error('uniquename', t("Feature update cannot proceed. The feature name '$node->uniquename' is not unique for this organism. Please provide a unique name for this feature."));
  287. }
  288. }
  289. }
  290. // Validating for an insert
  291. else {
  292. // make sure the feature type is a real sequence ontology term
  293. $type = tripal_get_cvterm(array(
  294. 'name' => $node->feature_type,
  295. 'cv_id' => array('name' => 'sequence')
  296. ));
  297. if (!$type) {
  298. form_set_error('feature_type', t("The feature type is not a valid name from the Sequence Ontology."));
  299. }
  300. // if this is an insert then we just need to make sure this name doesn't
  301. // already exist for this organism if it does then we need to throw an error
  302. $sql = "
  303. SELECT *
  304. FROM {feature} F
  305. INNER JOIN {cvterm} CVT ON F.type_id = CVT.cvterm_id
  306. WHERE
  307. F.uniquename = :name AND
  308. F.organism_id = :organism_id AND
  309. CVT.name = :cvtname
  310. ";
  311. $args = array(':name' => $node->uniquename, ':organism_id' => $node->organism_id, ':cvtname' => $node->feature_type);
  312. $result = chado_query($sql, $args)->fetchObject();
  313. if ($result) {
  314. form_set_error('uniquename', t("Feature insert cannot proceed. The feature name '$node->uniquename' already exists for this organism. Please provide a unique name for this feature."));
  315. }
  316. }
  317. }
  318. /**
  319. * Implement hook_node_access().
  320. *
  321. * This hook allows node modules to limit access to the node types they define.
  322. *
  323. * @param $node
  324. * The node on which the operation is to be performed, or, if it does not yet exist, the
  325. * type of node to be created
  326. *
  327. * @param $op
  328. * The operation to be performed
  329. *
  330. * @param $account
  331. * A user object representing the user for whom the operation is to be performed
  332. *
  333. * @return
  334. * If the permission for the specified operation is not set then return FALSE. If the
  335. * permission is set then return NULL as this allows other modules to disable
  336. * access. The only exception is when the $op == 'create'. We will always
  337. * return TRUE if the permission is set.
  338. *
  339. * @ingroup tripal_feature
  340. */
  341. function chado_feature_node_access($node, $op, $account) {
  342. $node_type = $node;
  343. if (is_object($node)) {
  344. $node_type = $node->type;
  345. }
  346. if($node_type == 'chado_feature') {
  347. if ($op == 'create') {
  348. if (!user_access('create chado_feature content', $account)) {
  349. return NODE_ACCESS_DENY;
  350. }
  351. return NODE_ACCESS_ALLOW;
  352. }
  353. if ($op == 'update') {
  354. if (!user_access('edit chado_feature content', $account)) {
  355. return NODE_ACCESS_DENY;
  356. }
  357. }
  358. if ($op == 'delete') {
  359. if (!user_access('delete chado_feature content', $account)) {
  360. return NODE_ACCESS_DENY;
  361. }
  362. }
  363. if ($op == 'view') {
  364. if (!user_access('access chado_feature content', $account)) {
  365. return NODE_ACCESS_DENY;
  366. }
  367. }
  368. }
  369. return NODE_ACCESS_IGNORE;
  370. }
  371. /**
  372. * Implements hook_insert().
  373. *
  374. * When a new chado_feature node is created we also need to add information
  375. * to our chado_feature table. This function is called on insert of a new node
  376. * of type 'chado_feature' and inserts the necessary information.
  377. *
  378. * @ingroup tripal_feature
  379. */
  380. function chado_feature_insert($node) {
  381. $node->uniquename = trim($node->uniquename);
  382. $node->fname = trim($node->fname);
  383. $node->feature_type = trim($node->feature_type);
  384. $node->residues = trim($node->residues);
  385. // remove spaces, newlines from residues
  386. $residues = preg_replace("/[\n\r\s]/", "", $node->residues);
  387. $obsolete = 'FALSE';
  388. if ($node->is_obsolete) {
  389. $obsolete = 'TRUE';
  390. }
  391. // get the feature type id
  392. $values = array(
  393. 'cv_id' => array(
  394. 'name' => 'sequence'
  395. ),
  396. 'name' => $node->feature_type
  397. );
  398. $type = chado_select_record('cvterm', array('cvterm_id'), $values);
  399. $feature_id = '';
  400. // if there is a feature_id in the $node object then this must be a sync so
  401. // we can skip adding the feature as it is already there, although
  402. // we do need to proceed with the rest of the insert
  403. if (!property_exists($node, 'feature_id')) {
  404. $values = array(
  405. 'organism_id' => $node->organism_id,
  406. 'name' => $node->fname,
  407. 'uniquename' => $node->uniquename,
  408. 'residues' => $residues,
  409. 'seqlen' => drupal_strlen($residues),
  410. 'is_obsolete' => $obsolete,
  411. 'type_id' => $type[0]->cvterm_id,
  412. 'md5checksum' => md5($residues)
  413. );
  414. $feature = chado_insert_record('feature', $values);
  415. if (!$feature) {
  416. drupal_set_message(t('Unable to add feature.'), 'warning');
  417. tripal_report_error('tripal_feature', TRIPAL_WARNING, 'Insert feature: Unable to create feature where values: %values',
  418. array('%values' => print_r($values, TRUE)));
  419. return;
  420. }
  421. $feature_id = $feature['feature_id'];
  422. // add the genbank accession and synonyms
  423. chado_feature_add_synonyms($node->synonyms, $feature_id);
  424. // * Properties Form *
  425. $details = array(
  426. 'property_table' => 'featureprop', // the name of the prop table
  427. 'base_table' => 'feature', // the name of your chado base table
  428. 'foreignkey_name' => 'feature_id', // the name of the key in your base table
  429. 'foreignkey_value' => $feature_id // the value of the feature_id key
  430. );
  431. chado_update_node_form_properties($node, $details);
  432. // * Additional DBxrefs Form *
  433. $details = array(
  434. 'linking_table' => 'feature_dbxref', // the name of your _dbxref table
  435. 'foreignkey_name' => 'feature_id', // the name of the key in your base table
  436. 'foreignkey_value' => $feature_id // the value of the feature_id key
  437. );
  438. chado_update_node_form_dbxrefs($node, $details);
  439. }
  440. else {
  441. $feature_id = $node->feature_id;
  442. }
  443. // Make sure the entry for this feature doesn't already exist in the
  444. // chado_feature table if it doesn't exist then we want to add it.
  445. $check_org_id = chado_get_id_from_nid('feature', $node->nid);
  446. if (!$check_org_id) {
  447. $record = new stdClass();
  448. $record->nid = $node->nid;
  449. $record->vid = $node->vid;
  450. $record->feature_id = $feature_id;
  451. drupal_write_record('chado_feature', $record);
  452. }
  453. }
  454. /**
  455. * Implements hook_update().
  456. *
  457. * @ingroup tripal_feature
  458. */
  459. function chado_feature_update($node) {
  460. $node->uniquename = trim($node->uniquename);
  461. $node->fname = trim($node->fname);
  462. $node->feature_type = trim($node->feature_type);
  463. $node->residues = trim($node->residues);
  464. $residues = preg_replace("/[\n\r\s]/", "", $node->residues);
  465. $obsolete = 'FALSE';
  466. if ($node->is_obsolete) {
  467. $obsolete = 'TRUE';
  468. }
  469. // get the feature type id
  470. $values = array(
  471. 'cv_id' => array(
  472. 'name' => 'sequence'
  473. ),
  474. 'name' => $node->feature_type
  475. );
  476. $type = chado_select_record('cvterm', array('cvterm_id'), $values);
  477. $feature_id = chado_get_id_from_nid('feature', $node->nid) ;
  478. if (sizeof($type) > 0) {
  479. $match = array(
  480. 'feature_id' => $feature_id,
  481. );
  482. $values = array(
  483. 'organism_id' => $node->organism_id,
  484. 'name' => $node->fname,
  485. 'uniquename' => $node->uniquename,
  486. 'residues' => $residues,
  487. 'seqlen' => drupal_strlen($residues),
  488. 'is_obsolete' => $obsolete,
  489. 'type_id' => $type[0]->cvterm_id,
  490. 'md5checksum' => md5($residues)
  491. );
  492. $options = array('return_record' => TRUE);
  493. $status = chado_update_record('feature', $match, $values, $options);
  494. // add the genbank synonyms
  495. chado_feature_add_synonyms($node->synonyms, $feature_id);
  496. // * Properties Form *
  497. $details = array(
  498. 'property_table' => 'featureprop', // the name of the prop table
  499. 'base_table' => 'feature', // the name of your chado base table
  500. 'foreignkey_name' => 'feature_id', // the name of the key in your base table
  501. 'foreignkey_value' => $feature_id // the value of the feature_id key
  502. );
  503. chado_update_node_form_properties($node, $details);
  504. // * Additional DBxrefs Form *
  505. $details = array(
  506. 'linking_table' => 'feature_dbxref', // the name of your _dbxref table
  507. 'foreignkey_name' => 'feature_id', // the name of the key in your base table
  508. 'foreignkey_value' => $feature_id // the value of the feature_id key
  509. );
  510. chado_update_node_form_dbxrefs($node, $details);
  511. }
  512. else {
  513. drupal_set_message(t('Unable to update feature.'), 'warning');
  514. tripal_report_error('tripal_feature', TRIPAL_WARNING,
  515. 'Update feature: Unable to update feature where values: %values',
  516. array('%values' => print_r($values, TRUE))
  517. );
  518. }
  519. }
  520. /**
  521. * Implements hook_delete().
  522. *
  523. * @ingroup tripal_feature
  524. */
  525. function chado_feature_delete($node) {
  526. $feature_id = chado_get_id_from_nid('feature', $node->nid);
  527. // if we don't have a library id for this node then this isn't a node of
  528. // type chado_library or the entry in the chado_library table was lost.
  529. if (!$feature_id) {
  530. return;
  531. }
  532. // remove the drupal content
  533. $sql_del = "DELETE FROM {chado_feature} WHERE nid = :nid AND vid = :vid";
  534. db_query($sql_del, array(':nid' => $node->nid, ':vid' => $node->vid));
  535. $sql_del = "DELETE FROM {node} WHERE nid = :nid AND vid = :vid";
  536. db_query($sql_del, array(':nid' => $node->nid, ':vid' => $node->vid));
  537. $sql_del = "DELETE FROM {node_revision} WHERE nid = :nid AND vid = :vid";
  538. db_query($sql_del, array(':nid' => $node->nid, ':vid' => $node->vid));
  539. // Remove data from feature tables of chado database. This will
  540. // cause a cascade delete and remove all data in referencing tables
  541. // for this feature. However, we need t specifically delete from the
  542. // featureloc table because the box() PLSQL function calls another
  543. // function that does not reference the 'chado' schema and causes an error
  544. // the chado_query function can handle this problem so we specificall delete
  545. // from that table to prevent the error. The same problem exists for the
  546. // frange.featuregroup table
  547. $previous_db = chado_set_active('chado') ;
  548. db_query("DELETE FROM frange.featuregroup WHERE subject_id = :feature_id", array(':feature_id' => $feature_id));
  549. db_query("DELETE FROM frange.featuregroup WHERE object_id = :feature_id", array(':feature_id' => $feature_id));
  550. db_query("DELETE FROM frange.featuregroup WHERE group_id = :feature_id", array(':feature_id' => $feature_id));
  551. db_query("DELETE FROM frange.featuregroup WHERE srcfeature_id = :feature_id", array(':feature_id' => $feature_id));
  552. chado_set_active($previous_db);
  553. chado_query("DELETE FROM {featureloc} WHERE feature_id = :feature_id", array(':feature_id' => $feature_id));
  554. chado_query("DELETE FROM {featureloc} WHERE srcfeature_id = :feature_id", array(':feature_id' => $feature_id));
  555. chado_query("DELETE FROM {feature} WHERE feature_id = :feature_id", array(':feature_id' => $feature_id));
  556. drupal_set_message(t("The feature and all associated data were removed"));
  557. }
  558. /**
  559. * Add synonyms to a feature
  560. *
  561. * @param $synonyms
  562. * A string containing synonyms separated by a return character
  563. * @param $feature_id
  564. * The feature to attach the synonyms to
  565. *
  566. * @ingroup tripal_feature
  567. */
  568. function chado_feature_add_synonyms($synonyms, $feature_id) {
  569. // separate synomys by carriage returns
  570. $synonyms = preg_replace("/[\n\r]+/", " ", $synonyms);
  571. // split the synonyms into an array based on a space as the delimieter
  572. $syn_array = array();
  573. $syn_array = explode(" ", $synonyms);
  574. // remove any old synonyms
  575. $feature_syn_dsql = "DELETE FROM {feature_synonym} WHERE feature_id = :feature_id";
  576. if (!chado_query($feature_syn_dsql, array(':feature_id' => $feature_id))) {
  577. tripal_report_error('tripal_feature', TRIPAL_ERROR, "Could not remove synonyms from feature. ", array());
  578. return;
  579. }
  580. // return if we don't have any synonmys to add
  581. if (!$synonyms) {
  582. return;
  583. }
  584. // iterate through each synonym and add it to the database
  585. foreach ($syn_array as $syn) {
  586. // skip this item if it's empty
  587. if (!$syn) {
  588. break;
  589. }
  590. // check to see if we have this accession number already in the database
  591. // if so then don't add it again. it messes up drupal if the insert fails.
  592. // It is possible for the accession number to be present and not the feature
  593. $synonym_sql = "SELECT synonym_id FROM {synonym} WHERE name = :name";
  594. $synonym = chado_query($synonym_sql, array(':name' => $syn))->fetchObject();
  595. if (!$synonym) {
  596. $synonym_isql = "
  597. INSERT INTO {synonym} (name, synonym_sgml, type_id)
  598. VALUES (:name, :synonym_sgml,
  599. (SELECT cvterm_id
  600. FROM {cvterm} CVT
  601. INNER JOIN {cv} ON CVT.cv_id = CV.cv_id
  602. WHERE CV.name = 'feature_property' and CVT.name = 'synonym')
  603. )
  604. ";
  605. if (!chado_query($synonym_isql, array(':name' => $syn, ':synonym_sgml' => $syn))) {
  606. tripal_report_error('tripal_feature', "Could not add synonym. ", array(), TRIPAL_WARNING);
  607. return;
  608. }
  609. // now get the synonym we just added
  610. $synonym_sql = "SELECT synonym_id FROM {synonym} WHERE name = :name";
  611. $synonym = chado_query($synonym_sql, array(':name' => $syn))->fetchObject();
  612. }
  613. // now add in our new sysnonym
  614. $feature_syn_isql = "
  615. INSERT INTO {feature_synonym} (synonym_id,feature_id,pub_id)
  616. VALUES (:synonym_id, :feature_id, :pub_id)";
  617. $args = array(':synonym_id' => $synonym->synonym_id, ':feature_id' => $feature_id, ':pub_id'=> 1);
  618. if (!chado_query($feature_syn_isql, $args)) {
  619. tripal_report_error('tripal_feature', "Could not associate synonym with feature. ", array(), TRIPAL_WARNING);
  620. return;
  621. }
  622. }
  623. }
  624. /**
  625. * Implements hook_load().
  626. *
  627. * When a node is requested by the user this function is called to allow us
  628. * to add auxiliary data to the node object.
  629. *
  630. * @ingroup tripal_feature
  631. */
  632. function chado_feature_load($nodes) {
  633. foreach ($nodes as $nid => $node) {
  634. // find the feature and add in the details
  635. $feature_id = chado_get_id_from_nid('feature', $nid);
  636. // if the nid does not have a matching record then skip this node.
  637. // this can happen with orphaned nodes.
  638. if (!$feature_id) {
  639. continue;
  640. }
  641. // build the feature variable
  642. $values = array('feature_id' => $feature_id);
  643. $feature = chado_generate_var('feature', $values);
  644. $nodes[$nid]->feature = $feature;
  645. // Now get the title
  646. $node->title = chado_get_node_title($node);
  647. }
  648. }
  649. /**
  650. * Implements hook_node_presave().
  651. * Acts on all content types.
  652. *
  653. * @ingroup tripal_feature
  654. */
  655. function tripal_feature_node_presave($node) {
  656. // set the title to ensure it is always unique
  657. switch ($node->type) {
  658. case 'chado_feature':
  659. // for a form submission the fields are part of the node object
  660. // but for a sync the fields are in an object of the node
  661. $name = '';
  662. $uname = '';
  663. $type = '';
  664. $organism_id = null;
  665. if(property_exists($node, 'uniquename')) {
  666. $organism_id = $node->organism_id;
  667. $name = $node->name;
  668. $uname = $node->uniquename;
  669. $type = $node->feature_type;
  670. }
  671. else if (property_exists($node, 'feature')) {
  672. $organism_id = $node->feature->organism_id;
  673. $name = $node->feature->name;
  674. $uname = $node->feature->uniquename;
  675. $type_id = $node->feature->type_id;
  676. $values = array('cvterm_id' => $type_id);
  677. $ftype = chado_select_record('cvterm', array('name'), $values);
  678. $type = $ftype[0]->name;
  679. }
  680. $values = array('organism_id' => $organism_id);
  681. $organism = chado_select_record('organism', array('genus', 'species'), $values);
  682. $node->title = "$name, $uname ($type) " . $organism[0]->genus . ' ' . $organism[0]->species;
  683. if ($name == $uname) {
  684. $node->title = "$name ($type) " . $organism[0]->genus . ' ' . $organism[0]->species;
  685. }
  686. break;
  687. }
  688. }
  689. /**
  690. * Implements hook_node_insert().
  691. * Acts on all content types.
  692. *
  693. * @ingroup tripal_feature
  694. */
  695. function tripal_feature_node_insert($node) {
  696. // set the URL path after inserting. We do it here because we do not
  697. // know the feature_id in the presave
  698. switch ($node->type) {
  699. case 'chado_feature':
  700. $feature_id = chado_get_id_from_nid('feature', $node->nid);
  701. // build the feature variable
  702. $values = array('feature_id' => $feature_id);
  703. $feature = chado_generate_var('feature', $values);
  704. $node->feature = $feature;
  705. // on an insert we need to add the feature_id to the node object
  706. // so that the tripal_feature_get_feature_url function can set the URL properly
  707. $node->feature_id = chado_get_id_from_nid('feature', $node->nid);
  708. // remove any previous alias
  709. db_query("DELETE FROM {url_alias} WHERE source = :source", array(':source' => "node/$node->nid"));
  710. // set the URL for this feature page
  711. $url_alias = tripal_feature_get_feature_url($node);
  712. $path_alias = array("source" => "node/$node->nid", "alias" => $url_alias);
  713. path_save($path_alias);
  714. // Now get the title
  715. $node->title = chado_get_node_title($node);
  716. break;
  717. }
  718. }
  719. /**
  720. * Implements hook_node_update().
  721. * Acts on all content types.
  722. *
  723. * @ingroup tripal_feature
  724. */
  725. function tripal_feature_node_update($node) {
  726. // add items to other nodes, build index and search results
  727. switch ($node->type) {
  728. case 'chado_feature':
  729. $feature_id = chado_get_id_from_nid('feature', $node->nid);
  730. // build the feature variable
  731. $values = array('feature_id' => $feature_id);
  732. $feature = chado_generate_var('feature', $values);
  733. $node->feature = $feature;
  734. // remove any previous alias
  735. db_query("DELETE FROM {url_alias} WHERE source = :source", array(':source' => "node/$node->nid"));
  736. // set the URL for this feature page
  737. $url_alias = tripal_feature_get_feature_url($node);
  738. $path_alias = array("source" => "node/$node->nid", "alias" => $url_alias);
  739. path_save($path_alias);
  740. // Now get the title
  741. $node->title = chado_get_node_title($node);
  742. break;
  743. }
  744. }
  745. /**
  746. * Return the url alias for a feature
  747. *
  748. * @param $node
  749. * A node object containing at least the feature_id and nid
  750. * @param $url_alias
  751. * Optional. This should be the URL alias syntax string that contains
  752. * placeholders such as [id], [genus], [species], [name], [uniquename],
  753. * and [type]. These placeholders will be substituted for actual values.
  754. * If this parameter is not provided then the value of the
  755. * chado_feature_url_string Drupal variable will be used.
  756. *
  757. * @ingroup tripal_feature
  758. */
  759. function tripal_feature_get_feature_url($node, $url_alias = NULL) {
  760. // get the starting URL alias
  761. if(!$url_alias) {
  762. $url_alias = variable_get('chado_feature_url_string', '/feature/[genus]/[species]/[type]/[uniquename]');
  763. if (!$url_alias) {
  764. $url_alias = '/feature/[genus]/[species]/[type]/[uniquename]';
  765. }
  766. $url_alias = preg_replace('/^\//', '', $url_alias); // remove any preceeding forward slash
  767. }
  768. // get the feature
  769. $values = array('feature_id' => $node->feature_id);
  770. $feature = chado_select_record('feature', array('*'), $values);
  771. if (!$feature) {
  772. tripal_report_error('trp-seturl', TRIPAL_ERROR, "Cannot find feature when setting URL alias for feature: %id", array('%id' => $node->feature_id));
  773. return FALSE;
  774. }
  775. $feature = (object) $feature[0];
  776. // get the organism
  777. $values = array('organism_id' => $feature->organism_id);
  778. $organism = chado_select_record('organism', array('*'), $values);
  779. if (!$organism) {
  780. tripal_report_error('trp-seturl', TRIPAL_ERROR, "Cannot find organism when setting URL alias for feature: %id", array('%id' => $node->feature_id));
  781. return FALSE;
  782. }
  783. $genus = preg_replace('/\s/', '_', strtolower($organism[0]->genus));
  784. $species = preg_replace('/\s/', '_', strtolower($organism[0]->species));
  785. // get the type
  786. $values = array('cvterm_id' => $feature->type_id);
  787. $cvterm = chado_select_record('cvterm', array('name'), $values);
  788. if (!$cvterm) {
  789. tripal_report_error('trp-seturl', TRIPAL_ERROR, "Cannot find type when setting URL alias for feature: %id", array('%id' => $node->feature_id));
  790. return FALSE;
  791. }
  792. $type = preg_replace('/\s/', '_', $cvterm[0]->name);
  793. // now substitute in the values
  794. $url_alias = preg_replace('/\[id\]/', $feature->feature_id, $url_alias);
  795. $url_alias = preg_replace('/\[genus\]/', $genus, $url_alias);
  796. $url_alias = preg_replace('/\[species\]/', $species, $url_alias);
  797. $url_alias = preg_replace('/\[type\]/', $type, $url_alias);
  798. $url_alias = preg_replace('/\[name\]/', $feature->name, $url_alias);
  799. $url_alias = preg_replace('/\[uniquename\]/', $feature->uniquename, $url_alias);
  800. // the dst field of the url_alias table is only 128 characters long.
  801. // if this is the case then simply return the node URL, we can't set this one
  802. if (strlen($url_alias) > 128) {
  803. tripal_report_error('trp-seturl', TRIPAL_ERROR, "Cannot set alias longer than 128 characters: %alias.", array('%alias' => $url_alias));
  804. return "node/" . $node->nid;
  805. }
  806. return $url_alias;
  807. }
  808. /**
  809. * Resets all of the URL alias for all features. This function is meant to
  810. * be run using Tripal's job managmenet interface
  811. *
  812. * @param $na
  813. * Tripal expects all jobs to have at least one argument. For this function
  814. * we don't need any, so we have this dummy argument as a filler
  815. * @param $job_id
  816. *
  817. * @ingroup tripal_feature
  818. */
  819. function tripal_feature_set_urls($na = NULL, $job = NULL) {
  820. $transaction = db_transaction();
  821. print "\nNOTE: Setting of URLs is performed using a database transaction. \n" .
  822. "If the load fails or is terminated prematurely then the entire set of \n" .
  823. "new URLs will be rolled back and no changes will be made\n\n";
  824. try {
  825. // get the number of records we need to set URLs for
  826. $csql = "SELECT count(*) FROM {chado_feature}";
  827. $num_nodes = db_query($csql)->fetchField();
  828. // calculate the interval at which we will print an update on the screen
  829. $num_set = 0;
  830. $num_per_interval = 100;
  831. // prepare the statements which will quickly add url alias. Because these
  832. // are not Chado tables we must manually prepare them
  833. $dsql = "DELETE FROM {url_alias} WHERE source = :source";
  834. $isql = "INSERT INTO url_alias (source, alias, language) VALUES (:source, :alias, :language)";
  835. // get the URL alias syntax string
  836. $url_alias = variable_get('chado_feature_url_string', '/feature/[genus]/[species]/[type]/[uniquename]');
  837. $url_alias = preg_replace('/^\//', '', $url_alias); // remove any preceeding forward slash
  838. // get the list of features that have been synced
  839. $sql = "SELECT * FROM {chado_feature}";
  840. $nodes = db_query($sql);
  841. foreach ($nodes as $node) {
  842. // get the URL alias
  843. $src = "node/$node->nid";
  844. $dst = tripal_feature_get_feature_url($node, $url_alias);
  845. // if the src and dst is the same (the URL alias couldn't be set)
  846. // then skip to the next one. There's nothing we can do about this one.
  847. if($src == $dst) {
  848. continue;
  849. }
  850. // remove any previous alias and then add the new one
  851. db_query($dsql, array(':source' => $src));
  852. db_query($isql, array(':source' => $src, ':alias' => $dst, ':language' => LANGUAGE_NONE));
  853. // update the job status every 1% features
  854. if ($job and $num_set % $num_per_interval == 0) {
  855. $percent = ($num_set / $num_nodes) * 100;
  856. tripal_set_job_progress($job, intval($percent));
  857. $percent = sprintf("%.2f", $percent);
  858. print "Setting URLs (" . $percent . "%). Memory: " . number_format(memory_get_usage()) . " bytes.\r";
  859. }
  860. $num_set++;
  861. }
  862. $percent = ($num_set / $num_nodes) * 100;
  863. tripal_set_job_progress($job, intval($percent));
  864. $percent = sprintf("%.2f", $percent);
  865. print "Setting URLs (" . $percent . "%). Memory: " . number_format(memory_get_usage()) . " bytes.\r";
  866. print "\nDone. Set " . number_format($num_set) . " URLs\n";
  867. }
  868. catch (Exception $e) {
  869. $transaction->rollback();
  870. print "\n"; // make sure we start errors on new line
  871. watchdog_exception('tripal_feature', $e);
  872. watchdog('trp-seturl', "Failed Removing URL Alias: %src", array('%src' => $src), WATCHDOG_ERROR);
  873. }
  874. }
  875. /**
  876. * Implements hook_node_view().
  877. * Acts on all content types.
  878. *
  879. * @ingroup tripal_feature
  880. */
  881. function tripal_feature_node_view($node, $view_mode, $langcode) {
  882. switch ($node->type) {
  883. case 'chado_feature':
  884. // Show feature browser and counts
  885. if ($view_mode == 'full') {
  886. $node->content['tripal_feature_alignments'] = array(
  887. '#markup' => theme('tripal_feature_alignments', array('node' => $node)),
  888. '#tripal_toc_id' => 'alignments',
  889. '#tripal_toc_title' => 'Alignments',
  890. );
  891. $node->content['tripal_feature_analyses'] = array(
  892. '#markup' => theme('tripal_feature_analyses', array('node' => $node)),
  893. '#tripal_toc_id' => 'analyses',
  894. '#tripal_toc_title' => 'Analyses',
  895. );
  896. $node->content['tripal_feature_base'] = array(
  897. '#markup' => theme('tripal_feature_base', array('node' => $node)),
  898. '#tripal_toc_id' => 'base',
  899. '#tripal_toc_title' => 'Overview',
  900. '#weight' => -100,
  901. );
  902. $node->content['tripal_feature_properties'] = array(
  903. '#markup' => theme('tripal_feature_properties', array('node' => $node)),
  904. '#tripal_toc_id' => 'properties',
  905. '#tripal_toc_title' => 'Properties',
  906. );
  907. $node->content['tripal_feature_publications'] = array(
  908. '#markup' => theme('tripal_feature_publications', array('node' => $node)),
  909. '#tripal_toc_id' => 'publications',
  910. '#tripal_toc_title' => 'Publications',
  911. );
  912. $node->content['tripal_feature_references'] = array(
  913. '#markup' => theme('tripal_feature_references', array('node' => $node)),
  914. '#tripal_toc_id' => 'references',
  915. '#tripal_toc_title' => 'Cross References',
  916. );
  917. $node->content['tripal_feature_relationships'] = array(
  918. '#markup' => theme('tripal_feature_relationships', array('node' => $node)),
  919. '#tripal_toc_id' => 'relationships',
  920. '#tripal_toc_title' => 'Relationships',
  921. );
  922. $node->content['tripal_feature_seqence'] = array(
  923. '#markup' => theme('tripal_feature_sequence', array('node' => $node)),
  924. '#tripal_toc_id' => 'sequences',
  925. '#tripal_toc_title' => 'Sequences',
  926. );
  927. $node->content['tripal_feature_synonyms'] = array(
  928. '#markup' => theme('tripal_feature_synonyms', array('node' => $node)),
  929. '#tripal_toc_id' => 'synonyms',
  930. '#tripal_toc_title' => 'Synonyms',
  931. );
  932. $node->content['tripal_feature_terms'] = array(
  933. '#markup' => theme('tripal_feature_terms', array('node' => $node)),
  934. '#tripal_toc_id' => 'terms',
  935. '#tripal_toc_title' => 'Annotated Terms',
  936. );
  937. }
  938. if ($view_mode == 'teaser') {
  939. $node->content['tripal_feature_teaser'] = array(
  940. '#markup' => theme('tripal_feature_teaser', array('node' => $node)),
  941. );
  942. }
  943. break;
  944. case 'chado_organism':
  945. // Show feature browser and counts
  946. if ($view_mode == 'full') {
  947. $node->content['tripal_organism_feature_counts'] = array(
  948. '#markup' => theme('tripal_organism_feature_counts', array('node' => $node)),
  949. '#tripal_toc_id' => 'feature_counts',
  950. '#tripal_toc_title' => 'Feature Summary',
  951. );
  952. $node->content['tripal_organism_feature_browser'] = array(
  953. '#markup' => theme('tripal_organism_feature_browser', array('node' => $node)),
  954. '#tripal_toc_id' => 'feature_browser',
  955. '#tripal_toc_title' => 'Feature Browser',
  956. );
  957. }
  958. break;
  959. // TODO: handle these node types. Should we also have a feature browser?
  960. case 'chado_library':
  961. break;
  962. case 'chado_stock':
  963. break;
  964. case 'chado_analysis':
  965. break;
  966. }
  967. }
  968. /**
  969. * Implements [content_type]_chado_node_default_title_format().
  970. *
  971. * Defines a default title format for the Chado Node API to set the titles on
  972. * Chado Feature nodes based on chado fields.
  973. */
  974. function chado_feature_chado_node_default_title_format() {
  975. return '[feature.name], [feature.uniquename] ([feature.type_id>cvterm.name]) [feature.organism_id>organism.genus] [feature.organism_id>organism.species]';
  976. }