tripal_jbrowse_mgmt.api.inc 16 KB

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