tripal_stock.chado_node.inc 37 KB

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