blib/lib/Bio/Graphics/Browser2/UserTracks.pm untested

filter: Statementstmt 0.0% 0 / 615 Branchbran 0.0% 0 / 200 Conditioncond 0.0% 0 / 83 MC/DCmcdc n/a Subroutinesub 0.0% 0 / 112 Podpod 0.0% 0 / 92 totaltotal 0.0% 0 / 1102 CC 101 SCAR 55.1
CC
101
Cov
0%
_guess_upload_type
1260.0
mirror_url
272.0
upload_file
182.0
CRAP 245.9
1 package Bio::Graphics::Browser2::UserTracks;
2  
3 # $Id$
4 use strict;
5 use Bio::Graphics::Browser2::DataSource;
6 use Bio::Graphics::Browser2::DataLoader;
7 use Bio::Graphics::Browser2::UserTracks::Filesystem;
8 use Bio::Graphics::Browser2::UserTracks::Database;
9 use File::Spec;
10 use File::Basename 'basename';
11 use File::Path 'mkpath','rmtree';
12 use File::Copy 'move';
13 use IO::File;
14 use IO::String;
15 use File::Temp 'tempdir';
16 use POSIX ();
17 use Carp qw(croak cluck);
18 use CGI 'param';
19 use Data::Dumper;
20  
21 use constant DEBUG => 0;
22 my $HASBIGWIG;
23  
24 # The intent of this is to provide a single unified interface for
25 # managing a user's uploaded and shared tracks.
26  
27 # BUG: It's still kind of screwy: there seem to be filesystem
28 # traversal methods in the parent class which should not be here.
29  
30 # class methods
31 sub busy_file_name { 'BUSY' }
32 sub status_file_name { 'STATUS' }
33 sub imported_file_name { 'IMPORTED' }
34 sub mirrored_file_name { 'MIRRORED' }
35 sub sources_dir_name { 'SOURCES' }
36  
37 sub new {
38 my $class = shift;
39 my ($data_source,$session) = @_;
40  
41 my $globals = $data_source->globals;
42 my $uploadsid = $session->uploadsid;
43 my $backend = $globals->user_account_db;
44 my $user_accounts = $globals->user_accounts;
45
46 my $implementer;
47  
48 if ($backend && $backend =~ /db/i && $user_accounts) {
49 $implementer = 'Bio::Graphics::Browser2::UserTracks::Database';
50 } else {
51 $implementer = 'Bio::Graphics::Browser2::UserTracks::Filesystem';
52 }
53  
54 my $self = $implementer->_new($data_source, $globals, $uploadsid, $session);
55 $self->is_admin(1) if $class->admin;
56 $self->create_track_lookup;
57 return $self;
58 }
59  
60 sub _new {
61 my $class = shift;
62 my ($data_source, $globals, $uploadsid, $session) = @_;
63
64 my $self = bless {
65 config => $data_source,
66 uploadsid => $uploadsid,
67 globals => $globals,
68 session => $session,
69 data_source => $data_source->name,
70 }, ref $class || $class;
71 return $self;
72 }
73  
74 ##### CLASS METHOD #####
75 sub admin {0}
76 ########################
77  
78 sub uploadsid {shift->{uploadsid}}
79 sub session {shift->{session}}
80 sub sessionid {shift->session->id}
81 sub page_settings {
82 my $self = shift;
83 return $self->{'.page_settings'} ||= $self->session->page_settings;
84 }
85 sub database {
86 my $self = shift;
87 return $self->isa('Bio::Graphics::Browser2::UserTracks::Database');
88 }
89 sub globals {shift->{globals} }
90 sub data_source {shift->{config} }
91 sub datasource_name {shift->{data_source} }
92 sub is_admin {
93 my $self = shift;
94 my $d = $self->{is_admin};
95 $self->{is_admin} = shift if @_;
96 $d;
97 }
98  
99 # Tracks - Returns an array of paths to a user's tracks.
100 sub tracks {
101 my $self = shift;
102 my @tracks;
103 push @tracks, $self->get_uploaded_files, $self->get_imported_files;
104 push @tracks, $self->get_added_public_files, $self->get_shared_files;
105 return @tracks;
106 }
107  
108 # Track Lookup - Returns a hash of tracks showing the files they originate from.
109 sub track_lookup {
110 my $self = shift;
111 return %{$self->{track_lookup}};
112 }
113  
114 # Create Track Lookup - Populate the track lookup hash.
115 sub create_track_lookup {
116 my $self = shift;
117 my @tracks = $self->tracks;
118
119 my $track_lookup = {};
120 foreach my $track (@tracks) {
121 $track_lookup->{$_} = $track foreach $self->labels($track);
122 }
123
124 $self->{track_lookup} = $track_lookup;
125 }
126  
127 # Get Track Upload ID - Returns the upload ID of the original file the track came from.
128 sub get_track_upload_id {
129 my $self = shift;
130 my $track = shift;
131 my %track_lookup = $self->track_lookup;
132 return $track_lookup{$track};
133 }
134  
135 # Is Mirrored - Returns the URL if a specific file is mirrored.
136 sub is_mirrored {
137 my $self = shift;
138 my $file = shift;
139 my $filename = $self->filename($file);
140 my $mirror_flag = $self->mirror_flag($file);
141 return unless -e $mirror_flag;
142 open(my $i, $mirror_flag);
143 my $url = <$i>;
144 close $i;
145 return $url;
146 }
147  
148 # Set Mirrored - Sets the mirror flag.
149 sub set_mirrored {
150 my $self = shift;
151 my $file = shift;
152 my $filename = $self->filename($file);
153 my $url = shift;
154 my $flagfile = $self->mirror_flag($file);
155 open my $i,">", $flagfile or warn "can't open mirror file: $!";
156 print $i $url;
157 close $i;
158 }
159  
160 # Conf Files (File) - Returns the paths to all tracks' conf files.
161 sub conf_files {
162 my $self = shift;
163 my $file = shift;
164 return grep {-e $_} map { $self->track_conf($file) } $self->tracks;
165 }
166  
167 sub path {
168 my $self = shift;
169 my $uploadsid = $self->uploadsid;
170 my $source = $self->data_source;
171 my $path = $self->is_admin ? $source->admindata() : $source->userdata($uploadsid);
172 return $path;
173 }
174  
175 # Track Path (File) - Returns a verified path to the folder holding a track.
176 sub track_path {
177 my $self = shift;
178 my $track = shift;
179 my $filename = $self->filename($track);
180 if ($filename =~ m!/!) {
181 my ($uploadsid,$base) = split '/',$filename;
182 return File::Spec->catfile($self->data_source->userdata($uploadsid),$self->escape_url($base));
183 } else {
184 my $folder_name = $self->escape_url($filename);
185 return File::Spec->catfile($self->path($track), $folder_name);
186 }
187 }
188  
189 # Blind Track Path (Filename) - Blindly attaches the userdata path to whatever filename you give it.
190 sub blind_track_path {
191 my $self = shift;
192 my $filename = shift;
193 return File::Spec->catfile($self->path, $filename);
194 }
195  
196 # Data Path (File, Data File) - Returns the full path to a track's original data file.
197 sub data_path {
198 my $self = shift;
199 my $file = shift;
200 my $filename = $self->filename($file);
201 my $datafile = shift;
202 return File::Spec->catfile($self->track_path($file), $self->sources_dir_name, $datafile);
203 }
204  
205 # Track Conf (File) - Returns the full path to the track's configuration file.
206 sub track_conf {
207 my $self = shift;
208 my $file = shift;
209 my $filename = $self->filename($file);
210 my $conf_file = $self->escape_url($filename) . ".conf";
211 return File::Spec->catfile($self->track_path($file), $conf_file);
212 }
213  
214 # Conf FH (File) - Returns a file handle to a track's configuration file.
215 sub conf_fh {
216 my $self = shift;
217 my $file = shift;
218 my $filename = $self->filename($file);
219 return Bio::Graphics::Browser2::UserConf->fh($self->track_conf($file));
220 }
221  
222 # Import Flag (File) - Returns a track's import flag file.
223 sub import_flag {
224 my $self = shift;
225 my $file = shift;
226 my $filename = $self->filename($file);
227 return File::Spec->catfile($self->track_path($file), $self->imported_file_name);
228 }
229  
230 # Mirror Flag (File) - Returns the location of the mirror flag file.
231 sub mirror_flag {
232 my $self = shift;
233 my $file = shift;
234 my $filename = $self->filename($file);
235 return File::Spec->catfile($self->track_path($file), $self->mirrored_file_name);
236 }
237  
238 # Conf Metadata (File) - Returns the modified time and size of a track's configuration file.
239 sub conf_metadata {
240 my $self = shift;
241 my $file = shift;
242 my $filename = $self->filename($file);
243 my $conf = $self->track_conf($file);
244 my $name = basename($conf);
245 return ($name, (stat($conf))[9, 7]);
246 }
247  
248 # Source Files (File) - Returns an array of source files (with details) associated with a specified track.
249 sub source_files {
250 my $self = shift;
251 my $file = shift;
252 my $filename = $self->filename($file);
253 my $path = File::Spec->catfile($self->track_path($file), $self->sources_dir_name);
254
255 my @files;
256 if (opendir my $dir, $path) {
257 while (my $f = readdir($dir)) {
258 my $path = File::Spec->catfile($path, $f);
259 next unless -f $path;
260 my ($size, $mtime) = (stat(_))[7,9];
261 push @files, [$f, $size, $mtime, $path];
262 }
263 }
264 return @files;
265 }
266  
267 # Escape URL (URL[, Uniquefy]) - Gets an escaped name from a given URL.
268 sub escape_url {
269 my $self = shift;
270 my $url = shift;
271 my $uniquefy = shift;
272  
273 my $filename;
274  
275 # Remove any illegal chars
276 # hack here: if the URL looks like a "uploadid/filename", then we
277 # leave the slash there.
278 if ($url =~ m!^[a-f0-9]{32}/!) { # treat as a path to another userid
279 my ($dir,$rest) = split '/',$url;
280 $rest =~ tr/a-zA-Z0-9_%^@.-/_/cs;
281 $filename = $rest;
282 } else {
283 ($filename = $url) =~ tr/a-zA-Z0-9_%^@.-/_/cs;
284 }
285
286 # Cut the length at the maximum filename.
287 if (length $filename > $self->max_filename) {
288 $filename = substr($filename, 0, $self->max_filename);
289 }
290
291 # If the file isn't unique, add a number on the end.
292 my $unique = 0;
293 while ($uniquefy && !$unique) {
294 my $path = $self->blind_track_path($filename);
295 if (-e $path) {
296 $filename .= "-0" unless $filename =~ /-\d+$/;
297 $filename =~ s/-(\d+)$/'-'.($1+1)/e; # add +1 to the trackname
298 } else {
299 $unique++;
300 }
301 }
302 return $filename;
303 }
304  
305 # Trackname from URL (URL[, Uniquefy]) - Gets a track name from a given URL and creates the folder to hold it.
306 sub trackname_from_url {
307 my $self = shift;
308 my $url = shift;
309 my $uniquefy = shift;
310  
311 warn "trackname_from_url($url)" if DEBUG;
312
313 my $filename = $self->escape_url($url, $uniquefy);
314 my $path = $self->blind_track_path($filename);
315
316 rmtree($path) if -e $path; # only happens if uniquefy = 0
317 mkpath $path;
318 return $filename;
319 }
320  
321 # Max filename () - Returns the maximum possible length for a file name.
322 sub max_filename {
323 my $self = shift;
324 my $length = POSIX::pathconf($self->path, &POSIX::_PC_NAME_MAX) || 255;
325 return $length - 4; # give enough room for the suffix
326 }
327  
328 # Import URL (URL, Overwrite[, Privacy Policy]) - Imports a URL for use in the database.
329 sub import_url {
330 my $self = shift;
331 my $url = shift;
332 my $overwrite = shift;
333 my $privacy_policy = shift || "private";
334 my $username = $self->{username};
335  
336 my $key;
337 if ($url =~ m!http://([^/]+).+/(\w+)/\?.*t=([^+;]+)!) {
338 my @tracks = split /\+/,$3;
339 $key = "Shared track from $1 (@tracks)";
340 } else {
341 $key = "Shared track from $url";
342 }
343  
344 my $filename = $self->trackname_from_url($url, !$overwrite);
345 my $file = $self->add_file($filename, 1);
346
347 my $loader = Bio::Graphics::Browser2::DataLoader->new($filename,
348 $self->track_path($file),
349 $self->track_conf($file),
350 $self->{config},
351 $self->uploadsid);
352 $loader->strip_prefix($self->{config}->seqid_prefix);
353 $loader->set_status('starting import');
354  
355 my $conf = $self->track_conf($file);
356 open (my $f, "+>", $conf) or croak "Couldn't open $conf: $!";
357 my @data = $f;
358  
359 if ($url =~ /\.bam$/) {
360 print $f $self->remote_bam_conf($file, $url, $key);
361 }
362 elsif ($url =~ /\.bw$/) {
363 print $f $self->remote_bigwig_conf($file, $url, $key);
364 }
365 elsif ($url =~ /\.bb$/) {
366 print $f $self->remote_bigbed_conf($file, $url, $key);
367 }
368 else {
369 print $f $self->remote_mirror_conf($file, $url, $key);# Conf Metadata (File) - Returns the modified time and size of a track's configuration file.
370 }
371  
372 close $f;
373 open my $i, ">", $self->import_flag($file);
374 close $i;
375  
376 $loader->set_processing_complete;
377
378 return (1, '', [$filename], $file);
379 }
380  
381 # Reload File (File) - Attempts to reload a file into the database.
382 sub reload_file {
383 my $self = shift;
384 my $file = shift;
385 my $filename = $self->filename($file);
386 my @sources = $self->source_files($file);
387 for my $s (@sources) {
388 my ($name, $size, $mtime, $path) = @$s;
389 rename $path, "$path.bak" or next;
390 my $io = IO::File->new("$path.bak") or next;
391 my ($result) = $self->upload_file($name, $io,'',1);
392 if ($result) {
393 unlink "$path.bak";
394 } else {
395 rename "$path.bak", $path;
396 }
397 }
398 }
399  
400 # Mirror URL (Filename, URL, Overwrite?) - Attempts to "mirror" a file on a URL, to avoid fetching it every time.
401 sub mirror_url {
402 my $self = shift;
403 my ($filename,$url,$overwrite,$render) = @_;
404
405 warn "mirroring..." if DEBUG;
406  
407 if ($url =~ /\.(bam|bw|bb)$/ or $url =~ /\b(gbgff|das)\b/) {
408 return $self->import_url($url, $overwrite);
409 }
410  
411 # first we do a HEAD to validate that the thing exists
412 eval "require LWP::UserAgent" unless LWP::UserAgent->can('new');
413 my $agent = LWP::UserAgent->new();
414 my $result = $agent->head($url);
415 unless ($result->is_success) {
416 my $msg = $url.': '.$result->status_line;
417 warn $msg if DEBUG;
418 return (0,$msg,[]);
419 }
420  
421 # fetch in one process, process in another
422 eval "use IO::Pipe" unless IO::Pipe->can('new');
423 my $fh = IO::Pipe->new;
424 my $child = $render->fork();
425 die "Couldn't fork" unless defined $child;
426  
427 unless ($child) {
428 warn "printing from child..." if DEBUG;
429 $fh->writer();
430 $self->_print_url($agent, $url, $fh);
431 CORE::exit 0;
432 }
433 $fh->reader;
434  
435 $filename = $self->trackname_from_url($filename, !$overwrite);
436
437 my $content_type = $result->header('Content-Type') || 'text/plain';
438  
439 if ($content_type eq 'application/gzip' or $filename =~ /\.gz$/) {
440 $fh = $self->install_filter($fh,'gunzip -c');
441 } elsif ($content_type eq 'application/bzip2' or $filename =~ /\.bz2$/) {
442 $fh = $self->install_filter($fh,'bunzip2 -c');
443 }
444
445 my $file = $self->add_file($filename, 1);
446
447 # guess the file type from the first non-blank line
448 my ($type, $lines, $eol) = $self->guess_upload_type($file, $fh);
449 $lines ||= [];
450 my (@tracks, $fcgi);
451  
452 my $mirror_result = eval {
453 local $SIG{TERM} = sub { die "cancelled" };
454 croak "Could not guess the type of the file $filename" unless $type;
455  
456 my $load = $self->get_loader($type, $file);
457 $load->eol_char($eol);
458 @tracks = $load->load($lines, $fh);
459 1;
460 };
461  
462 if ($@ =~ /cancelled/) {
463 $self->delete_file($file);
464 return (0,'Upload process terminated',[]);
465 }
466  
467 my $msg = $@;
468 warn "UPLOAD ERROR: ", $msg if $msg;
469 $self->delete_file($file) unless $mirror_result;
470 $self->set_mirrored($file, $url);
471 return ($mirror_result, $msg, \@tracks);
472 }
473  
474 # Upload Data (Filename, Data, Content Type, Overwrite?) - Uploads a string of data entered as text (on the Upload & Share Tracks tab).
475 sub upload_data {
476 my $self = shift;
477 my ($file_name, $data, $content_type, $overwrite) = @_;
478 my $io = IO::String->new($data);
479 $self->upload_file($file_name, $io, $content_type, $overwrite);
480 }
481  
482 # Upload URL (URL) - Uploads a file at a specified URL to the database.
483 sub upload_url {
484 my $self = shift;
485 my $url = shift;
486 my $dir = tempdir(CLEANUP=>1);
487 my $path = File::Spec->catfile($dir, basename($url));
488 eval "require LWP::UserAgent" unless LWP::UserAgent->can('new');
489 my $agent = LWP::UserAgent->new();
490 my $response = $agent->mirror($url, $path);
491 $response->is_success or die $response->status_line;
492 my $mime = $response->header('Content-type');
493 open my $fh,"<",$path;
494 my @args = $self->upload_file(basename($url),$fh,$mime,1);
495 unlink $path;
496 File::Temp::cleanup();
497 return @args;
498 }
499  
500 # Upload File (Filename, File Handle, Content Type, Overwrite?) - Uploads a user's file, as called by the AJAX upload system (on the Upload & Share Tracks tab) via Action.pm.
501 sub upload_file {
502 my $self = shift;
503 my ($file_name, $fh, $content_type, $overwrite) = @_;
504  
505 my $original_name = $file_name;
506 $file_name =~ s/\.(gz|bz2)$//; # to indicate that it is decompressed
507 $file_name =~ s/\.(tgz|tbz|tbz2)$/.tar/; # change archive extension
508  
509 warn "$file_name: OVERWRITE = $overwrite" if DEBUG;
510  
511 my $filename = $self->trackname_from_url($file_name, !$overwrite);
512
513 $content_type ||= '';
514
515 if ($original_name =~ /\.sam\.gz/) { # special case compressed sam files - do not uncompress!
516 # $filename = $original_name;
517 } elsif ($content_type eq 'application/gzip' or $original_name =~ /\.(?:tgz|gz)$/) {
518 $fh = $self->install_filter($fh,'gunzip -c');
519 } elsif ($content_type eq 'application/bzip2' or $original_name =~ /\.(?:tbz2?|bz2)$/) {
520 $fh = $self->install_filter($fh,'bunzip2 -c');
521 }
522
523 my $fileid = $self->get_file_id($filename) if $self->database;
524 my $file = $self->database ? $fileid ? $fileid : $self->add_file($filename) : $filename;
525
526 # guess the file type from the first non-blank line
527 my ($type, $lines, $eol) = $self->guess_upload_type($file, $fh);
528 $lines ||= [];
529 my (@tracks, $fcgi);
530  
531 my $result = eval {
532 local $SIG{TERM} = sub { die "cancelled" };
533 croak "Could not guess the type of the file $file_name" unless $type;
534 croak "This server does not support $type uploads"
535 if $type =~ /bigwig|bigbed|useq|archive/ && !$self->has_bigwig;
536 my $load = $self->get_loader($type, $file);
537 $load->eol_char($eol);
538 @tracks = $load->load($lines, $fh);
539 1;
540 };
541  
542 if ($@ =~ /cancelled/) {
543 $self->delete_file($file);
544 return (0,'Cancelled by user',[]);
545 }
546  
547 my $msg = $@;
548 warn "UPLOAD ERROR: ", $msg if $msg;
549 if ($result) {
550 $self->title($file,$filename);
551 } else {
552 $self->delete_file($file);
553 }
554 return ($result, $msg, \@tracks);
555 }
556  
557 # set title of upload- implemented in subclasses
558 sub title { }
559  
560 # set the key of a labeled track - this involves rewriting the track config
561 sub set_key {
562 my $self = shift;
563 my ($file,$label,$new_key) = @_;
564 my $old_path = $self->track_conf($file);
565 my $new_path = "$old_path.bak";
566 open my $in,$old_path or croak "$old_path: $!";
567 open my $out,'>',$new_path or croak "$new_path: $!";
568 my $in_stanza;
569 while (<$in>) {
570 $in_stanza = undef if /^\[.+\]/;
571 $in_stanza ||= /^\[$label\]/;
572 next unless $in_stanza;
573 $_ = "key = $new_key\n" if /^key/;
574 } continue {
575 print $out $_;
576 }
577 close $in; close $out;
578 rename $new_path,$old_path;
579 return $new_key; # in case we want to change it later
580 }
581  
582 # Merge Conf (File, New Data) - Merges new data into a track's configuration file.
583 sub merge_conf {
584 my $self = shift;
585 my $file = shift;
586 my $filename = $self->filename($file);
587 my $new_data = shift;
588  
589 my $path = $self->track_conf($file) or return;
590  
591 my @lines = split /\r\n|\r|\n/,$new_data;
592 my (%stanzas, $current_stanza);
593 for (@lines) {
594 if (/^\[(.+)\]/) {
595 $current_stanza = $1;
596 $stanzas{$current_stanza} = '';
597 } elsif ($current_stanza) {
598 $stanzas{$current_stanza} .= "$_\n";
599 }
600 }
601  
602 open my $fh, $path or croak "$path: $!";
603 my $merged = '';
604 my @database;
605 # read header with the [database] definition
606 while (<$fh>) {
607 $merged .= $_;
608 push @database,$1 if /^\[(.+):database/;
609 last if /cut here/;
610 }
611  
612 $merged .= "\n";
613  
614 # read the rest
615 while (<$fh>) {
616 if (/^\[/) {
617 (my $stanza = $_) =~ s/\[(\w+?)_.+_(\d+)(:\d+)?\]\s*\n/$1_$2$3/;
618 $stanza =~ s/^\[//; # just in case
619 $stanza =~ s/\]\n//;
620 if (my $body = $stanzas{$stanza}) {
621 $merged .= $_;
622 $merged .= $body;
623 delete $stanzas{$stanza};
624 }
625 }
626 }
627  
628 # anything that's left (new stuff)
629 for my $stanza (keys %stanzas) {
630 $merged .= "\n[$stanza]\n";
631 $merged .= $stanzas{$stanza};
632 }
633  
634 $merged =~ s/database_(\d+).+/$database[$1]/g;
635  
636 open $fh,'>',$path or croak "Can't open $path for writing: $!";
637 print $fh $merged;
638 close $fh;
639 }
640  
641 #Labels (File) - Returns the track labels for a specified uploaded file.
642 sub labels {
643 my $self = shift;
644 my $file = shift;
645 my $conf = $self->track_conf($file);
646
647 return grep {!/:(database|\d+)/} eval{ Bio::Graphics::FeatureFile->new(-file=>$conf)->labels };
648 }
649  
650 sub file_from_label {
651 my $self = shift;
652 my $label = shift;
653 my %track_lookup = $self->track_lookup;
654 return $track_lookup{$label};
655 }
656  
657 # Status (File) - Returns the status of a DataLoader object for a specific file.
658 sub status {
659 my $self = shift;
660 my $file = shift;
661 my $filename = $self->filename($file);
662 my $loader = 'Bio::Graphics::Browser2::DataLoader';
663 my $load = $loader->new($filename,
664 $self->track_path($file),
665 $self->track_conf($file),
666 $self->{config},
667 $self->uploadsid,
668 );
669 return $load->get_status();
670 }
671  
672 # Get Loader (Type, File) - Returns the loader of the appropriate DataLoader package type for a specific file.
673 sub get_loader {
674 my $self = shift;
675 my $type = shift;
676 my $file = shift;
677 my $filename = $self->filename($file);
678
679 my $module = "Bio::Graphics::Browser2::DataLoader::$type";
680 eval "require $module";
681 die $@ if $@;
682
683 my $loader = $module->new($filename,
684 $self->track_path($file),
685 $self->track_conf($file),
686 $self->{config},
687 $self->uploadsid,
688 );
689 $loader->strip_prefix($self->{config}->seqid_prefix);
690 $loader->force_category('General') if $self->is_admin;
691 return $loader;
692 }
693  
694 # guess the file type and eol based on its name and the first 1024 bytes
695 # of the file. The @$lines will contain the lines that were consumed
696 # during this operation so that the info isn't lost.
697 sub guess_upload_type {
698 my $self = shift;
699 my ($type, $lines, $eol) = $self->_guess_upload_type(@_);
700 $type = 'wig2bigwig' if $type eq 'wiggle' && $self->has_bigwig;
701 return ($type, $lines, $eol);
702 }
703  
704 sub _guess_upload_type {
705 my $self = shift;
706 my $file = shift;
707 my $filename = $self->filename($file);
708 my $fh = shift;
709  
710 my $buffer;
711 read($fh,$buffer,1024);
712  
713 # first check for binary upload
714 my $magic = substr($buffer,0,4);
715 return ('bam',[$buffer],undef)
716 if $magic eq "\x1f\x8b\x08\x04";
717 return('bigwig',[$buffer],undef)
718 if $magic eq "\x26\xfc\x8f\x88";
719 return('bigbed',[$buffer],undef)
720 if $magic eq "\xeb\xf2\x89\x87";
721 if ($magic eq "\x50\x4B\x03\x04") { # zip file
722 return('useq', [$buffer], undef) if $filename =~ /\.useq$/i;
723 return('archive', [$buffer], undef) if $filename =~ /\.zip$/i;
724 }
725
726 # check for archives
727 return('archive', [$buffer], undef) if
728 $filename =~ /\.(?:tar|tgz|tbz|tbz2)(?:\.(gz|bz2))?$/i;
729
730 # everything else is text (for now)
731 my $eol = $buffer =~ /\015\012/ ? "\015\012" # MS-DOS
732 :$buffer =~ /\015/ ? "\015" # Macintosh
733 :$buffer =~ /\012/ ? "\012" # Unix
734 :"\012"; # default to Unix
735  
736 local $/ = $eol;
737 my @lines = map {$_.$eol} split $eol,$buffer;
738 $lines[-1] =~ s/$eol$// unless $buffer =~ /$eol$/;
739 my $remainder = <$fh>;
740 $remainder ||= '';
741 $lines[-1] .= $remainder;
742  
743 # first guess based on file names
744 my $ftype = $filename =~ /\.gff(\.(gz|bz2|Z))?$/i ? 'gff'
745 :$filename =~ /\.gff3(\.(gz|bz2|Z))?$/i ? 'gff3'
746 :$filename =~ /\.bed(\.(gz|bz2|Z))?$/i ? 'bed'
747 :$filename =~ /\.bw$/i ? 'bigwig'
748 :$filename =~ /\.bb$/i ? 'bigbed'
749 :$filename =~ /\.wig(\.(gz|bz2|Z))?$/i ? 'wiggle'
750 :$filename =~ /\.fff(\.(gz|bz2|Z))?$/i ? 'featurefile'
751 :$filename =~ /\.bam(\.gz)?$/i ? 'bam'
752 :$filename =~ /\.sam(\.gz)?$/i ? 'sam'
753 :$filename =~ /\.useq$/i ? 'useq'
754 :$filename =~ /\.(?:tar|tgz|tbz|tbz2|zip)(?:\.(gz|bz2))?$/i ? 'archive'
755 :undef;
756
757 return ($ftype,\@lines,$eol) if $ftype;
758  
759 # otherwise scan the thing until we find a pattern we know about
760 # or hit the end of the file. Extra lines that we read are
761 # accumulated into the @lines array.
762 my $i = 0;
763 while (1) {
764 my $line;
765 if ($i <= $#lines) {
766 $line = $lines[$i++];
767 } else {
768 my $line = <$fh>;
769 last unless $line;
770 push @lines,$line;
771 }
772 return ('featurefile',\@lines,$eol) if $line =~ /^reference/i;
773 return ('featurefile',\@lines,$eol) if $line =~ /\w+:\d+\.\.\d+/i;
774 return ('gff2',\@lines,$eol) if $line =~ /^\#\#gff-version\s+2/;
775 return ('gff3',\@lines,$eol) if $line =~ /^\#\#gff-version\s+3/;
776 return ('wiggle',\@lines,$eol) if $line =~ /type=wiggle/;
777 return ('bed',\@lines,$eol) if $line =~ /^track type/;
778 return ('bed',\@lines,$eol) if $line =~ /^\w+\s+\d+\s+\d+/;
779 return ('sam',\@lines,$eol) if $line =~ /^\@[A-Z]{2}/;
780 return ('sam',\@lines,$eol) if $line =~ /^[^ \t\n\r]+\t[0-9]+\t[^ \t\n\r@=]+\t[0-9]+\t[0-9]+\t(?:[0-9]+[MIDNSHP])+|\*/;
781 }
782 return;
783 }
784  
785 sub has_bigwig {
786 my $self = shift;
787 return $HASBIGWIG if defined $HASBIGWIG;
788 return $HASBIGWIG = 1 if Bio::DB::BigWig->can('new');
789 my $result = eval "require Bio::DB::BigWig; 1";
790 return $HASBIGWIG = $result || 0;
791 }
792  
793 # Install Filter (File Handle, Command) - Attaches a filter (such as GUNZIP or BUNZIP2) to a file handle.
794 sub install_filter {
795 my $self = shift;
796 my ($in_fh, $command) = @_;
797  
798 my $child = open(my $out_fh,"-|");
799 defined $child or die "Couldn't fork for pipe: $!";
800 return $out_fh if $child;
801  
802 # we are in child now
803 Bio::Graphics::Browser2::Render->prepare_fcgi_for_fork('child');
804 my $unzip = IO::File->new("| $command") or die "Can't open $command: $!";
805 my $buffer;
806 while ((my $bytes = read($in_fh,$buffer,8192))>0) {
807 $unzip->print($buffer);
808 }
809 close $unzip;
810 CORE::exit 0;
811 }
812  
813 sub remote_mirror_conf {
814 my $self = shift;
815 my $file = shift;
816 my $filename = $self->filename($file);
817 my ($url, $key) = @_;
818  
819 return <<END;
820 >>>>>>>>>>>>>> cut here <<<<<<<<<<<<
821 [$filename]
822 remote feature = $url
823 category = My Tracks:Remote Tracks
824 key = $key
825 END
826 ;
827 }
828  
829 sub remote_bam_conf {
830 my $self = shift;
831 my $file = shift;
832 my $filename = $self->filename($file);
833 my ($url, $key) = @_;
834  
835 my $id = rand(1000);
836 my $dbname = "remotebam_$id";
837 my $track_id = $filename;# . "_1";
838  
839 eval "require Bio::Graphics::Browser2::DataLoader::bam"
840 unless Bio::Graphics::Browser2::DataLoader::bam->can('new');
841 my $loader = Bio::Graphics::Browser2::DataLoader::bam->new(
842 $filename,
843 $self->track_path($file),
844 $self->track_conf($file),
845 $self->{config},
846 $self->uploadsid);
847 my $fasta = $loader->get_fasta_file;
848  
849 return <<END;
850 [$dbname:database]
851 db_adaptor = Bio::DB::Sam
852 db_args = -bam $url
853 -split_splices 1
854 -fasta $fasta
855 search options = none
856  
857 >>>>>>>>>>>>>> cut here <<<<<<<<<<<<
858  
859 [$track_id:2001]
860 feature = coverage:2000
861 min_score = 0
862 glyph = wiggle_xyplot
863 height = 50
864 fgcolor = black
865 bgcolor = black
866 autoscale = local
867  
868 [$track_id]
869 database = $dbname
870 feature = read_pair
871 glyph = segments
872 feature_limit = 500
873 draw_target = 1
874 show_mismatch = 1
875 mismatch_color = red
876 bgcolor = blue
877 fgcolor = blue
878 height = 3
879 label = 1
880 label density = 50
881 stranded = 1
882 bump = fast
883 key = $key
884 END
885 ;
886 }
887  
888 sub remote_bigwig_conf {
889 my $self = shift;
890 my $file = shift;
891 my $filename = $self->filename($file);
892 my ($url, $key) = @_;
893 my $id = rand(1000);
894 my $dbname = "remotebw_$id";
895 my $track_id = $filename;
896 warn "remote_bigwig_conf";
897 return <<END;
898 [$dbname:database]
899 db_adaptor = Bio::DB::BigWig
900 db_args = -bigwig $url
901 search options = none
902  
903 >>>>>>>>>>>>>> cut here <<<<<<<<<<<<
904 [$track_id]
905 database = $dbname
906 feature = summary
907 glyph = wiggle_whiskers
908 max_color = lightgrey
909 min_color = lightgrey
910 mean_color = black
911 stdev_color = grey
912 stdev_color_neg = grey
913 height = 20
914  
915 END
916 }
917  
918 sub remote_bigbed_conf {
919 my $self = shift;
920 my $file = shift;
921 my $filename = $self->filename($file);
922 my ($url, $key) = @_;
923 my $id = rand(1000);
924 my $dbname = "remotebb_$id";
925 my $track_id = $filename;
926 my @COLORS = qw(blue red orange brown mauve peach
927 green cyan yellow coral);
928 my $color = $COLORS[rand @COLORS];
929 warn "remote_bigbed_conf";
930 return <<END;
931 [$dbname:database]
932 db_adaptor = Bio::DB::BigBed
933 db_args = -bigbed $url
934 search options = none
935  
936 >>>>>>>>>>>>>> cut here <<<<<<<<<<<<
937 [$track_id]
938 database = $dbname
939 feature = region
940 glyph = segments
941 label density = 50
942 feature_limit = 500
943 bump = fast
944 stranded = 1
945 height = 4
946 bgcolor = $color
947 fgcolor = $color
948 key = $filename segments
949 description =
950  
951 [$track_id\_coverage]
952 database = $dbname
953 feature = summary
954 glyph = wiggle_whiskers
955 fgcolor = black
956 height = 50
957 autoscale = chromosome
958 key = $filename coverage
959 description =
960  
961 END
962 }
963  
964 sub _print_url {
965 my $self = shift;
966 my ($agent, $url, $fh) = @_;
967 $agent->get($url,':content_cb' => sub { print $fh shift; });
968 }
969  
970 # Sharing Link (File ID) - Generates the sharing link for a specific file.
971 sub sharing_link {
972 my $self = shift;
973 my $file = shift or return;
974 return CGI::url(-full => 1, -path_info => 1) . "?share_link=" . $file;
975 }
976  
977 # These methods are replaced by methods in Filesystem.pm and Database.pm
978 # Many of these functions are called asynchronously, if you want to connect an AJAX call to one of these functions add a hook in Action.pm
979 sub get_file_id { warn "get_file_id() has been called, without properly inheriting subclass Database.pm"; }
980 sub filename { warn "filename() has been called, without properly inheriting a subclass (like Filesystem.pm or Database.pm)"; }
981 sub nowfun { warn "nowfun() has been called, without properly inheriting subclass Database.pm"; }
982 sub get_uploaded_files { warn "get_uploaded_files() has been called, without properly inheriting a subclass (like Filesystem.pm or Database.pm)"; }
983 sub get_public_files { warn "get_public_files() has been called, without properly inheriting subclass Database.pm"; }
984 sub get_imported_files { warn "get_imported_files() has been called, without properly inheriting a subclass (like Filesystem.pm or Database.pm)"; }
985 sub get_shared_files { warn "get_shared_files() has been called, without properly inheriting subclass Database.pm"; }
986 sub share { warn "share() has been called, without properly inheriting subclass Database.pm"; }
987 sub unshare { warn "unshare() has been called, without properly inheriting subclass Database.pm"; }
988 sub field { warn "field() has been called, without properly inheriting subclass Database.pm"; }
989 sub update_modified { warn "update_modified() has been called, without properly inheriting subclass Database.pm"; }
990 sub created { warn "created() has been called, without properly inheriting a subclass (like Filesystem.pm or Database.pm)"; }
991 sub modified { warn "modified() has been called, without properly inheriting a subclass (like Filesystem.pm or Database.pm)"; }
992 sub description { warn "description() has been called, without properly inheriting a subclass (like Filesystem.pm or Database.pm)"; }
993 sub add_file { warn "add_file() has been called, without properly inheriting a subclass (like Filesystem.pm or Database.pm)"; }
994 sub delete_file { warn "delete_file() has been called, without properly inheriting a subclass (like Filesystem.pm or Database.pm)"; }
995 sub is_imported { warn "is_imported() has been called, without properly inheriting a subclass (like Filesystem.pm or Database.pm)"; }
996 sub permissions { warn "permissions() has been called, without properly inheriting subclass Database.pm"; }
997 sub is_mine { warn "is_mine() has been called, without properly inheriting a subclass (like Filesystem.pm or Database.pm)"; }
998 sub owner { warn "owner() has been called, without properly inheriting a subclass (like Filesystem.pm or Database.pm)"; }
999 sub is_shared_with_me { warn "is_shared_with_me() has been called, without properly inheriting subclass Database.pm"; }
1000 sub file_type { warn "file_type() has been called, without properly inheriting a subclass (like Filesystem.pm or Database.pm)"; }
1001 sub shared_with { warn "shared_with() has been called, without properly inheriting subclass Database.pm"; }
1002 sub file_exists { warn "file_exists() has been called, without properly inheriting subclass Filesystem.pm"; }
1003 sub change_userid { warn "change_userid() has been called, without properly inheriting a subclass (like Filesystem.pm or Database.pm)"; }
1004 sub change_uploadsid { warn "change_uploadsid() has been called, without properly inheriting a subclass (like Filesystem.pm or Database.pm)"; }
1005 sub close_database { } # do nothing
1006  
1007 package Bio::Graphics::Browser2::UserConf;
1008  
1009 use base 'Tie::Handle';
1010 use Symbol;
1011  
1012 sub fh {
1013 my $class = shift;
1014 my $path = shift;
1015 my $g = gensym;
1016 tie(*$g,$class,$path);
1017 return $g;
1018 }
1019  
1020 sub TIEHANDLE {
1021 my $class = shift;
1022 my $path = shift;
1023 open my $f,$path or die "$path:$!";
1024 return bless {
1025 fh => $f,
1026 seen_cut => 0,
1027 _db => {}, # remember db names
1028 -didx => 0, # db indexes
1029 },$class;
1030 }
1031  
1032 sub READLINE {
1033 my $self = shift;
1034 my $fh = $self->{fh};
1035  
1036 while (my $line = <$fh>) {
1037 $self->{_db}{$1} = $self->{_didx}++ if $line =~ /^\[(.+):database/;
1038 if ($line =~ /cut here/i) {
1039 $self->{seen_cut}++;
1040 next;
1041 }
1042 next unless $self->{seen_cut};
1043 $line =~ s/database\s*=\s*(.+)/database = database_$self->{_db}{$1} # do not change this!/;
1044 $line =~ s/\[(\w+?)_.+_(\d+)(:\d+)?\]/[$1_$2$3]/;
1045 return $line;
1046 }
1047 return;
1048 }
1049  
1050 sub CLOSE { close shift->{fh} }
1051  
1052 # this is for the administrator-uploaded tracks.
1053 # we simply change the location of the uploads
1054 package Bio::Graphics::Browser2::AdminTracks;
1055 use base 'Bio::Graphics::Browser2::UserTracks';
1056  
1057 sub admin {1}
1058  
1059 1;