tripal_stock.chado_node.inc 37 KB

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