tripal_jbrowse_mgmt.api.inc 15 KB

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