tripal_jbrowse_mgmt.api.inc 15 KB

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