tripal_jbrowse_mgmt.api.inc 17 KB

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