tripal_jbrowse_mgmt.api.inc 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705
  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. if (file_exists($destination_symlink)){
  375. return TRUE;
  376. }else{
  377. return symlink($source, $destination_symlink);
  378. }
  379. }
  380. else{
  381. return file_unmanaged_copy($source, $destination, FILE_EXISTS_ERROR);
  382. }
  383. }
  384. /**
  385. * Build the http query for a given instance to link to JBrowse.
  386. *
  387. * @param $instance
  388. *
  389. * @return array
  390. */
  391. function tripal_jbrowse_mgmt_build_http_query($instance) {
  392. $path = tripal_jbrowse_mgmt_make_slug($instance->title);
  393. if(isset($instance->analysis_id)){
  394. $path = $path . '_' . $instance->analysis_id;
  395. }
  396. $added_tracks = tripal_jbrowse_mgmt_get_tracks($instance);
  397. $properties = tripal_jbrowse_mgmt_get_instance_properties($instance->id);
  398. // Determine the tracks to display.
  399. $tracks_path = '';
  400. // If the start-tracks property is set then use that directly.
  401. if (isset($properties['start-tracks'])) {
  402. $tracks_path = $properties['start-tracks'];
  403. }
  404. // Otherwise, show all tracks that were added using this module.
  405. elseif (!empty($added_tracks)) {
  406. $tracks_path = implode(',', array_map(function ($track) {
  407. return tripal_jbrowse_mgmt_make_slug($track->label);
  408. }, $added_tracks));
  409. }
  410. $settings = tripal_jbrowse_mgmt_get_settings();
  411. $data_path = (empty($settings['data_path'])) ? 'data' : '/' . $settings['data_path'];
  412. return [
  413. 'data' => "$data_path/$path/data",
  414. 'tracks' => $tracks_path,
  415. ];
  416. // Now we need to add start location if it's set.
  417. if (isset($properties['start-loc'])) {
  418. $query_params['loc'] = $properties['start-loc'];
  419. }
  420. return $query_params;
  421. }
  422. /**
  423. * Get trackList.json for an instance.
  424. *
  425. * @param object $instance
  426. *
  427. * @return array Decoded json array.
  428. *
  429. * @throws \Exception
  430. */
  431. function tripal_jbrowse_mgmt_get_json($instance) {
  432. $path = tripal_jbrowse_mgmt_get_track_list_file_path($instance);
  433. if (file_exists($path)) {
  434. $contents = file_get_contents($path);
  435. if (!$contents) {
  436. throw new Exception('Unable to find ' . $path . ' file');
  437. }
  438. return json_decode($contents, TRUE);
  439. }
  440. else {
  441. return [];
  442. }
  443. }
  444. /**
  445. * Get the json for a given track.
  446. *
  447. * @param object $track
  448. * The track from the database.
  449. *
  450. * @return array
  451. * @throws \Exception
  452. */
  453. function tripal_jbrowse_mgmt_get_track_json($track) {
  454. if (!$track->instance) {
  455. $track->instance = tripal_jbrowse_mgmt_get_instance($track->instance_id);
  456. }
  457. $json = tripal_jbrowse_mgmt_get_json($track->instance);
  458. $key = tripal_jbrowse_mgmt_make_slug($track->label);
  459. $track_json = NULL;
  460. foreach ($json['tracks'] as $index => $jtrack) {
  461. if ($jtrack['label'] === $key) {
  462. $track_json = $jtrack;
  463. break;
  464. }
  465. }
  466. return $track_json;
  467. }
  468. /**
  469. * @param object $track
  470. * Track object.
  471. * @param array $track_json
  472. * Edited track array.
  473. *
  474. * @throws \Exception
  475. */
  476. function tripal_jbrowse_mgmt_save_track_json($track, $track_json) {
  477. if (!$track->instance) {
  478. $track->instance = tripal_jbrowse_mgmt_get_instance($track->instance_id);
  479. }
  480. $json = tripal_jbrowse_mgmt_get_json($track->instance);
  481. $key = tripal_jbrowse_mgmt_make_slug($track->label);
  482. foreach ($json['tracks'] as $index => $jtrack) {
  483. if ($jtrack['label'] === $key) {
  484. $json['tracks'][$index] = $track_json;
  485. break;
  486. }
  487. }
  488. return tripal_jbrowse_mgmt_save_json($track->instance, $json);
  489. }
  490. /**
  491. * @param object $instance
  492. * @param array $data
  493. *
  494. * @throws \Exception
  495. * @return bool|int
  496. */
  497. function tripal_jbrowse_mgmt_save_json($instance, $data) {
  498. $path = tripal_jbrowse_mgmt_get_track_list_file_path($instance);
  499. $default = tripal_jbrowse_mgmt_get_json($instance);
  500. $json = $data + $default;
  501. $encoded = json_encode($json, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES);
  502. return file_put_contents($path, $encoded);
  503. }
  504. /**
  505. * @param $instance
  506. *
  507. * @return string
  508. */
  509. function tripal_jbrowse_mgmt_get_track_list_file_path($instance) {
  510. $settings = tripal_jbrowse_mgmt_get_settings();
  511. $path = $settings['data_dir'];
  512. $path .= '/' . tripal_jbrowse_mgmt_make_slug($instance->title);
  513. if(isset($instance->analysis_id)){
  514. $path = $path . '_' . $instance->analysis_id;
  515. }
  516. $path .= '/data/trackList.json';
  517. return $path;
  518. }
  519. /**
  520. * Gets a list of supported track types.
  521. *
  522. * @return array
  523. */
  524. function tripal_jbrowse_mgmt_get_track_types() {
  525. return [
  526. 'FeatureTrack',
  527. 'CanvasFeatures',
  528. 'HTMLFeatures',
  529. 'HTMLVariants',
  530. 'XYPlot',
  531. ];
  532. }
  533. /**
  534. * Save properties for a given instance.
  535. *
  536. * @param $id
  537. * The instance ID that properties should be associated with.
  538. * @param $data
  539. * An array of properties where each is
  540. * key: property_type, value: property value.
  541. */
  542. function tripal_jbrowse_mgmt_save_instance_properties($id, $data) {
  543. // For each property...
  544. foreach ($data as $type => $value) {
  545. tripal_jbrowse_mgmt_save_instance_property($id, $type, $value);
  546. }
  547. }
  548. /**
  549. * Save the details for a specific property of a given instance.
  550. *
  551. * @param $id
  552. * The instance ID that properties should be associated with.
  553. * @param $type
  554. * The name of the property type to be saved.
  555. * @param $value
  556. * The value of the property to be saved.
  557. */
  558. function tripal_jbrowse_mgmt_save_instance_property($id, $type, $value) {
  559. // Check to see if the property already exists.
  560. $result = db_select('tripal_jbrowse_mgmt_instanceprop', 'p')
  561. ->fields('p', ['value'])
  562. ->condition('instance_id', $id)
  563. ->condition('property_type', $type)
  564. ->execute()->fetchObject();
  565. // If the property doesn't already exist then insert it.
  566. if (empty($result)) {
  567. return db_insert('tripal_jbrowse_mgmt_instanceprop')
  568. ->fields([
  569. 'instance_id' => $id,
  570. 'property_type' => $type,
  571. 'value' => $value,
  572. ])->execute();
  573. }
  574. // Otherwise, we need to update it.
  575. else {
  576. return db_update('tripal_jbrowse_mgmt_instanceprop')
  577. ->fields([
  578. 'value' => $value,
  579. ])
  580. ->condition('instance_id', $id)
  581. ->condition('property_type', $type)
  582. ->execute();
  583. }
  584. }
  585. /**
  586. * Retrieves the value for a given instance property.
  587. *
  588. * @param $id
  589. * The instance ID.
  590. * @param $type
  591. * The name of the property type.
  592. * @return
  593. * The value of the property for a given instance.
  594. */
  595. function tripal_jbrowse_mgmt_get_instance_property($id, $type) {
  596. return db_select('tripal_jbrowse_mgmt_instanceprop', 'p')
  597. ->fields('p', ['value'])
  598. ->condition('instance_id', $id)
  599. ->condition('property_type', $type)
  600. ->execute()->fetchField();
  601. }
  602. /**
  603. * Retrieves all properties for a given instance.
  604. *
  605. * @param $id
  606. * The instance ID.
  607. * @return
  608. * An array of properties for the specified instance
  609. * where the key: property type and value: property value.
  610. */
  611. function tripal_jbrowse_mgmt_get_instance_properties($id) {
  612. return db_select('tripal_jbrowse_mgmt_instanceprop', 'p')
  613. ->fields('p', ['property_type', 'value'])
  614. ->condition('instance_id', $id)
  615. ->execute()->fetchAllKeyed(0,1);
  616. }