tripal_jbrowse_mgmt.api.inc 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660
  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. * @param $symbolic_link
  335. * bool indicates create symbolic_link or copy
  336. * @return bool
  337. */
  338. function tripal_jbrowse_mgmt_copy_file($source, $destination, $sym_link) {
  339. if (empty($destination)) {
  340. throw new Exception('Please provide a valid destination path to copy the source to.');
  341. }
  342. file_prepare_directory($destination, FILE_CREATE_DIRECTORY);
  343. if (isset($sym_link) AND ($sym_link == true)){
  344. $destination_symlink = $destination.'/'.basename($source);
  345. return symlink($source, $destination_symlink);
  346. }
  347. else{
  348. return file_unmanaged_copy($source, $destination, FILE_EXISTS_ERROR);
  349. }
  350. }
  351. /**
  352. * Build the http query for a given instance to link to JBrowse.
  353. *
  354. * @param $instance
  355. *
  356. * @return array
  357. */
  358. function tripal_jbrowse_mgmt_build_http_query($instance) {
  359. $path = tripal_jbrowse_mgmt_make_slug($instance->title);
  360. $added_tracks = tripal_jbrowse_mgmt_get_tracks($instance);
  361. $properties = tripal_jbrowse_mgmt_get_instance_properties($instance->id);
  362. // Determine the tracks to display.
  363. $tracks_path = '';
  364. // If the start-tracks property is set then use that directly.
  365. if (isset($properties['start-tracks'])) {
  366. $tracks_path = $properties['start-tracks'];
  367. }
  368. // Otherwise, show all tracks that were added using this module.
  369. elseif (!empty($added_tracks)) {
  370. $tracks_path = implode(',', array_map(function ($track) {
  371. return tripal_jbrowse_mgmt_make_slug($track->label);
  372. }, $added_tracks));
  373. }
  374. $settings = tripal_jbrowse_mgmt_get_settings();
  375. $data_path = (empty($settings['data_path'])) ? 'data' : '/' . $settings['data_path'];
  376. return [
  377. 'data' => "$data_path/$path/data",
  378. 'tracks' => $tracks_path,
  379. ];
  380. // Now we need to add start location if it's set.
  381. if (isset($properties['start-loc'])) {
  382. $query_params['loc'] = $properties['start-loc'];
  383. }
  384. return $query_params;
  385. }
  386. /**
  387. * Get trackList.json for an instance.
  388. *
  389. * @param object $instance
  390. *
  391. * @return array Decoded json array.
  392. *
  393. * @throws \Exception
  394. */
  395. function tripal_jbrowse_mgmt_get_json($instance) {
  396. $path = tripal_jbrowse_mgmt_get_track_list_file_path($instance);
  397. if (file_exists($path)) {
  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. else {
  405. return [];
  406. }
  407. }
  408. /**
  409. * Get the json for a given track.
  410. *
  411. * @param object $track
  412. * The track from the database.
  413. *
  414. * @return array
  415. * @throws \Exception
  416. */
  417. function tripal_jbrowse_mgmt_get_track_json($track) {
  418. if (!$track->instance) {
  419. $track->instance = tripal_jbrowse_mgmt_get_instance($track->instance_id);
  420. }
  421. $json = tripal_jbrowse_mgmt_get_json($track->instance);
  422. $key = tripal_jbrowse_mgmt_make_slug($track->label);
  423. $track_json = NULL;
  424. foreach ($json['tracks'] as $index => $jtrack) {
  425. if ($jtrack['label'] === $key) {
  426. $track_json = $jtrack;
  427. break;
  428. }
  429. }
  430. return $track_json;
  431. }
  432. /**
  433. * @param object $track
  434. * Track object.
  435. * @param array $track_json
  436. * Edited track array.
  437. *
  438. * @throws \Exception
  439. */
  440. function tripal_jbrowse_mgmt_save_track_json($track, $track_json) {
  441. if (!$track->instance) {
  442. $track->instance = tripal_jbrowse_mgmt_get_instance($track->instance_id);
  443. }
  444. $json = tripal_jbrowse_mgmt_get_json($track->instance);
  445. $key = tripal_jbrowse_mgmt_make_slug($track->label);
  446. foreach ($json['tracks'] as $index => $jtrack) {
  447. if ($jtrack['label'] === $key) {
  448. $json['tracks'][$index] = $track_json;
  449. break;
  450. }
  451. }
  452. return tripal_jbrowse_mgmt_save_json($track->instance, $json);
  453. }
  454. /**
  455. * @param object $instance
  456. * @param array $data
  457. *
  458. * @throws \Exception
  459. * @return bool|int
  460. */
  461. function tripal_jbrowse_mgmt_save_json($instance, $data) {
  462. $path = tripal_jbrowse_mgmt_get_track_list_file_path($instance);
  463. $default = tripal_jbrowse_mgmt_get_json($instance);
  464. $json = $data + $default;
  465. $encoded = json_encode($json, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES);
  466. return file_put_contents($path, $encoded);
  467. }
  468. /**
  469. * @param $instance
  470. *
  471. * @return string
  472. */
  473. function tripal_jbrowse_mgmt_get_track_list_file_path($instance) {
  474. $settings = tripal_jbrowse_mgmt_get_settings();
  475. $path = $settings['data_dir'];
  476. $path .= '/' . tripal_jbrowse_mgmt_make_slug($instance->title);
  477. $path .= '/data/trackList.json';
  478. return $path;
  479. }
  480. /**
  481. * Gets a list of supported track types.
  482. *
  483. * @return array
  484. */
  485. function tripal_jbrowse_mgmt_get_track_types() {
  486. return [
  487. 'FeatureTrack',
  488. 'CanvasFeatures',
  489. 'HTMLFeatures',
  490. 'HTMLVariants',
  491. 'XYPlot',
  492. ];
  493. }
  494. /**
  495. * Save properties for a given instance.
  496. *
  497. * @param $id
  498. * The instance ID that properties should be associated with.
  499. * @param $data
  500. * An array of properties where each is
  501. * key: property_type, value: property value.
  502. */
  503. function tripal_jbrowse_mgmt_save_instance_properties($id, $data) {
  504. // For each property...
  505. foreach ($data as $type => $value) {
  506. tripal_jbrowse_mgmt_save_instance_property($id, $type, $value);
  507. }
  508. }
  509. /**
  510. * Save the details for a specific property of a given instance.
  511. *
  512. * @param $id
  513. * The instance ID that properties should be associated with.
  514. * @param $type
  515. * The name of the property type to be saved.
  516. * @param $value
  517. * The value of the property to be saved.
  518. */
  519. function tripal_jbrowse_mgmt_save_instance_property($id, $type, $value) {
  520. // Check to see if the property already exists.
  521. $result = db_select('tripal_jbrowse_mgmt_instanceprop', 'p')
  522. ->fields('p', ['value'])
  523. ->condition('instance_id', $id)
  524. ->condition('property_type', $type)
  525. ->execute()->fetchObject();
  526. // If the property doesn't already exist then insert it.
  527. if (empty($result)) {
  528. return db_insert('tripal_jbrowse_mgmt_instanceprop')
  529. ->fields([
  530. 'instance_id' => $id,
  531. 'property_type' => $type,
  532. 'value' => $value,
  533. ])->execute();
  534. }
  535. // Otherwise, we need to update it.
  536. else {
  537. return db_update('tripal_jbrowse_mgmt_instanceprop')
  538. ->fields([
  539. 'value' => $value,
  540. ])
  541. ->condition('instance_id', $id)
  542. ->condition('property_type', $type)
  543. ->execute();
  544. }
  545. }
  546. /**
  547. * Retrieves the value for a given instance property.
  548. *
  549. * @param $id
  550. * The instance ID.
  551. * @param $type
  552. * The name of the property type.
  553. * @return
  554. * The value of the property for a given instance.
  555. */
  556. function tripal_jbrowse_mgmt_get_instance_property($id, $type) {
  557. return db_select('tripal_jbrowse_mgmt_instanceprop', 'p')
  558. ->fields('p', ['value'])
  559. ->condition('instance_id', $id)
  560. ->condition('property_type', $type)
  561. ->execute()->fetchField();
  562. }
  563. /**
  564. * Retrieves all properties for a given instance.
  565. *
  566. * @param $id
  567. * The instance ID.
  568. * @return
  569. * An array of properties for the specified instance
  570. * where the key: property type and value: property value.
  571. */
  572. function tripal_jbrowse_mgmt_get_instance_properties($id) {
  573. return db_select('tripal_jbrowse_mgmt_instanceprop', 'p')
  574. ->fields('p', ['property_type', 'value'])
  575. ->condition('instance_id', $id)
  576. ->execute()->fetchAllKeyed(0,1);
  577. }