tripal_jbrowse_mgmt.api.inc 16 KB

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