tripal_jbrowse_mgmt.api.inc 15 KB

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