tripal_jbrowse_mgmt.api.inc 15 KB

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