tripal_stock.chado_node.inc 37 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098
  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 (!tripal_core_chado_select('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. // If your module is using the Chado Node: Title & Path API to allow custom titles
  804. // for your node type. Every time you want the title of the node, you need to use the
  805. // following API function:
  806. $node->title = chado_get_node_title($node);
  807. // on an insert we need to add the stock_id to the node object
  808. // so that the tripal_stock_get_stock_url function can set the URL properly
  809. $node->stock_id = chado_get_id_from_nid('stock', $node->nid);
  810. // remove any previous alias
  811. db_query("DELETE FROM {url_alias} WHERE source = :source", array(':source' => "node/$node->nid"));
  812. // set the URL for this stock page
  813. $url_alias = tripal_stock_get_stock_url($node);
  814. $path_alias = array("source" => "node/$node->nid", "alias" => $url_alias);
  815. path_save($path_alias);
  816. break;
  817. }
  818. }
  819. /**
  820. * Implements hook_node_update().
  821. * Acts on all content types.
  822. *
  823. * @ingroup tripal_stock
  824. */
  825. function tripal_stock_node_update($node) {
  826. // add items to other nodes, build index and search results
  827. switch ($node->type) {
  828. case 'chado_stock':
  829. // If your module is using the Chado Node: Title & Path API to allow custom titles
  830. // for your node type. Every time you want the title of the node, you need to use the
  831. // following API function:
  832. $node->title = chado_get_node_title($node);
  833. // remove any previous alias
  834. db_query("DELETE FROM {url_alias} WHERE source = :source", array(':source' => "node/$node->nid"));
  835. // set the URL for this stock page
  836. $url_alias = tripal_stock_get_stock_url($node);
  837. $path_alias = array("source" => "node/$node->nid", "alias" => $url_alias);
  838. path_save($path_alias);
  839. break;
  840. }
  841. }
  842. /**
  843. * Return the url alias for a stock
  844. *
  845. * @param $node
  846. * A node object containing at least the stock_id and nid
  847. * @param $url_alias
  848. * Optional. This should be the URL alias syntax string that contains
  849. * placeholders such as [id], [genus], [species], [name], [uniquename],
  850. * and [type]. These placeholders will be substituted for actual values.
  851. * If this parameter is not provided then the value of the
  852. * chado_stock_url_string Drupal variable will be used.
  853. *
  854. * @ingroup tripal_stock
  855. */
  856. function tripal_stock_get_stock_url($node, $url_alias = NULL) {
  857. // get the starting URL alias
  858. if(!$url_alias) {
  859. $url_alias = variable_get('chado_stock_url_string', '/stock/[genus]/[species]/[type]/[uniquename]');
  860. if (!$url_alias) {
  861. $url_alias = '/stock/[genus]/[species]/[type]/[uniquename]';
  862. }
  863. $url_alias = preg_replace('/^\//', '', $url_alias); // remove any preceeding forward slash
  864. }
  865. // get the stock
  866. $values = array('stock_id' => $node->stock_id);
  867. $stock = chado_select_record('stock', array('*'), $values);
  868. if (!$stock) {
  869. tripal_report_error('trp-seturl', TRIPAL_ERROR, "Cannot find stock when setting URL alias for stock: %id", array('%id' => $node->stock_id));
  870. return FALSE;
  871. }
  872. $stock = (object) $stock[0];
  873. // get the organism
  874. $values = array('organism_id' => $stock->organism_id);
  875. $organism = chado_select_record('organism', array('*'), $values);
  876. if (!$organism) {
  877. tripal_report_error('trp-seturl', TRIPAL_ERROR, "Cannot find organism when setting URL alias for stock: %id", array('%id' => $node->stock_id));
  878. return FALSE;
  879. }
  880. $genus = preg_replace('/\s/', '_', strtolower($organism[0]->genus));
  881. $species = preg_replace('/\s/', '_', strtolower($organism[0]->species));
  882. // get the type
  883. $values = array('cvterm_id' => $stock->type_id);
  884. $cvterm = chado_select_record('cvterm', array('name'), $values);
  885. if (!$cvterm) {
  886. tripal_report_error('trp-seturl', TRIPAL_ERROR, "Cannot find type when setting URL alias for stock: %id", array('%id' => $node->stock_id));
  887. return FALSE;
  888. }
  889. $type = preg_replace('/\s/', '_', $cvterm[0]->name);
  890. // now substitute in the values
  891. $url_alias = preg_replace('/\[id\]/', $stock->stock_id, $url_alias);
  892. $url_alias = preg_replace('/\[genus\]/', $genus, $url_alias);
  893. $url_alias = preg_replace('/\[species\]/', $species, $url_alias);
  894. $url_alias = preg_replace('/\[type\]/', $type, $url_alias);
  895. $url_alias = preg_replace('/\[name\]/', $stock->name, $url_alias);
  896. $url_alias = preg_replace('/\[uniquename\]/', $stock->uniquename, $url_alias);
  897. // the dst field of the url_alias table is only 128 characters long.
  898. // if this is the case then simply return the node URL, we can't set this one
  899. if (strlen($url_alias) > 128) {
  900. tripal_report_error('trp-seturl', TRIPAL_ERROR, "Cannot set alias longer than 128 characters: %alias.", array('%alias' => $url_alias));
  901. return "node/" . $node->nid;
  902. }
  903. return $url_alias;
  904. }
  905. /**
  906. * Resets all of the URL alias for all stocks. This function is meant to
  907. * be run using Tripal's job managmenet interface
  908. *
  909. * @param $na
  910. * Tripal expects all jobs to have at least one argument. For this function
  911. * we don't need any, so we have this dummy argument as a filler
  912. * @param $job_id
  913. *
  914. * @ingroup tripal_stock
  915. */
  916. function tripal_stock_set_urls($na = NULL, $job = NULL) {
  917. $transaction = db_transaction();
  918. print "\nNOTE: Setting of URLs is performed using a database transaction. \n" .
  919. "If the load fails or is terminated prematurely then the entire set of \n" .
  920. "new URLs will be rolled back and no changes will be made\n\n";
  921. try {
  922. // get the number of records we need to set URLs for
  923. $csql = "SELECT count(*) FROM {chado_stock}";
  924. $num_nodes = db_query($csql)->fetchField();
  925. // calculate the interval at which we will print an update on the screen
  926. $num_set = 0;
  927. $num_per_interval = 100;
  928. // prepare the statements which will quickly add url alias. Because these
  929. // are not Chado tables we must manually prepare them
  930. $dsql = "DELETE FROM {url_alias} WHERE source = :source";
  931. $isql = "INSERT INTO url_alias (source, alias, language) VALUES (:source, :alias, :language)";
  932. // get the URL alias syntax string
  933. $url_alias = variable_get('chado_stock_url_string', '/stock/[genus]/[species]/[type]/[uniquename]');
  934. $url_alias = preg_replace('/^\//', '', $url_alias); // remove any preceeding forward slash
  935. // get the list of stocks that have been synced
  936. $sql = "SELECT * FROM {chado_stock}";
  937. $nodes = db_query($sql);
  938. foreach ($nodes as $node) {
  939. // get the URL alias
  940. $src = "node/$node->nid";
  941. $dst = tripal_stock_get_stock_url($node, $url_alias);
  942. // if the src and dst is the same (the URL alias couldn't be set)
  943. // then skip to the next one. There's nothing we can do about this one.
  944. if($src == $dst) {
  945. continue;
  946. }
  947. // remove any previous alias and then add the new one
  948. db_query($dsql, array(':source' => $src));
  949. db_query($isql, array(':source' => $src, ':alias' => $dst, ':language' => LANGUAGE_NONE));
  950. // update the job status every 1% stocks
  951. if ($job and $num_set % $num_per_interval == 0) {
  952. $percent = ($num_set / $num_nodes) * 100;
  953. tripal_job_set_progress($job, intval($percent));
  954. $percent = sprintf("%.2f", $percent);
  955. print "Setting URLs (" . $percent . "%). Memory: " . number_format(memory_get_usage()) . " bytes.\r";
  956. }
  957. $num_set++;
  958. }
  959. $percent = ($num_set / $num_nodes) * 100;
  960. tripal_job_set_progress($job, intval($percent));
  961. $percent = sprintf("%.2f", $percent);
  962. print "Setting URLs (" . $percent . "%). Memory: " . number_format(memory_get_usage()) . " bytes.\r";
  963. print "\nDone. Set " . number_format($num_set) . " URLs\n";
  964. }
  965. catch (Exception $e) {
  966. $transaction->rollback();
  967. print "\n"; // make sure we start errors on new line
  968. watchdog_exception('tripal_stock', $e);
  969. watchdog('trp-seturl', "Failed Removing URL Alias: %src", array('%src' => $src), WATCHDOG_ERROR);
  970. }
  971. }
  972. /**
  973. * Implements [content_type]_chado_node_default_title_format().
  974. *
  975. * Defines a default title format for the Chado Node API to set the titles on
  976. * Chado Stock nodes based on chado fields.
  977. */
  978. function chado_stock_chado_node_default_title_format() {
  979. return '[stock.name], [stock.uniquename] ([stock.type_id>cvterm.name]) [stock.organism_id>organism.genus] [stock.organism_id>organism.species]';
  980. }