tripal_jbrowse_mgmt.api.inc 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682
  1. <?php
  2. /**
  3. * @file
  4. */
  5. /**
  6. * Get saved settings.
  7. *
  8. * @return null
  9. */
  10. function tripal_jbrowse_mgmt_get_settings() {
  11. $default = [
  12. 'bin_path' => '',
  13. 'link' => '',
  14. 'data_dir' => '',
  15. 'data_path' => '',
  16. 'menu_template' => [],
  17. ];
  18. $variable = variable_get('tripal_jbrowse_mgmt_settings', json_encode($default));
  19. $settings = json_decode($variable, TRUE) + $default;
  20. return $settings;
  21. }
  22. /**
  23. * Save settings.
  24. *
  25. * @param array $settings
  26. *
  27. * @return array The final merged settings
  28. */
  29. function tripal_jbrowse_mgmt_save_settings($settings) {
  30. $default = [
  31. 'bin_path' => '',
  32. 'link' => '',
  33. 'data_dir' => '',
  34. 'menu_template' => [],
  35. ];
  36. $final = $settings + $default;
  37. variable_set('tripal_jbrowse_mgmt_settings', json_encode($final));
  38. return $final;
  39. }
  40. /**
  41. * Get an array to instances.
  42. *
  43. * @return mixed
  44. */
  45. function tripal_jbrowse_mgmt_get_instances($conditions = NULL) {
  46. static $users = [];
  47. static $organisms = [];
  48. static $analysis = [];
  49. $instances = db_select('tripal_jbrowse_mgmt_instances', 'H')->fields('H');
  50. if ($conditions) {
  51. foreach ($conditions as $field => $value) {
  52. $instances->condition($field, $value);
  53. }
  54. }
  55. $instances = $instances->execute()->fetchAll();
  56. foreach ($instances as $key => &$instance) {
  57. if (!isset($users[$instance->uid])) {
  58. $users[$instance->uid] = user_load($instance->uid);
  59. }
  60. $instance->user = $users[$instance->uid];
  61. if (!isset($organisms[$instance->organism_id])) {
  62. $organisms[$instance->organism_id] = chado_query('SELECT * FROM {organism} WHERE organism_id=:id',
  63. [':id' => $instance->organism_id])->fetchObject();
  64. }
  65. $instance->organism = $organisms[$instance->organism_id];
  66. if($instance->analysis_id){
  67. if (!isset($analysis[$instance->analysis_id])){
  68. $analysis[$instance->analysis_id] = chado_query('SELECT * FROM {analysis} WHERE analysis_id=:id',
  69. [':id' => $instance->analysis_id])->fetchObject();
  70. }
  71. $instance->analysis = $analysis[$instance->analysis_id];
  72. }
  73. }
  74. return $instances;
  75. }
  76. /**
  77. * Create a new instance.
  78. *
  79. * @param $data
  80. *
  81. * @return \DatabaseStatementInterface|int
  82. *
  83. * @throws \Exception
  84. */
  85. function tripal_jbrowse_mgmt_create_instance($data) {
  86. global $user;
  87. // Check that required fields are provided.
  88. $required = ['organism_id', 'created_at'];
  89. foreach ($required as $key) {
  90. if (!isset($data[$key])) {
  91. tripal_report_error(
  92. 'tripal_jbrowse_mgmt',
  93. TRIPAL_ERROR,
  94. 'Unable to create instance due to missing :key',
  95. [':key' => $key]
  96. );
  97. return FALSE;
  98. }
  99. }
  100. // If they are all present, then insert into the database.
  101. return db_insert('tripal_jbrowse_mgmt_instances')->fields([
  102. 'uid' => $user->uid,
  103. 'organism_id' => $data['organism_id'],
  104. 'analysis_id' => $data['analysis_id'],
  105. 'title' => $data['title'],
  106. 'description' => isset($data['description']) ? $data['description'] : '',
  107. 'created_at' => $data['created_at'],
  108. 'file' => $data['file'],
  109. ])->execute();
  110. }
  111. /**
  112. * Get an instance by id.
  113. *
  114. * @param $instance_id
  115. *
  116. * @return mixed
  117. */
  118. function tripal_jbrowse_mgmt_get_instance($instance_id) {
  119. $instance = tripal_jbrowse_mgmt_get_instances(['id' => $instance_id]);
  120. return reset($instance);
  121. }
  122. /**
  123. * Update an instance.
  124. *
  125. * @param int $id
  126. * @param array $data
  127. *
  128. * @return \DatabaseStatementInterface
  129. */
  130. function tripal_jbrowse_mgmt_update_instance($id, $data) {
  131. return db_update('tripal_jbrowse_mgmt_instances')
  132. ->fields($data)
  133. ->condition('id', $id)
  134. ->execute();
  135. }
  136. /**
  137. * @param int|object $instance
  138. *
  139. * @return int
  140. * @throws \Exception
  141. */
  142. function tripal_jbrowse_mgmt_delete_instance($instance) {
  143. if (is_object($instance) && property_exists($instance, 'id')) {
  144. $id = $instance->id;
  145. }
  146. elseif (is_numeric($instance)) {
  147. $id = $instance;
  148. }
  149. else {
  150. throw new Exception('Unable to extract instance ID. Please provide a valid ID to delete the instance.');
  151. }
  152. return db_delete('tripal_jbrowse_mgmt_instances')
  153. ->condition('id', $id)
  154. ->execute();
  155. }
  156. /**
  157. * Create a new JBrowse track for a given instance.
  158. *
  159. * @param $data
  160. *
  161. * @return bool|int Track ID or FALSE if an error occurs.
  162. *
  163. * @throws \Exception
  164. */
  165. function tripal_jbrowse_mgmt_create_track($instance, $data) {
  166. global $user;
  167. return db_insert('tripal_jbrowse_mgmt_tracks')->fields([
  168. 'uid' => $user->uid,
  169. 'instance_id' => $instance->id,
  170. 'organism_id' => $instance->organism_id,
  171. 'label' => $data['label'],
  172. 'track_type' => $data['track_type'],
  173. 'file_type' => $data['file_type'],
  174. 'created_at' => $data['created_at'],
  175. 'file' => $data['file'],
  176. ])->execute();
  177. }
  178. /**
  179. * Delete a track by ID.
  180. *
  181. * @param $track_id
  182. *
  183. * @return int
  184. */
  185. function tripal_jbrowse_mgmt_delete_track($track_id) {
  186. return db_delete('tripal_jbrowse_mgmt_tracks')
  187. ->condition('id', $track_id)
  188. ->execute();
  189. }
  190. /**
  191. * Get attached tracks with users pre-loaded.
  192. *
  193. * @param $instance
  194. *
  195. * @return mixed
  196. */
  197. function tripal_jbrowse_mgmt_get_tracks($instance, array $conditions = []) {
  198. static $users = [];
  199. $tracks = db_select('tripal_jbrowse_mgmt_tracks', 'HJT')->fields('HJT');
  200. foreach ($conditions as $field => $value) {
  201. $tracks->condition($field, $value);
  202. }
  203. $tracks = $tracks->condition('instance_id', $instance->id)
  204. ->execute()
  205. ->fetchAll();
  206. foreach ($tracks as &$track) {
  207. if (!isset($users[$track->uid])) {
  208. $users[$track->uid] = user_load($track->uid);
  209. }
  210. $track->user = $users[$track->uid];
  211. }
  212. return $tracks;
  213. }
  214. /**
  215. * Get a track with instance and user data attached.
  216. *
  217. * @param $track_id
  218. *
  219. * @return mixed
  220. */
  221. function tripal_jbrowse_mgmt_get_track($track_id) {
  222. $track = db_select('tripal_jbrowse_mgmt_tracks', 'HJT')
  223. ->fields('HJT')
  224. ->condition('id', $track_id)
  225. ->execute()
  226. ->fetchObject();
  227. $track->user = user_load($track->uid);
  228. $track->instance = tripal_jbrowse_mgmt_get_instance($track->instance_id);
  229. return $track;
  230. }
  231. /**
  232. * @param $track
  233. * @param array $fields
  234. *
  235. * @return \DatabaseStatementInterface
  236. */
  237. function tripal_jbrowse_mgmt_update_track($track, array $fields) {
  238. return db_update('tripal_jbrowse_mgmt_tracks')
  239. ->fields($fields)
  240. ->condition('id', $track->id)
  241. ->execute();
  242. }
  243. /**
  244. * Get a list of organisms.
  245. *
  246. * @return mixed
  247. */
  248. function tripal_jbrowse_mgmt_get_organisms_list() {
  249. return db_select('chado.organism', 'CO')
  250. ->fields('CO', ['organism_id', 'genus', 'species', 'common_name'])
  251. ->execute()
  252. ->fetchAll();
  253. }
  254. /**
  255. * parse analysis to obtain analysis_id
  256. *
  257. * @return mixed
  258. */
  259. function tripal_jbrowse_mgmt_analysis_parse_4id($name_id) {
  260. return $analysis_id;
  261. }
  262. /**
  263. * Format the name of the organism to `Genus species (Common Name)`.
  264. *
  265. * @param object $organism
  266. * The organism object as retrieved by
  267. * db_query()->fetchObject().
  268. *
  269. * @return string
  270. */
  271. function tripal_jbrowse_mgmt_construct_organism_name($organism) {
  272. $name = $organism->genus;
  273. $name .= " $organism->species";
  274. if (!empty($organism->common_name)) {
  275. $name .= " ($organism->common_name)";
  276. }
  277. return $name;
  278. }
  279. /**
  280. * Sanitize the string for the URL.
  281. *
  282. * @param string $string
  283. * The string to sanitize.
  284. *
  285. * @return string
  286. * The sanitized string.
  287. */
  288. function tripal_jbrowse_mgmt_make_slug($string) {
  289. $slug = str_replace(' ', '_', $string);
  290. $slug = str_replace('(', '_', $slug);
  291. $slug = str_replace(')', '_', $slug);
  292. $slug = str_replace('[', '_', $slug);
  293. $slug = str_replace(']', '_', $slug);
  294. $slug = str_replace('!', '_', $slug);
  295. $slug = str_replace('?', '_', $slug);
  296. $slug = str_replace('"', '_', $slug);
  297. $slug = str_replace('\'', '_', $slug);
  298. $slug = str_replace('\\', '_', $slug);
  299. $slug = str_replace(':', '_', $slug);
  300. return strtolower(trim($slug, '_'));
  301. }
  302. /**
  303. * @param $field
  304. *
  305. * @return bool|\stdClass
  306. */
  307. function tripal_jbrowse_mgmt_upload_file($field) {
  308. $file = file_save_upload($field, [
  309. 'file_validate_extensions' => ['fasta faa fna fastq txt gff vcf wig gz tbi bw'],
  310. // Make it 20 GB max.
  311. 'file_validate_size' => [1024 * 1024 * 1024 * 20],
  312. ]);
  313. // drupal_realpath($file->uri);.
  314. return !$file ? FALSE : $file;
  315. }
  316. /**
  317. * Moves a file to an intermediate directory, then to the destination, if given.
  318. *
  319. * @param $file
  320. * The file object.
  321. *
  322. * @param $path
  323. * The path to the directory of the new object.
  324. * If the directory provided does not exist, it will be created.
  325. *
  326. * @return
  327. * The path to the moved file, or NULL on fail.
  328. */
  329. function tripal_jbrowse_mgmt_move_file($file, $path = NULL) {
  330. $directory = 'public://tripal/tripal_jbrowse_mgmt';
  331. file_prepare_directory($directory, FILE_CREATE_DIRECTORY);
  332. $file = file_move($file, $directory, FILE_EXISTS_REPLACE);
  333. if (isset($path)) {
  334. file_prepare_directory($path, FILE_CREATE_DIRECTORY);
  335. $oldname = drupal_realpath($file->uri);
  336. $newname = $path . '/' . $file->filename;
  337. if (!rename($oldname, $newname)) {
  338. return NULL;
  339. }
  340. }
  341. return isset($path) ? $newname : drupal_realpath($file->uri);
  342. }
  343. /**
  344. * Copy a file into a new directory.
  345. * If the directory provided does not exist, it will be created.
  346. *
  347. * @param $source
  348. * File path of the source file.
  349. * @param $destination
  350. * File path to the destination directory.
  351. * @param $symbolic_link
  352. * bool indicates create symbolic_link or copy
  353. * @return bool
  354. */
  355. function tripal_jbrowse_mgmt_copy_file($source, $destination, $sym_link) {
  356. if (empty($destination)) {
  357. throw new Exception('Please provide a valid destination path to copy the source to.');
  358. }
  359. file_prepare_directory($destination, FILE_CREATE_DIRECTORY);
  360. if (isset($sym_link) AND ($sym_link == true)){
  361. $destination_symlink = $destination.'/'.basename($source);
  362. return symlink($source, $destination_symlink);
  363. }
  364. else{
  365. return file_unmanaged_copy($source, $destination, FILE_EXISTS_ERROR);
  366. }
  367. }
  368. /**
  369. * Build the http query for a given instance to link to JBrowse.
  370. *
  371. * @param $instance
  372. *
  373. * @return array
  374. */
  375. function tripal_jbrowse_mgmt_build_http_query($instance) {
  376. $path = tripal_jbrowse_mgmt_make_slug($instance->title);
  377. if(isset($instance->analysis_id)){
  378. $path = $path . '_' . $instance->analysis_id;
  379. }
  380. $added_tracks = tripal_jbrowse_mgmt_get_tracks($instance);
  381. $properties = tripal_jbrowse_mgmt_get_instance_properties($instance->id);
  382. // Determine the tracks to display.
  383. $tracks_path = '';
  384. // If the start-tracks property is set then use that directly.
  385. if (isset($properties['start-tracks'])) {
  386. $tracks_path = $properties['start-tracks'];
  387. }
  388. // Otherwise, show all tracks that were added using this module.
  389. elseif (!empty($added_tracks)) {
  390. $tracks_path = implode(',', array_map(function ($track) {
  391. return tripal_jbrowse_mgmt_make_slug($track->label);
  392. }, $added_tracks));
  393. }
  394. $settings = tripal_jbrowse_mgmt_get_settings();
  395. $data_path = (empty($settings['data_path'])) ? 'data' : '/' . $settings['data_path'];
  396. return [
  397. 'data' => "$data_path/$path/data",
  398. 'tracks' => $tracks_path,
  399. ];
  400. // Now we need to add start location if it's set.
  401. if (isset($properties['start-loc'])) {
  402. $query_params['loc'] = $properties['start-loc'];
  403. }
  404. return $query_params;
  405. }
  406. /**
  407. * Get trackList.json for an instance.
  408. *
  409. * @param object $instance
  410. *
  411. * @return array Decoded json array.
  412. *
  413. * @throws \Exception
  414. */
  415. function tripal_jbrowse_mgmt_get_json($instance) {
  416. $path = tripal_jbrowse_mgmt_get_track_list_file_path($instance);
  417. $contents = file_get_contents($path);
  418. if (!$contents) {
  419. throw new Exception('Unable to find ' . $path . ' file');
  420. }
  421. return json_decode($contents, TRUE);
  422. }
  423. /**
  424. * Get the json for a given track.
  425. *
  426. * @param object $track
  427. * The track from the database.
  428. *
  429. * @return array
  430. * @throws \Exception
  431. */
  432. function tripal_jbrowse_mgmt_get_track_json($track) {
  433. if (!$track->instance) {
  434. $track->instance = tripal_jbrowse_mgmt_get_instance($track->instance_id);
  435. }
  436. $json = tripal_jbrowse_mgmt_get_json($track->instance);
  437. $key = tripal_jbrowse_mgmt_make_slug($track->label);
  438. $track_json = NULL;
  439. foreach ($json['tracks'] as $index => $jtrack) {
  440. if ($jtrack['label'] === $key) {
  441. $track_json = $jtrack;
  442. break;
  443. }
  444. }
  445. return $track_json;
  446. }
  447. /**
  448. * @param object $track
  449. * Track object.
  450. * @param array $track_json
  451. * Edited track array.
  452. *
  453. * @throws \Exception
  454. */
  455. function tripal_jbrowse_mgmt_save_track_json($track, $track_json) {
  456. if (!$track->instance) {
  457. $track->instance = tripal_jbrowse_mgmt_get_instance($track->instance_id);
  458. }
  459. $json = tripal_jbrowse_mgmt_get_json($track->instance);
  460. $key = tripal_jbrowse_mgmt_make_slug($track->label);
  461. foreach ($json['tracks'] as $index => $jtrack) {
  462. if ($jtrack['label'] === $key) {
  463. $json['tracks'][$index] = $track_json;
  464. break;
  465. }
  466. }
  467. return tripal_jbrowse_mgmt_save_json($track->instance, $json);
  468. }
  469. /**
  470. * @param object $instance
  471. * @param array $data
  472. *
  473. * @throws \Exception
  474. * @return bool|int
  475. */
  476. function tripal_jbrowse_mgmt_save_json($instance, $data) {
  477. $path = tripal_jbrowse_mgmt_get_track_list_file_path($instance);
  478. $default = tripal_jbrowse_mgmt_get_json($instance);
  479. $json = $data + $default;
  480. $encoded = json_encode($json, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES);
  481. return file_put_contents($path, $encoded);
  482. }
  483. /**
  484. * @param $instance
  485. *
  486. * @return string
  487. */
  488. function tripal_jbrowse_mgmt_get_track_list_file_path($instance) {
  489. $settings = tripal_jbrowse_mgmt_get_settings();
  490. $path = $settings['data_dir'];
  491. $path .= '/' . tripal_jbrowse_mgmt_make_slug($instance->title);
  492. if(isset($instance->analysis_id)){
  493. $path = $path . '_' . $instance->analysis_id;
  494. }
  495. $path .= '/data/trackList.json';
  496. return $path;
  497. }
  498. /**
  499. * Gets a list of supported track types.
  500. *
  501. * @return array
  502. */
  503. function tripal_jbrowse_mgmt_get_track_types() {
  504. return [
  505. 'FeatureTrack',
  506. 'CanvasFeatures',
  507. 'HTMLFeatures',
  508. 'HTMLVariants',
  509. 'XYPlot',
  510. ];
  511. }
  512. /**
  513. * Save properties for a given instance.
  514. *
  515. * @param $id
  516. * The instance ID that properties should be associated with.
  517. * @param $data
  518. * An array of properties where each is
  519. * key: property_type, value: property value.
  520. */
  521. function tripal_jbrowse_mgmt_save_instance_properties($id, $data) {
  522. // For each property...
  523. foreach ($data as $type => $value) {
  524. tripal_jbrowse_mgmt_save_instance_property($id, $type, $value);
  525. }
  526. }
  527. /**
  528. * Save the details for a specific property of a given instance.
  529. *
  530. * @param $id
  531. * The instance ID that properties should be associated with.
  532. * @param $type
  533. * The name of the property type to be saved.
  534. * @param $value
  535. * The value of the property to be saved.
  536. */
  537. function tripal_jbrowse_mgmt_save_instance_property($id, $type, $value) {
  538. // Check to see if the property already exists.
  539. $result = db_select('tripal_jbrowse_mgmt_instanceprop', 'p')
  540. ->fields('p', ['value'])
  541. ->condition('instance_id', $id)
  542. ->condition('property_type', $type)
  543. ->execute()->fetchObject();
  544. // If the property doesn't already exist then insert it.
  545. if (empty($result)) {
  546. return db_insert('tripal_jbrowse_mgmt_instanceprop')
  547. ->fields([
  548. 'instance_id' => $id,
  549. 'property_type' => $type,
  550. 'value' => $value,
  551. ])->execute();
  552. }
  553. // Otherwise, we need to update it.
  554. else {
  555. return db_update('tripal_jbrowse_mgmt_instanceprop')
  556. ->fields([
  557. 'value' => $value,
  558. ])
  559. ->condition('instance_id', $id)
  560. ->condition('property_type', $type)
  561. ->execute();
  562. }
  563. }
  564. /**
  565. * Retrieves the value for a given instance property.
  566. *
  567. * @param $id
  568. * The instance ID.
  569. * @param $type
  570. * The name of the property type.
  571. * @return
  572. * The value of the property for a given instance.
  573. */
  574. function tripal_jbrowse_mgmt_get_instance_property($id, $type) {
  575. return db_select('tripal_jbrowse_mgmt_instanceprop', 'p')
  576. ->fields('p', ['value'])
  577. ->condition('instance_id', $id)
  578. ->condition('property_type', $type)
  579. ->execute()->fetchField();
  580. }
  581. /**
  582. * Retrieves all properties for a given instance.
  583. *
  584. * @param $id
  585. * The instance ID.
  586. * @return
  587. * An array of properties for the specified instance
  588. * where the key: property type and value: property value.
  589. */
  590. function tripal_jbrowse_mgmt_get_instance_properties($id) {
  591. return db_select('tripal_jbrowse_mgmt_instanceprop', 'p')
  592. ->fields('p', ['property_type', 'value'])
  593. ->condition('instance_id', $id)
  594. ->execute()->fetchAllKeyed(0,1);
  595. }