tripal_stock.chado_node.inc 38 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114
  1. <?php
  2. /**
  3. * @file Stock Node Functionality
  4. */
  5. /**
  6. * Implements hook_node_info().
  7. * Registers a stock node type
  8. *
  9. * @return
  10. * An array describing various details of the node
  11. *
  12. * @ingroup tripal_stock
  13. */
  14. function tripal_stock_node_info() {
  15. return array(
  16. 'chado_stock' => array(
  17. 'name' => t('Stock'),
  18. 'base' => 'chado_stock',
  19. 'description' => t('A Chado Stock is a collection of material that can be sampled and have experiments performed on it.'),
  20. 'has_title' => TRUE,
  21. 'locked' => TRUE,
  22. 'chado_node_api' => array(
  23. 'base_table' => 'stock',
  24. 'hook_prefix' => 'chado_stock',
  25. 'record_type_title' => array(
  26. 'singular' => t('Stock'),
  27. 'plural' => t('Stocks')
  28. ),
  29. 'sync_filters' => array(
  30. 'type_id' => TRUE,
  31. 'organism_id' => TRUE
  32. ),
  33. )
  34. ),
  35. );
  36. }
  37. /**
  38. * Implements hook_load().
  39. * Prepares the chado_stock node
  40. *
  41. * @param $node
  42. * The basic node containing all variables common to all nodes
  43. *
  44. * @return
  45. * A stock node containing all the variables from the basic node and all stock specific variables
  46. *
  47. * D7 @todo: Make optimizations to take advantage of $nodes
  48. *
  49. * @ingroup tripal_stock
  50. */
  51. function chado_stock_load($nodes) {
  52. $new_nodes = array();
  53. foreach ($nodes as $nid => $node) {
  54. // get the stock details from chado
  55. if (isset($node->stock_id)) {
  56. $stock_id = $node->stock_id;
  57. }
  58. else {
  59. $stock_id = chado_get_id_from_nid('stock', $nid);
  60. }
  61. // if the nid does not have a matching record then skip this node.
  62. // this can happen with orphaned nodes.
  63. if (!$stock_id) {
  64. continue;
  65. }
  66. // build the variable with all the stock details
  67. $values = array('stock_id' => $stock_id);
  68. $stock = chado_generate_var('stock', $values);
  69. // add in the uniquename and the description as these are both text fields
  70. $stock = chado_expand_var($stock, 'field', 'stock.uniquename');
  71. $stock = chado_expand_var($stock, 'field', 'stock.description');
  72. // add this to the node
  73. $node->stock = $stock;
  74. $new_nodes[$nid] = $node;
  75. // If your module is using the Chado Node: Title & Path API to allow custom titles
  76. // for your node type. Every time you want the title of the node, you need to use the
  77. // following API function:
  78. $node->title = chado_get_node_title($node);
  79. }
  80. return $new_nodes;
  81. }
  82. /**
  83. * Implements hook_form().
  84. * Creates the main Add/Edit/Delete Form for chado stocks
  85. *
  86. * Parts to be added by this form
  87. * name,
  88. * uniquename,
  89. * description,
  90. * type => select from cvterm with key cvterm_id,
  91. * organism => select from available with key organism_id
  92. * main_db_reference => accession, version, description, db_name(select from dropdown)
  93. *
  94. * @param $node
  95. * An empty node object on insert OR the current stock node object on update
  96. * @param $form_state
  97. * The current state of the form
  98. *
  99. * @return
  100. * A description of the form to be rendered by drupal_get_form()
  101. *
  102. * @ingroup tripal_stock
  103. */
  104. function chado_stock_form($node, $form_state) {
  105. /* I don't think we need this... commenting out but leaving just in case
  106. // If existing stock then expand all fields needed using the chado API
  107. if (isset($node->nid)) {
  108. $fields_needed = array('stock.uniquename', 'stock.name', 'stock.stock_id', 'stock.type_id', 'stock.organism_id', 'stock.description', 'stock.dbxref_id', 'dbxref.accession', 'dbxref.description', 'dbxref.db_id', 'db.db_id');
  109. foreach ($fields_needed as $field_name) {
  110. // Check to see if it's excluded and expand it if so
  111. if (isset($node->expandable_fields)) {
  112. if (in_array($field_name, $node->expandable_fields)) {
  113. $node = chado_expand_var($node, 'field', $field_name);
  114. }
  115. }
  116. }
  117. }
  118. */
  119. //TODO: @lacey can you take a look at the above code?
  120. // Default values can come in the following ways:
  121. //
  122. // 1) as elements of the $node object. This occurs when editing an existing stock
  123. // 2) in the $form_state['values'] array which occurs on a failed validation or
  124. // ajax callbacks from non submit form elements
  125. // 3) in the $form_state['input'] array which occurs on ajax callbacks from submit
  126. // form elements and the form is being rebuilt
  127. //
  128. // set form field defaults
  129. $sname = '';
  130. $uniquename = '';
  131. $stock_id = 0;
  132. $type_id = 0;
  133. $organism_id = 0;
  134. $sdescription = '';
  135. $dbxref_accession = '';
  136. $dbxref_description = '';
  137. $dbxref_database = 0;
  138. // 1) if we are editing an existing node then the stock is already part of the node
  139. if (property_exists($node, 'stock')) {
  140. $sname = $node->stock->name;
  141. $uniquename = $node->stock->uniquename;
  142. $stock_id = $node->stock->stock_id;
  143. $type_id = $node->stock->type_id->cvterm_id;
  144. $organism_id = $node->stock->organism_id->organism_id;
  145. $sdescription = $node->stock->description;
  146. if (isset($node->stock->dbxref_id->db_id)) {
  147. $dbxref_accession = $node->stock->dbxref_id->accession;
  148. $dbxref_description = $node->stock->dbxref_id->description;
  149. $dbxref_database = $node->stock->dbxref_id->db_id->db_id;
  150. }
  151. }
  152. // 2) if we are re constructing the form from a failed validation or ajax callback
  153. // then use the $form_state['values'] values
  154. if (array_key_exists('values', $form_state)) {
  155. $sname = $form_state['values']['sname'];
  156. $uniquename = $form_state['values']['uniquename'];
  157. $stock_id = $form_state['values']['stock_id'];
  158. $type_id = $form_state['values']['type_id'];
  159. $organism_id = $form_state['values']['organism_id'];
  160. $sdescription = $form_state['values']['description'];
  161. $dbxref_accession = $form_state['values']['accession'];
  162. $dbxref_description = $form_state['values']['db_description'];
  163. $dbxref_database = $form_state['values']['database'];
  164. }
  165. // 3) if we are re building the form from after submission (from ajax call) then
  166. // the values are in the $form_state['input'] array
  167. if (array_key_exists('input', $form_state) and !empty($form_state['input'])) {
  168. $sname = $form_state['input']['sname'];
  169. $uniquename = $form_state['input']['uniquename'];
  170. $stock_id = $form_state['input']['stock_id'];
  171. $type_id = $form_state['input']['type_id'];
  172. $organism_id = $form_state['input']['organism_id'];
  173. $sdescription = $form_state['input']['description'];
  174. $dbxref_accession = $form_state['input']['accession'];
  175. $dbxref_description = $form_state['input']['db_description'];
  176. $dbxref_database = $form_state['input']['database'];
  177. }
  178. $form['names'] = array(
  179. '#type' => 'fieldset',
  180. '#title' => t('Stock Name')
  181. );
  182. $form['names']['sname'] = array(
  183. '#type' => 'textfield',
  184. '#title' => t('Name'),
  185. '#default_value' => $sname,
  186. '#required' => TRUE
  187. );
  188. $form['names']['uniquename'] = array(
  189. '#type' => 'textfield',
  190. '#title' => t('Unique Name'),
  191. '#default_value' => $uniquename,
  192. '#required' => TRUE
  193. );
  194. if ($stock_id > 0) {
  195. $form['names']['stock_id'] = array(
  196. '#type' => 'hidden',
  197. '#value' => $stock_id,
  198. );
  199. }
  200. $form['details'] = array(
  201. '#type' => 'fieldset',
  202. '#title' => t('Stock Details')
  203. );
  204. $type_options = tripal_get_cvterm_default_select_options('stock', 'type_id', 'stock types');
  205. $type_options[0] = 'Select a Type';
  206. $form['details']['type_id'] = array(
  207. '#type' => 'select',
  208. '#title' => t('Type of Stock'),
  209. '#options' => $type_options,
  210. '#default_value' => $type_id,
  211. '#required' => TRUE,
  212. );
  213. // get the list of organisms
  214. $sql = "SELECT * FROM {organism} ORDER BY genus, species";
  215. $org_rset = chado_query($sql);
  216. $organisms = array();
  217. $organisms[''] = '';
  218. while ($organism = $org_rset->fetchObject()) {
  219. $organisms[$organism->organism_id] = "$organism->genus $organism->species ($organism->common_name)";
  220. }
  221. $form['details']['organism_id'] = array(
  222. '#type' => 'select',
  223. '#title' => t('Source Organism for stock'),
  224. '#default_value' => $organism_id,
  225. '#options' => $organisms,
  226. '#required' => TRUE
  227. );
  228. $form['details']['stock_description'] = array(
  229. '#type' => 'textarea',
  230. '#title' => t('Notes'),
  231. '#default_value' => $sdescription,
  232. '#description' => t('Briefly enter any notes on the above stock. This should not include phenotypes or genotypes.'),
  233. );
  234. $form['database_reference'] = array(
  235. '#type' => 'fieldset',
  236. '#title' => t('Stock Database Reference')
  237. );
  238. $form['database_reference']['accession'] = array(
  239. '#type' => 'textfield',
  240. '#title' => t('Accession'),
  241. '#default_value' => $dbxref_accession,
  242. );
  243. $form['database_reference']['db_description'] = array(
  244. '#type' => 'textarea',
  245. '#title' => t('Description of Database Reference'),
  246. '#default_value' => $dbxref_description,
  247. '#description' => t('Optionally enter a description about the database accession.')
  248. );
  249. $db_options = tripal_db_get_db_options();
  250. $db_options[0] = 'Select a Database';
  251. $form['database_reference']['database'] = array(
  252. '#type' => 'select',
  253. '#title' => t('Database'),
  254. '#options' => $db_options,
  255. '#default_value' => $dbxref_database
  256. );
  257. // PROPERTIES FORM
  258. //---------------------------------------------
  259. $prop_cv = tripal_get_default_cv('stockprop', 'type_id');
  260. $cv_id = $prop_cv ? $prop_cv->cv_id : NULL;
  261. $details = array(
  262. 'property_table' => 'stockprop',
  263. 'chado_id' => $stock_id,
  264. 'cv_id' => $cv_id
  265. );
  266. chado_add_node_form_properties($form, $form_state, $details);
  267. // ADDITIONAL DBXREFS FORM
  268. //---------------------------------------------
  269. $details = array(
  270. 'linking_table' => 'stock_dbxref',
  271. 'base_foreign_key' => 'stock_id',
  272. 'base_key_value' => $stock_id
  273. );
  274. chado_add_node_form_dbxrefs($form, $form_state, $details);
  275. // RELATIONSHIPS FORM
  276. //---------------------------------------------
  277. $relationship_cv = tripal_get_default_cv('stock_relationship', 'type_id');
  278. $cv_id = $relationship_cv ? $relationship_cv->cv_id : NULL;
  279. $details = array(
  280. 'relationship_table' => 'stock_relationship',
  281. 'base_table' => 'stock',
  282. 'base_foreign_key' => 'stock_id',
  283. 'base_key_value' => $stock_id,
  284. 'nodetype' => 'stock',
  285. 'cv_id' => $cv_id
  286. );
  287. chado_add_node_form_relationships($form, $form_state, $details);
  288. return $form;
  289. }
  290. /**
  291. * Implements hook_validate().
  292. * Validate the input from the chado_stock node form
  293. *
  294. * @param $node
  295. * The current node including fields with the form element names and submitted values
  296. * @param $form
  297. * A description of the form to be rendered by drupal_get_form()
  298. *
  299. * @ingroup tripal_stock
  300. */
  301. function chado_stock_validate(&$node, $form, &$form_state) {
  302. // if this is a delete then don't validate
  303. if($node->op == 'Delete') {
  304. return;
  305. }
  306. // we are syncing if we do not have a node ID but we do have a stock_id. We don't
  307. // need to validate during syncing so just skip it.
  308. if (is_null($node->nid) and property_exists($node, 'stock_id') and $node->stock_id != 0) {
  309. return;
  310. }
  311. // remove surrounding whitespace
  312. $node->uniquename = trim($node->uniquename);
  313. $node->sname = trim($node->sname);
  314. $node->stock_description = trim($node->stock_description);
  315. $node->accession = trim($node->accession);
  316. $node->db_description = trim($node->db_description);
  317. $int_in_chado_sql = "SELECT count(*) as count FROM {:table} WHERE :column = :value";
  318. $string_in_chado_sql = "SELECT count(*) as count FROM {:table} WHERE :column = :value";
  319. // if this is an update, we want to make sure that a different stock for
  320. // the organism doesn't already have this uniquename. We don't want to give
  321. // two sequences the same uniquename
  322. if (property_exists($node, 'nid') and property_exists($node, 'stock_id')) {
  323. $sql = "
  324. SELECT *
  325. FROM {stock} S
  326. INNER JOIN {cvterm} CVT ON S.type_id = CVT.cvterm_id
  327. WHERE
  328. uniquename = :uname AND organism_id = :organism_id AND
  329. CVT.name = :cvtname AND NOT stock_id = :stock_id
  330. ";
  331. $result = chado_query($sql, array(':uname' => $node->uniquename,
  332. ':organism_id' => $node->organism_id, ':cvtname' => $node->type_id,
  333. ':stock_id' => $node->stock_id))->fetchObject();
  334. if ($result) {
  335. form_set_error('uniquename', t("Stock update cannot proceed. The stock name '$node->uniquename' is not unique for this organism. Please provide a unique name for this stock."));
  336. }
  337. }
  338. // if this is an insert then we just need to make sure this name doesn't
  339. // already exist for this organism if it does then we need to throw an error
  340. else {
  341. $sql = "
  342. SELECT *
  343. FROM {Stock} S
  344. INNER JOIN {cvterm} CVT ON S.type_id = CVT.cvterm_id
  345. WHERE uniquename = :uname AND organism_id = :organism_id AND CVT.name = :cvtname";
  346. $result = chado_query($sql, array(':uname' => $node->uniquename,
  347. ':organism_id' => $node->organism_id, ':cvtname' => $node->type_id))->fetchObject();
  348. if ($result) {
  349. form_set_error('uniquename', t("Stock insert cannot proceed. The stock name '$node->uniquename' already exists for this organism. Please provide a unique name for this stock."));
  350. }
  351. }
  352. // Check Type of Stock is valid cvterm_id in chado ( $form['values']['details']['type_id'] )
  353. if ($node->type_id == 0) {
  354. form_set_error('type_id', 'Please select a type of stock.');
  355. }
  356. else {
  357. $replace = array(':table' => 'cvterm', ':column' => 'cvterm_id');
  358. $new_sql = str_replace(array_keys($replace),$replace,$int_in_chado_sql);
  359. $num_rows = chado_query($new_sql, array(':value' => $node->type_id))->fetchObject();
  360. if ( $num_rows->count != 1) {
  361. form_set_error('type_id', "The type you selected is not valid. Please choose another one. (CODE:$num_rows)"); }
  362. }
  363. // Check Source Organism is valid organism_id in chado ( $form['values']['details']['organism_id'] )
  364. if ( $node->organism_id == 0) {
  365. form_set_error('organism_id', 'Please select a source organism for this stock');
  366. }
  367. else {
  368. $replace = array(':table' => 'organism', ':column' => 'organism_id');
  369. $new_sql = str_replace(array_keys($replace),$replace,$int_in_chado_sql);
  370. $num_rows = chado_query($new_sql, array(':value' => $node->organism_id))->fetchObject();
  371. if ( $num_rows->count != 1 ) {
  372. form_set_error('organism_id', "The organism you selected is not valid. Please choose another one. (CODE:$num_rows)"); }
  373. }
  374. // Check if Accession also database
  375. if ($node->accession != '') {
  376. if ($node->database == 0) {
  377. // there is an accession but no database selected
  378. form_set_error('database', 'You need to enter both a database and an accession for that database in order to add a database reference.');
  379. }
  380. }
  381. else {
  382. if ($node->database > 0) {
  383. // there is a database selected but no accession
  384. form_set_error('accession', 'You need to enter both a database and an accession for that database in order to add a database reference.');
  385. }
  386. }
  387. // Check database is valid db_id in chado ( $form['values']['database_reference']['database'] )
  388. if ( $node->database > 0) {
  389. $replace = array(':table' => 'db', ':column' => 'db_id');
  390. $new_sql = str_replace(array_keys($replace),$replace,$int_in_chado_sql);
  391. $num_rows = chado_query($new_sql, array(':value' => $node->database))->fetchObject();
  392. if ($num_rows->count != 1) {
  393. form_set_error('database', 'The database you selected is not valid. Please choose another one.'); }
  394. }
  395. }
  396. /**
  397. * Implements hook_insert().
  398. * Inserts data from chado_stock_form() into drupal and chado
  399. *
  400. * @param $node
  401. * The current node including fields with the form element names and submitted values
  402. *
  403. * @return
  404. * TRUE if the node was successfully inserted into drupal/chado; FALSE otherwise
  405. *
  406. * @ingroup tripal_stock
  407. */
  408. function chado_stock_insert($node) {
  409. $node->uniquename = trim($node->uniquename);
  410. $node->sname = trim($node->sname);
  411. // if there is an stock_id in the $node object then this must be a sync so
  412. // we can skip adding the stock to chado as it is already there, although
  413. // we do need to proceed with the rest of the insert
  414. if (!property_exists($node, 'stock_id')) {
  415. // before we can add the stock, we must add the dbxref if one has been
  416. // provided by the user.
  417. $dbxref_status = 0;
  418. if (!empty($node->accession) ) {
  419. if (!empty($node->database) ) {
  420. $values = array(
  421. 'db_id' => $node->database,
  422. 'accession' => $node->accession,
  423. );
  424. if (!chado_select_record('dbxref', array('dbxref_id'), $values)) {
  425. $values['description'] = $node->db_description;
  426. $values['version'] = '1';
  427. $dbxref_status = chado_insert_record('dbxref', $values);
  428. if (!$dbxref_status) {
  429. drupal_set_message(t('Unable to add database reference to this stock.'), 'warning');
  430. tripal_report_error('tripal_stock', TRIPAL_WARNING,
  431. 'Insert Stock: Unable to create dbxref where values:%values',
  432. array('%values' => print_r($values, TRUE)));
  433. }
  434. }
  435. else {
  436. $dbxref_status = 1;
  437. }
  438. }
  439. }
  440. // create stock including the dbxref
  441. $stock = '';
  442. if ($dbxref_status) {
  443. $values = array(
  444. 'dbxref_id' => array(
  445. 'db_id' => $node->database,
  446. 'accession' => $node->accession
  447. ),
  448. 'organism_id' => $node->organism_id,
  449. 'name' => $node->sname,
  450. 'uniquename' => $node->uniquename,
  451. 'description' => $node->stock_description,
  452. 'type_id' => $node->type_id
  453. );
  454. $stock = chado_insert_record('stock', $values);
  455. }
  456. // create a stock without a dbxref
  457. else {
  458. $values = array(
  459. 'organism_id' => $node->organism_id,
  460. 'name' => $node->sname,
  461. 'uniquename' => $node->uniquename,
  462. 'description' => $node->stock_description,
  463. 'type_id' => $node->type_id
  464. );
  465. $stock = chado_insert_record('stock', $values);
  466. }
  467. if (is_array($stock)) {
  468. $stock_added = TRUE;
  469. $stock_id = $stock['stock_id'];
  470. }
  471. else {
  472. $stock_added = FALSE;
  473. }
  474. if ($stock_added) {
  475. // Now add properties
  476. $details = array(
  477. 'property_table' => 'stockprop',
  478. 'base_table' => 'stock',
  479. 'foreignkey_name' => 'stock_id',
  480. 'foreignkey_value' => $stock_id
  481. );
  482. chado_update_node_form_properties($node, $details);
  483. // Now add the additional references
  484. $details = array(
  485. 'linking_table' => 'stock_dbxref',
  486. 'foreignkey_name' => 'stock_id',
  487. 'foreignkey_value' => $stock_id
  488. );
  489. chado_update_node_form_dbxrefs($node, $details);
  490. // Now add in relationships
  491. $details = array(
  492. 'relationship_table' => 'stock_relationship',
  493. 'foreignkey_value' => $stock_id
  494. );
  495. chado_update_node_form_relationships($node, $details);
  496. }
  497. } //end of adding stock to chado
  498. else {
  499. // stock already exists since this is a sync
  500. $stock_added = TRUE;
  501. $stock['stock_id'] = $node->stock_id;
  502. }
  503. // if the stock creation was succesful then add the URL and the entry in the
  504. // chado_stock table
  505. if ($stock_added) {
  506. // add the entry to the chado_stock table
  507. db_insert('chado_stock')->fields(array(
  508. 'nid' => (int) $node->nid,
  509. 'vid' => (int) $node->vid,
  510. 'stock_id' => (int) $stock['stock_id']
  511. ))->execute();
  512. }
  513. else {
  514. drupal_set_message(t('Error during stock creation.'), 'error');
  515. tripal_report_error('tripal_stock', TRIPAL_WARNING,
  516. 'Insert Stock: Unable to create stock where values:%values',
  517. array('%values' => print_r($values, TRUE)));
  518. return FALSE;
  519. }
  520. }
  521. /**
  522. * Implements hook_update().
  523. * Handles Editing/Updating of main stock info
  524. *
  525. * NOTE: Currently just writes over all old data
  526. *
  527. * @param $node
  528. * The current node including fields with the form element names and submitted values
  529. *
  530. * @return
  531. * TRUE if the node was successfully updated in drupal/chado; FALSE otherwise
  532. *
  533. * @ingroup tripal_stock
  534. */
  535. function chado_stock_update($node) {
  536. $node->uniquename = trim($node->uniquename);
  537. $node->sname = trim($node->sname);
  538. if ($node->revision) {
  539. // there is no way to handle revisions in Chado but leave
  540. // this here just to make not we've addressed it.
  541. }
  542. //update dbxref
  543. $dbxref_status = NULL;
  544. $dbxref_present = FALSE;
  545. if ($node->database) {
  546. $dbxref_present = TRUE;
  547. if ($node->accession) {
  548. $dbxref_mode = '';
  549. $stock = chado_select_record(
  550. 'stock',
  551. array('dbxref_id', 'type_id'),
  552. array('stock_id' => $node->stock_id)
  553. );
  554. if ($stock[0]->dbxref_id) {
  555. $values = array(
  556. 'db_id' => $node->database,
  557. 'accession' => $node->accession,
  558. 'description' => $node->db_description
  559. );
  560. $dbxref_status = chado_update_record(
  561. 'dbxref',
  562. array('dbxref_id' => $stock[0]->dbxref_id),
  563. $values
  564. );
  565. $dbxref_mode = 'Update';
  566. }
  567. else {
  568. if ($stock[0]->type_id) {
  569. //create the dbxref
  570. //used the type_id as a control to check we have a stock but not a dbxref
  571. $values = array(
  572. 'db_id' => $node->database,
  573. 'accession' => $node->accession,
  574. 'description' => $node->db_description,
  575. 'version' => '1',
  576. );
  577. $dbxref_status = chado_insert_record(
  578. 'dbxref',
  579. $values
  580. );
  581. $dbxref_mode = 'Create';
  582. }
  583. else {
  584. drupal_set_message(t('Unable to find stock to Update'), 'error');
  585. tripal_report_error('tripal_stock', TRIPAL_ERROR,
  586. 'Stock Update: Unable to find stock to update using values: %values',
  587. array('%values', print_r($values, TRUE))
  588. );
  589. return FALSE;
  590. }
  591. }
  592. }
  593. if (!$dbxref_status) {
  594. tripal_report_error('tripal_stock', TRIPAL_WARNING,
  595. 'Stock Update: Unable to %mode main stock dbxref with values: %values',
  596. array('%values' => print_r($values, TRUE), '%mode' => $dbxref_mode));
  597. }
  598. }
  599. //can't change stock id which is all thats stored in drupal thus only update chado
  600. $update_values = array(
  601. 'organism_id' => $node->organism_id,
  602. 'name' => $node->sname,
  603. 'uniquename' => $node->uniquename,
  604. 'description' => $node->stock_description,
  605. 'type_id' => $node->type_id,
  606. );
  607. if ($dbxref_present) {
  608. if ($dbxref_status) {
  609. $update_values['dbxref_id'] = array(
  610. 'db_id' => $node->database,
  611. 'accession' => $node->accession
  612. );
  613. }
  614. }
  615. $status = chado_update_record('stock', array('stock_id' => $node->stock_id), $update_values);
  616. if (!$status) {
  617. drupal_set_message(t('Unable to update stock'), 'error');
  618. tripal_report_error('tripal_stock', TRIPAL_ERROR,
  619. 'Stock Update: Unable to update stock using match values: %mvalues and update values: %uvalues',
  620. array('%mvalues' => print_r(array('stock_id' => $node->stock_id), TRUE), '%uvalues' => print_r($update_values, TRUE))
  621. );
  622. }
  623. else {
  624. // set the URL for this stock page
  625. $values = array('stock_id' => $node->stock_id);
  626. $stock = chado_select_record('stock', array('*'), $values);
  627. }
  628. // now update the properties
  629. if ($node->stock_id > 0) {
  630. $details = array(
  631. 'property_table' => 'stockprop',
  632. 'base_table' => 'stock',
  633. 'foreignkey_name' => 'stock_id',
  634. 'foreignkey_value' => $node->stock_id
  635. );
  636. chado_update_node_form_properties($node, $details);
  637. }
  638. // now update the additional dbxrefs
  639. if ($node->stock_id > 0) {
  640. $details = array(
  641. 'linking_table' => 'stock_dbxref',
  642. 'foreignkey_name' => 'stock_id',
  643. 'foreignkey_value' => $node->stock_id
  644. );
  645. chado_update_node_form_dbxrefs($node, $details);
  646. }
  647. // now update relationships
  648. if ($node->stock_id > 0) {
  649. $details = array(
  650. 'relationship_table' => 'stock_relationship',
  651. 'foreignkey_value' => $node->stock_id
  652. );
  653. chado_update_node_form_relationships($node, $details);
  654. }
  655. }
  656. /**
  657. * Implements hook_delete().
  658. * Handles deleting of chado_stocks
  659. *
  660. * NOTE: Currently deletes data -no undo or record-keeping functionality
  661. *
  662. * @param $node
  663. * The current node including fields with the form element names and submitted values
  664. *
  665. * @return
  666. * TRUE if the node was successfully deleted from drupal/chado; FALSE otherwise
  667. *
  668. * @ingroup tripal_stock
  669. */
  670. function chado_stock_delete($node) {
  671. // Set stock in chado: is_obsolete = TRUE
  672. chado_query("DELETE FROM {stock} WHERE stock_id = :stock_id", array(':stock_id' => $node->stock->stock_id));
  673. //remove drupal node and all revisions
  674. db_query("DELETE FROM {chado_stock} WHERE nid = :nid", array(':nid' => $node->nid));
  675. }
  676. /**
  677. * Used by Tripal Chado Node API during sync'ing of nodes
  678. *
  679. * @ingroup tripal_stock
  680. */
  681. function chado_stock_chado_node_sync_create_new_node($new_node, $record) {
  682. $new_node->organism_id = $record->organism_id;
  683. $new_node->sname = $record->name;
  684. $new_node->uniquename = $record->uniquename;
  685. $new_node->type_id = $record->type_id;
  686. return $new_node;
  687. }
  688. /**
  689. * Implements hook_node_presave(). Acts on all content types.
  690. *
  691. * @ingroup tripal_stock
  692. */
  693. function tripal_stock_node_presave($node) {
  694. switch ($node->type) {
  695. case 'chado_stock':
  696. // for a form submission the fields part of the node object
  697. // but for a sync the fields are in an object of the node
  698. $organism_id = null;
  699. $sname = '';
  700. $uniquename = '';
  701. $type = '';
  702. if(property_exists($node, 'organism_id')) {
  703. $organism_id = $node->organism_id;
  704. $sname = $node->sname;
  705. $uniquename = $node->uniquename;
  706. $type_id = $node->type_id;
  707. $values = array('cvterm_id' => $node->type_id);
  708. $cvterm = chado_select_record('cvterm', array('name'), $values);
  709. $type = $cvterm[0]->name;
  710. }
  711. else if (property_exists($node, 'stock')) {
  712. $organism_id = $node->stock->organism_id;
  713. $sname = $node->stock->name;
  714. $uniquename = $node->stock->uniquename;
  715. $type = $node->stock->type_id->name;
  716. }
  717. $values = array('organism_id' => $organism_id);
  718. $organism = chado_select_record('organism', array('genus','species'), $values);
  719. // If your module is using the Chado Node: Title & Path API to allow custom titles
  720. // for your node type. Every time you want the title of the node, you need to use the
  721. // following API function:
  722. $node->title = chado_get_node_title($node);
  723. if ($sname == $uniquename) {
  724. $node->title = "$sname ($type) " . $organism[0]->genus . ' ' . $organism[0]->species;
  725. }
  726. break;
  727. }
  728. }
  729. /**
  730. * Implements hook_node_view(). Acts on all content types.
  731. *
  732. * @ingroup tripal_stock
  733. */
  734. function tripal_stock_node_view($node, $view_mode, $langcode) {
  735. switch ($node->type) {
  736. case 'chado_stock':
  737. if ($view_mode == 'full') {
  738. $node->content['tripal_stock_base'] = array(
  739. '#markup' => theme('tripal_stock_base', array('node' => $node)),
  740. '#tripal_toc_id' => 'base',
  741. '#tripal_toc_title' => 'Overview',
  742. '#weight' => -100,
  743. );
  744. $node->content['tripal_stock_collections'] = array(
  745. '#markup' => theme('tripal_stock_collections', array('node' => $node)),
  746. '#tripal_toc_id' => 'collections',
  747. '#tripal_toc_title' => 'Stock Collections',
  748. );
  749. $node->content['tripal_stock_properties'] = array(
  750. '#markup' => theme('tripal_stock_properties', array('node' => $node)),
  751. '#tripal_toc_id' => 'properties',
  752. '#tripal_toc_title' => 'Properties',
  753. );
  754. $node->content['tripal_stock_references'] = array(
  755. '#markup' => theme('tripal_stock_references', array('node' => $node)),
  756. '#tripal_toc_id' => 'references',
  757. '#tripal_toc_title' => 'Cross References',
  758. );
  759. $node->content['tripal_stock_relationships'] = array(
  760. '#markup' => theme('tripal_stock_relationships', array('node' => $node)),
  761. '#tripal_toc_id' => 'relationships',
  762. '#tripal_toc_title' => 'Relationships',
  763. );
  764. $node->content['tripal_stock_synonyms'] = array(
  765. '#markup' => theme('tripal_stock_synonyms', array('node' => $node)),
  766. '#tripal_toc_id' => 'synonyms',
  767. '#tripal_toc_title' => 'Synonyms',
  768. );
  769. $node->content['tripal_stock_publications'] = array(
  770. '#markup' => theme('tripal_stock_publications', array('node' => $node)),
  771. '#tripal_toc_id' => 'publications',
  772. '#tripal_toc_title' => 'Publications',
  773. );
  774. }
  775. if ($view_mode == 'teaser') {
  776. $node->content['tripal_stock_teaser'] = array(
  777. '#markup' => theme('tripal_stock_teaser', array('node' => $node)),
  778. );
  779. }
  780. break;
  781. case 'chado_organism':
  782. if ($view_mode == 'full') {
  783. $node->content['tripal_organism_stocks'] = array(
  784. '#markup' => theme('tripal_organism_stocks', array('node' => $node)),
  785. '#tripal_toc_id' => 'stocks',
  786. '#tripal_toc_title' => 'Stocks',
  787. );
  788. }
  789. break;
  790. }
  791. }
  792. /**
  793. * Implements hook_node_insert().
  794. * Acts on all content types.
  795. *
  796. * @ingroup tripal_stock
  797. */
  798. function tripal_stock_node_insert($node) {
  799. // set the URL path after inserting. We do it here because we do not
  800. // know the stock_id in the presave
  801. switch ($node->type) {
  802. case 'chado_stock':
  803. // get the feature details from chado
  804. $stock_id = chado_get_id_from_nid('stock', $node->nid);
  805. $values = array('stock_id' => $stock_id);
  806. $stock = chado_generate_var('stock', $values);
  807. $stock = chado_expand_var($stock, 'field', 'stock.uniquename');
  808. $stock = chado_expand_var($stock, 'field', 'stock.description');
  809. $node->stock = $stock;
  810. // If your module is using the Chado Node: Title & Path API to allow custom titles
  811. // for your node type. Every time you want the title of the node, you need to use the
  812. // following API function:
  813. $node->title = chado_get_node_title($node);
  814. // on an insert we need to add the stock_id to the node object
  815. // so that the tripal_stock_get_stock_url function can set the URL properly
  816. $node->stock_id = chado_get_id_from_nid('stock', $node->nid);
  817. // remove any previous alias
  818. db_query("DELETE FROM {url_alias} WHERE source = :source", array(':source' => "node/$node->nid"));
  819. // set the URL for this stock page
  820. $url_alias = tripal_stock_get_stock_url($node);
  821. $path_alias = array("source" => "node/$node->nid", "alias" => $url_alias);
  822. path_save($path_alias);
  823. break;
  824. }
  825. }
  826. /**
  827. * Implements hook_node_update().
  828. * Acts on all content types.
  829. *
  830. * @ingroup tripal_stock
  831. */
  832. function tripal_stock_node_update($node) {
  833. // add items to other nodes, build index and search results
  834. switch ($node->type) {
  835. case 'chado_stock':
  836. // get the feature details from chado
  837. $stock_id = chado_get_id_from_nid('stock', $node->nid);
  838. $values = array('stock_id' => $stock_id);
  839. $stock = chado_generate_var('stock', $values);
  840. $stock = chado_expand_var($stock, 'field', 'stock.uniquename');
  841. $stock = chado_expand_var($stock, 'field', 'stock.description');
  842. $node->stock = $stock;
  843. // If your module is using the Chado Node: Title & Path API to allow custom titles
  844. // for your node type. Every time you want the title of the node, you need to use the
  845. // following API function:
  846. $node->title = chado_get_node_title($node);
  847. // remove any previous alias
  848. db_query("DELETE FROM {url_alias} WHERE source = :source", array(':source' => "node/$node->nid"));
  849. // set the URL for this stock page
  850. $url_alias = tripal_stock_get_stock_url($node);
  851. $path_alias = array("source" => "node/$node->nid", "alias" => $url_alias);
  852. path_save($path_alias);
  853. break;
  854. }
  855. }
  856. /**
  857. * Return the url alias for a stock
  858. *
  859. * @param $node
  860. * A node object containing at least the stock_id and nid
  861. * @param $url_alias
  862. * Optional. This should be the URL alias syntax string that contains
  863. * placeholders such as [id], [genus], [species], [name], [uniquename],
  864. * and [type]. These placeholders will be substituted for actual values.
  865. * If this parameter is not provided then the value of the
  866. * chado_stock_url_string Drupal variable will be used.
  867. *
  868. * @ingroup tripal_stock
  869. */
  870. function tripal_stock_get_stock_url($node, $url_alias = NULL) {
  871. // get the starting URL alias
  872. if(!$url_alias) {
  873. $url_alias = variable_get('chado_stock_url_string', '/stock/[genus]/[species]/[type]/[uniquename]');
  874. if (!$url_alias) {
  875. $url_alias = '/stock/[genus]/[species]/[type]/[uniquename]';
  876. }
  877. $url_alias = preg_replace('/^\//', '', $url_alias); // remove any preceeding forward slash
  878. }
  879. // get the stock
  880. $values = array('stock_id' => $node->stock_id);
  881. $stock = chado_select_record('stock', array('*'), $values);
  882. if (!$stock) {
  883. tripal_report_error('trp-seturl', TRIPAL_ERROR, "Cannot find stock when setting URL alias for stock: %id", array('%id' => $node->stock_id));
  884. return FALSE;
  885. }
  886. $stock = (object) $stock[0];
  887. // get the organism
  888. $values = array('organism_id' => $stock->organism_id);
  889. $organism = chado_select_record('organism', array('*'), $values);
  890. if (!$organism) {
  891. tripal_report_error('trp-seturl', TRIPAL_ERROR, "Cannot find organism when setting URL alias for stock: %id", array('%id' => $node->stock_id));
  892. return FALSE;
  893. }
  894. $genus = preg_replace('/\s/', '_', strtolower($organism[0]->genus));
  895. $species = preg_replace('/\s/', '_', strtolower($organism[0]->species));
  896. // get the type
  897. $values = array('cvterm_id' => $stock->type_id);
  898. $cvterm = chado_select_record('cvterm', array('name'), $values);
  899. if (!$cvterm) {
  900. tripal_report_error('trp-seturl', TRIPAL_ERROR, "Cannot find type when setting URL alias for stock: %id", array('%id' => $node->stock_id));
  901. return FALSE;
  902. }
  903. $type = preg_replace('/\s/', '_', $cvterm[0]->name);
  904. // now substitute in the values
  905. $url_alias = preg_replace('/\[id\]/', $stock->stock_id, $url_alias);
  906. $url_alias = preg_replace('/\[genus\]/', $genus, $url_alias);
  907. $url_alias = preg_replace('/\[species\]/', $species, $url_alias);
  908. $url_alias = preg_replace('/\[type\]/', $type, $url_alias);
  909. $url_alias = preg_replace('/\[name\]/', $stock->name, $url_alias);
  910. $url_alias = preg_replace('/\[uniquename\]/', $stock->uniquename, $url_alias);
  911. // the dst field of the url_alias table is only 128 characters long.
  912. // if this is the case then simply return the node URL, we can't set this one
  913. if (strlen($url_alias) > 128) {
  914. tripal_report_error('trp-seturl', TRIPAL_ERROR, "Cannot set alias longer than 128 characters: %alias.", array('%alias' => $url_alias));
  915. return "node/" . $node->nid;
  916. }
  917. return $url_alias;
  918. }
  919. /**
  920. * Resets all of the URL alias for all stocks. This function is meant to
  921. * be run using Tripal's job managmenet interface
  922. *
  923. * @param $na
  924. * Tripal expects all jobs to have at least one argument. For this function
  925. * we don't need any, so we have this dummy argument as a filler
  926. * @param $job_id
  927. *
  928. * @ingroup tripal_stock
  929. */
  930. function tripal_stock_set_urls($na = NULL, $job = NULL) {
  931. $transaction = db_transaction();
  932. print "\nNOTE: Setting of URLs is performed using a database transaction. \n" .
  933. "If the load fails or is terminated prematurely then the entire set of \n" .
  934. "new URLs will be rolled back and no changes will be made\n\n";
  935. try {
  936. // get the number of records we need to set URLs for
  937. $csql = "SELECT count(*) FROM {chado_stock}";
  938. $num_nodes = db_query($csql)->fetchField();
  939. // calculate the interval at which we will print an update on the screen
  940. $num_set = 0;
  941. $num_per_interval = 100;
  942. // prepare the statements which will quickly add url alias. Because these
  943. // are not Chado tables we must manually prepare them
  944. $dsql = "DELETE FROM {url_alias} WHERE source = :source";
  945. $isql = "INSERT INTO url_alias (source, alias, language) VALUES (:source, :alias, :language)";
  946. // get the URL alias syntax string
  947. $url_alias = variable_get('chado_stock_url_string', '/stock/[genus]/[species]/[type]/[uniquename]');
  948. $url_alias = preg_replace('/^\//', '', $url_alias); // remove any preceeding forward slash
  949. // get the list of stocks that have been synced
  950. $sql = "SELECT * FROM {chado_stock}";
  951. $nodes = db_query($sql);
  952. foreach ($nodes as $node) {
  953. // get the URL alias
  954. $src = "node/$node->nid";
  955. $dst = tripal_stock_get_stock_url($node, $url_alias);
  956. // if the src and dst is the same (the URL alias couldn't be set)
  957. // then skip to the next one. There's nothing we can do about this one.
  958. if($src == $dst) {
  959. continue;
  960. }
  961. // remove any previous alias and then add the new one
  962. db_query($dsql, array(':source' => $src));
  963. db_query($isql, array(':source' => $src, ':alias' => $dst, ':language' => LANGUAGE_NONE));
  964. // update the job status every 1% stocks
  965. if ($job and $num_set % $num_per_interval == 0) {
  966. $percent = ($num_set / $num_nodes) * 100;
  967. tripal_set_job_progress($job, intval($percent));
  968. $percent = sprintf("%.2f", $percent);
  969. print "Setting URLs (" . $percent . "%). Memory: " . number_format(memory_get_usage()) . " bytes.\r";
  970. }
  971. $num_set++;
  972. }
  973. $percent = ($num_set / $num_nodes) * 100;
  974. tripal_set_job_progress($job, intval($percent));
  975. $percent = sprintf("%.2f", $percent);
  976. print "Setting URLs (" . $percent . "%). Memory: " . number_format(memory_get_usage()) . " bytes.\r";
  977. print "\nDone. Set " . number_format($num_set) . " URLs\n";
  978. }
  979. catch (Exception $e) {
  980. $transaction->rollback();
  981. print "\n"; // make sure we start errors on new line
  982. watchdog_exception('tripal_stock', $e);
  983. watchdog('trp-seturl', "Failed Removing URL Alias: %src", array('%src' => $src), WATCHDOG_ERROR);
  984. }
  985. }
  986. /**
  987. * Implements [content_type]_chado_node_default_title_format().
  988. *
  989. * Defines a default title format for the Chado Node API to set the titles on
  990. * Chado Stock nodes based on chado fields.
  991. */
  992. function chado_stock_chado_node_default_title_format() {
  993. return '[stock.name], [stock.uniquename] ([stock.type_id>cvterm.name]) [stock.organism_id>organism.genus] [stock.organism_id>organism.species]';
  994. }