blib/lib/Legacy/Graphics/Browser/Util.pm untested

filter: Statementstmt 0.0% 0 / 283 Branchbran 0.0% 0 / 126 Conditioncond 0.0% 0 / 82 MC/DCmcdc n/a Subroutinesub 0.0% 0 / 34 Podpod 0.0% 0 / 22 totaltotal 0.0% 0 / 547 CC 64 SCAR 38.1
CC
64
Cov
0%
parse_feature_str
156.0
print_top
90.0
open_database
56.0
CRAP 45.0
1 package Legacy::Graphics::Browser::Util;
2  
3 # a package of useful internal routines for GBrowse
4  
5 use strict;
6 use Legacy::Graphics::Browser;
7 use Legacy::Graphics::Browser::I18n;
8 use CGI qw(:standard);
9 use CGI::Toggle;
10 use Carp 'carp','cluck';
11 use Text::ParseWords ();
12  
13 use vars qw(@ISA @EXPORT $CONFIG $LANG %DB $HEADER $HTML $ADDED_FEATURES);
14 require Exporter;
15 @ISA = 'Exporter';
16 @EXPORT = qw(conf_dir open_config open_database
17 print_header print_top print_bottom html_frag
18 error fatal_error redirect_legacy_url
19 parse_feature_str url2file modperl_request is_safari
20 shellwords
21 );
22  
23 use constant DEBUG => 0;
24 use constant JS => '/gbrowse2/js';
25  
26 sub conf_dir {
27 my $default = shift;
28 if (my $request = modperl_request()) {
29 my $conf = $request->dir_config('GBrowseConf') or return $default;
30 return $conf if $conf =~ m!^/!; # return absolute
31 return (exists $ENV{MOD_PERL_API_VERSION} &&
32 $ENV{MOD_PERL_API_VERSION} >= 2)
33 ? Apache2::ServerUtil::server_root() . "/$conf"
34 : Apache->server_root_relative($conf);
35 }
36 return $default;
37 }
38  
39 sub url2file {
40 my $url = shift;
41 my $request = modperl_request();
42  
43 for my $l ((map {"$url.$_"} $CONFIG->language->language), $url) {
44 my $file = $request ? $request->lookup_uri($l)->filename
45 : "$ENV{DOCUMENT_ROOT}/$l";
46 return $file if -e $file;
47 }
48 return;
49 }
50  
51 sub modperl_request {
52 return unless $ENV{MOD_PERL};
53 (exists $ENV{MOD_PERL_API_VERSION} &&
54 $ENV{MOD_PERL_API_VERSION} >= 2 ) ? Apache2::RequestUtil->request
55 : Apache->request;
56 }
57  
58  
59 sub open_config {
60 my $dir = shift;
61 my $suffix = shift;
62 $CONFIG ||= Legacy::Graphics::Browser->new;
63 $CONFIG->read_configuration($dir,$suffix) or die "Can't read configuration files: $!";
64 $LANG ||= Legacy::Graphics::Browser::I18n->new("$dir/languages");
65 # $CONFIG->source or early_error($LANG,'NO_SOURCES');
66  
67 set_language($CONFIG,$LANG);
68 $CONFIG->language($LANG);
69 $CONFIG->dir($dir);
70  
71 # initialize some variables
72 $HEADER=0;
73 $HTML=0;
74 $ADDED_FEATURES = 0;
75  
76 $CONFIG;
77 }
78  
79 sub open_database {
80 my $config = shift || $CONFIG;
81 my $source = $config->source;
82 return $DB{$source} if $DB{$source};
83 my ($adaptor,@argv) = eval{$config->db_settings};
84 unless ($adaptor) {
85 warn "gbrowse: trying to reload config, cache must be stale";
86 my $dir = $config->dir;
87 $config = Legacy::Graphics::Browser->new;
88 $config->read_configuration($dir) or fatal_error("Can't read configuration files: $!");
89 $config->source($source);
90 ($adaptor,@argv) = $config->db_settings;
91 }
92  
93 ################################################
94 # HACK ALERT
95 patch_old_versions_of_bioperl($adaptor,@argv);
96 ################################################
97  
98 $DB{$source} = eval {$adaptor->new(@argv)} or warn $@;
99 fatal_error('Could not open database.',pre("$@")) unless $DB{$source};
100  
101 if (my $refclass = $config->setting('reference class')) {
102 eval {$DB{$source}->default_class($refclass)};
103 }
104  
105 $DB{$source}->strict_bounds_checking(1) if $DB{$source}->can('strict_bounds_checking');
106 $DB{$source}->absolute(1) if $DB{$source}->can('absolute');
107  
108 return $DB{$source};
109 }
110  
111 sub print_header {
112 print header(@_) unless $HEADER++;
113 }
114  
115 sub parse_added_feature {
116 my $f = shift;
117 my $fcount = shift;
118 my $zero = 0;
119 $fcount ||= \$zero;
120 my ($reference,$type,$name,@position);
121 my @args = shellwords($f||'');
122 if (@args > 3) {
123 ($reference,$type,$name,@position) = @args;
124 } elsif (@args > 2) {
125 ($reference,$name,@position) = @args;
126 $type = 'Your Features';
127 } elsif (@args > 1) {
128 ($reference,@position) = @args;
129 ($type,$name) = ('Your Features',"Feature ".++$$fcount);
130 }
131 my @segments = map { [/(-?\d+)(?:-|\.\.)(-?\d+)/]} map {split ','} @position;
132 ($reference,$type,$name,@segments);
133 }
134  
135 sub print_top {
136 my $title = shift;
137 my $reset_all = shift;
138 my $alert = shift;
139 local $^W = 0; # to avoid a warning from CGI.pm
140  
141 my $titlebar = is_safari() ? 'titlebar-safari.css' : 'titlebar-default.css';
142  
143 my @extra_headers;
144 my @stylesheets = shellwords($CONFIG->setting('stylesheet') || '/gbrowse2/css/gbrowse.css');
145 for my $ss (@stylesheets) {
146 my ($url,$media) = $ss =~ /^([^(]+)(?:\((.+)\))?/;
147 $media ||= 'all';
148 push @extra_headers,CGI::Link({-rel=>'stylesheet',
149 -type=>'text/css',
150 -href=>$CONFIG->relative_path($url),
151 -media=>$media});
152 }
153  
154 push @extra_headers,$CONFIG->setting('head') if $CONFIG->setting('head');
155  
156 print_header(-expires=>'now');
157 my @args = (-title => $title,
158 -style => [{src=>$CONFIG->relative_path('tracks.css')},
159 {src=>$CONFIG->relative_path($titlebar)}],
160 -encoding=>$CONFIG->tr('CHARSET'),
161 );
162 push @args,(-lang=>($CONFIG->language_code)[0]) if $CONFIG->language_code;
163 push @args,(-gbrowse_images => $CONFIG->globals->button_url || '/gbrowse2/images/buttons');
164 push @args,(-gbrowse_js => $CONFIG->globals->js_url || '/gbrowse2/js');
165 push @args,(-reset_toggle => 1) if $reset_all;
166  
167 my @onload;
168 push @onload, $CONFIG->setting('onload') if $CONFIG->setting('onload');
169 push @onload, "alert('$alert')" if $alert;
170  
171 # push all needed javascript files onto top of page
172 my $drag_and_drop = $CONFIG->drag_and_drop;
173 my $b_tips = $CONFIG->setting('balloon tips') || $drag_and_drop;
174 my $js = $CONFIG->relative_path_setting('js')||JS;
175 my @js = qw/buttons.js prototype.js balloon.config.js balloon.js rubber.js overviewSelect.js/;
176 push @onload, 'Overview.prototype.initialize()';
177 #push @onload, 'Details.prototype.initialize()';
178  
179 #if ($CONFIG->setting('region segment')) {
180 # push @js, 'regionSelect.js';
181 # push @onload, 'Region.prototype.initialize()';
182 #}
183  
184 my @scripts = map { {src=> "$js/$_" } } @js;
185 push @args, (-script => \@scripts);
186 push @args, (-onLoad => join('; ',@onload));
187 push @args, (-head => \@extra_headers);
188  
189 print start_html(@args) unless $HTML++;
190 print_balloon_settings() if $b_tips;
191 print_select_menu($_) for (qw/DETAIL OVERVIEW REGION/);
192 }
193  
194 # prepare custom menu(s) for rubber-band selection
195 sub print_select_menu {
196 my $view = shift || 'DETAIL';
197 my $config_label = uc($view).' SELECT MENU';
198  
199 # HTML for the custom menu is required
200 my $menu_html = $CONFIG->setting($config_label => 'HTML')
201 || $CONFIG->setting($config_label => 'html')
202 || return;
203  
204 # should not be visible
205 my %style = (display => 'none');
206 # optional style attributes
207 for my $att (qw/width font background background-color border/) {
208 my $val = $CONFIG->setting($config_label => $att) || next;
209 $style{$att} = $val;
210 }
211 $style{width} .= 'px';
212 my $style = join('; ', map {"$_:$style{$_}"} keys %style);
213  
214 # clean up the HTML just a bit
215 $menu_html =~ s/\</\n\</g;
216  
217 print div( { -style => $style,
218 -id => lc($view).'SelectMenu' },
219 $menu_html );
220 }
221  
222 sub print_balloon_settings {
223 my $custom_balloons = $CONFIG->setting('custom balloons');
224 my $images = $CONFIG->relative_path('images');
225 my %config_values = $custom_balloons =~ /\[([^]]+)\]([^[]+)/g;
226 $config_values{'balloon'} ||= <<END;
227 images = $images/balloons
228 delayTime = 500
229 END
230  
231 my $balloon_settings;
232  
233 for my $balloon (keys %config_values) {
234 my %config = $config_values{$balloon} =~ /(\w+)\s*=\s*(\S+)/g;
235 my $img = $config{images} || "$images/balloons";
236 $balloon_settings .= <<END;
237 var $balloon = new Balloon;
238 BalloonConfig($balloon);
239 $balloon.images = '$img';
240 $balloon.balloonImage = 'balloon.png';
241 $balloon.ieImage = 'balloon_ie.png';
242 $balloon.upLeftStem = 'up_left.png';
243 $balloon.downLeftStem = 'down_left.png';
244 $balloon.upRightStem = 'up_right.png';
245 $balloon.downRightStem = 'down_right.png';
246 $balloon.closeButton = 'close.png';
247 END
248 for my $option (keys %config) {
249 next if $option eq 'images';
250 my $value = $config{$option} =~ /^[\d.-]+$/ ? $config{$option} : "'$config{$option}'";
251 $balloon_settings .= "$balloon.$option = $value;\n";
252 }
253 }
254 print "<script>\n$balloon_settings\n</script>\n";
255 }
256  
257 sub print_bottom {
258 my ($version) = @_;
259 print
260 $CONFIG->footer || '',
261 p(i(font({-size=>'small'},
262 $CONFIG->tr('Footer_1'))),br,
263 tt(font({-size=>'small'},$CONFIG->tr('Footer_2',$version)))),
264 end_html;
265 }
266  
267 sub error {
268 my @msg = @_;
269 cluck "@_" if DEBUG;
270 print_top();
271 print h2({-class=>'error'},@msg);
272 }
273  
274 sub fatal_error {
275 my @msg = @_;
276 warn "@_" if DEBUG;
277 print_top($CONFIG,'GBrowse Error');
278 print h2('An internal error has occurred');
279 print p({-class=>'error'},@msg);
280 my $webmaster = $ENV{SERVER_ADMIN} ?
281 "maintainer (".a({-href=>"mailto:$ENV{SERVER_ADMIN}"},$ENV{SERVER_ADMIN}).')'
282 : 'maintainer';
283 print p("Please contact this site's $webmaster for assistance.");
284 print_bottom($CONFIG);
285 exit 0;
286 }
287  
288  
289 sub early_error {
290 my $lang = shift;
291 my $msg = shift;
292 $msg = $lang->tr($msg);
293 warn "@_" if DEBUG;
294 local $^W = 0; # to avoid a warning from CGI.pm
295 print_header(-expires=>'+1m');
296 my @args = (-title => 'GBrowse Error');
297 push @args,(-lang=>$lang->language);
298 print start_html();
299 print b($msg);
300 print end_html;
301 exit 0;
302 }
303  
304 sub set_language {
305 my ($config,$lang) = @_;
306 my $default_language = $config->setting('language');
307 my $accept = http('Accept-language') || '';
308 my @languages = $accept =~ /([a-z]{2}-?[a-z]*)/ig;
309 push @languages,$default_language if $default_language;
310 warn "languages = ",join(',',@languages) if DEBUG;
311 return unless @languages;
312 $lang->language(@languages);
313 }
314  
315 sub html_frag {
316 my $fragname = shift;
317 my $a = $CONFIG->config->setting(general => $fragname);
318 return $a->(@_) if ref $a eq 'CODE';
319 return $a || '';
320 }
321  
322 sub patch_old_versions_of_bioperl {
323 my $adaptor = shift;
324 my %argv = @_;
325 local $^W = 0;
326 require Bio::Perl;
327 if ($adaptor eq 'Bio::DB::GFF' && $Bio::Perl::VERSION == 1.5) {
328 eval <<'END';
329 use Bio::DB::GFF;
330 sub Bio::DB::GFF::load_gff {
331 my $self = shift;
332 my $file_or_directory = shift || '.';
333 my $verbose = shift;
334  
335 local $self->{__verbose__} = $verbose;
336 return $self->do_load_gff($file_or_directory) if ref($file_or_directory)
337 && tied *$file_or_directory;
338  
339 my $tied_stdin = tied(*STDIN);
340 open SAVEIN,"<&STDIN" unless $tied_stdin;
341 local @ARGV = $self->setup_argv($file_or_directory,'gff','gff3') or return; # to play tricks with reader
342 my $result = $self->do_load_gff('ARGV');
343 open STDIN,"<&SAVEIN" unless $tied_stdin; # restore STDIN
344 return $result;
345 }
346 sub Bio::DB::GFF::_load_gff_line {
347 my $self = shift;
348 my $line = shift;
349 my $lineend = $self->{load_data}{lineend};
350  
351 $self->{load_data}{gff3_flag}++ if $line =~ /^\#\#\s*gff-version\s+3/;
352 $self->preferred_groups(split(/\s+/,$1)) if $line =~ /^\#\#\s*group-tags?\s+(.+)/;
353  
354 if ($line =~ /^\#\#\s*sequence-region\s+(\S+)\s+(\d+)\s+(\d+)/i) { # header line
355 $self->load_gff_line(
356 {
357 ref => $1,
358 class => 'Sequence',
359 source => 'reference',
360 method => 'Component',
361 start => $2,
362 stop => $3,
363 score => undef,
364 strand => undef,
365 phase => undef,
366 gclass => 'Sequence',
367 gname => $1,
368 tstart => undef,
369 tstop => undef,
370 attributes => [],
371 }
372 );
373 return $self->{load_data}{count}++;
374 }
375  
376 return if /^#/;
377  
378 my ($ref,$source,$method,$start,$stop,$score,$strand,$phase,$group) = split "\t",$line;
379 return unless defined($ref) && defined($method) && defined($start) && defined($stop);
380 foreach (\$score,\$strand,\$phase) {
381 undef $$_ if $$_ eq '.';
382 }
383  
384 print STDERR $self->{load_data}{count}," records$lineend"
385 if $self->{__verbose__} && $self->{load_data}{count} % 1000 == 0;
386  
387 my ($gclass,$gname,$tstart,$tstop,$attributes) = $self->split_group($group,$self->{load_data}{gff3_flag});
388  
389 # no standard way in the GFF file to denote the class of the reference sequence -- drat!
390 # so we invoke the factory to do it
391 my $class = $self->refclass($ref);
392  
393 # call subclass to do the dirty work
394 if ($start > $stop) {
395 ($start,$stop) = ($stop,$start);
396 if ($strand eq '+') {
397 $strand = '-';
398 } elsif ($strand eq '-') {
399 $strand = '+';
400 }
401 }
402 # GFF2/3 transition stuff
403 $gclass = [$gclass] unless ref $gclass;
404 $gname = [$gname] unless ref $gname;
405 for (my $i=0; $i<@$gname;$i++) {
406 $self->load_gff_line({ref => $ref,
407 class => $class,
408 source => $source,
409 method => $method,
410 start => $start,
411 stop => $stop,
412 score => $score,
413 strand => $strand,
414 phase => $phase,
415 gclass => $gclass->[$i],
416 gname => $gname->[$i],
417 tstart => $tstart,
418 tstop => $tstop,
419 attributes => $attributes}
420 );
421 $self->{load_data}{count}++;
422 }
423 }
424 END
425 warn $@ if $@;
426 }
427  
428 if ($adaptor eq 'Bio::DB::GFF' && $argv{-adaptor} eq 'memory' && $Bio::Perl::VERSION <= 1.5) {
429 # patch memory.pm inability to handle missing gclass fields
430 eval <<'END';
431 use Bio::DB::GFF::Adaptor::memory;
432 sub Bio::DB::GFF::Adaptor::memory::load_gff_line {
433 my $self = shift;
434 my $feature_hash = shift;
435 $feature_hash->{strand} = '' if $feature_hash->{strand} && $feature_hash->{strand} eq '.';
436 $feature_hash->{phase} = '' if $feature_hash->{phase} && $feature_hash->{phase} eq '.';
437 $feature_hash->{gclass} = 'Sequence' unless length $feature_hash->{gclass} > 0;
438 # sort by group please
439 push @{$self->{tmp}{$feature_hash->{gclass},$feature_hash->{gname}}},$feature_hash;
440 }
441 END
442 warn $@ if $@;
443 }
444 }
445  
446 sub redirect_legacy_url {
447 my $source = shift;
448 my @more_args = @_;
449  
450 if ($source && path_info() ne "/$source/") {
451  
452 my $q = new CGI '';
453 if (request_method() eq 'GET') {
454 foreach (param()) {
455 next if $_ eq 'source';
456 $q->param($_=>param($_)) if defined param($_);
457 }
458 }
459  
460 # This is infinitely more difficult due to horrible bug in Apache version 2
461 # It is fixed in CGI.pm versions 3.11 and higher, but this version is not guaranteed
462 # to be available.
463 my ($script_name,$path_info) = _broken_apache_hack();
464 my $query_string = $q->query_string;
465 my $protocol = $q->protocol;
466  
467 my $new_url = $script_name;
468 $new_url .= "/$source/";
469 $new_url .= "?$query_string" if $query_string;
470  
471 print redirect(-uri=>$new_url,-status=>"301 Moved Permanently");
472 exit 0;
473 }
474 }
475  
476 sub parse_feature_str {
477 my $f = shift;
478 my ($reference,$type,$name,@position);
479 my @args = shellwords($f||'');
480 if (@args > 3) {
481 ($reference,$type,$name,@position) = @args;
482 } elsif (@args > 2) {
483 ($reference,$name,@position) = @args;
484 } elsif (@args > 1) {
485 ($reference,@position) = @args;
486 } elsif ($f =~ /^(.+):(\d+.+)$/) {
487 ($reference,@position) = ($1,$2);
488 } elsif ($f =~ /^(.+)/) {
489 $reference = $1;
490 @position = '1..1';
491 }
492 return unless $reference;
493  
494 $type = 'Your_Features' unless defined $type;
495 $name = "Feature ".++$ADDED_FEATURES unless defined $name;
496  
497 my @segments = map { [/(-?\d+)(?:-|\.\.)(-?\d+)/]} map {split ','} @position;
498 ($reference,$type,$name,@segments);
499 }
500  
501 # workaround for broken Apache 2 and CGI.pm <= 3.10
502 sub _broken_apache_hack {
503 my $raw_script_name = $ENV{SCRIPT_NAME} || '';
504 my $raw_path_info = $ENV{PATH_INFO} || '';
505 my $uri = $ENV{REQUEST_URI} || '';
506  
507 ## dgg patch; need for what versions? apache 1.x;
508 if ($raw_script_name =~ m/$raw_path_info$/) {
509 $raw_script_name =~ s/$raw_path_info$//;
510 }
511  
512 my @uri_double_slashes = $uri =~ m^(/{2,}?)^g;
513 my @path_double_slashes = "$raw_script_name $raw_path_info" =~ m^(/{2,}?)^g;
514  
515 my $apache_bug = @uri_double_slashes != @path_double_slashes;
516 return ($raw_script_name,$raw_path_info) unless $apache_bug;
517  
518 my $path_info_search = $raw_path_info;
519 # these characters will not (necessarily) be escaped
520 $path_info_search =~ s/([^a-zA-Z0-9$()':_.,+*\/;?=&-])/uc sprintf("%%%02x",ord($1))/eg;
521 $path_info_search = quotemeta($path_info_search);
522 $path_info_search =~ s!/!/+!g;
523 if ($uri =~ m/^(.+)($path_info_search)/) {
524 return ($1,$2);
525 } else {
526 return ($raw_script_name,$raw_path_info);
527 }
528 }
529  
530 sub is_safari {
531 return CGI::user_agent =~ /safari/i;
532 }
533  
534 # work around an annoying uninit variable warning from Text::Parsewords
535 sub shellwords {
536 my @args = @_;
537 return unless @args;
538 foreach(@args) {
539 s/^\s+//;
540 s/\s+$//;
541 $_ = '' unless defined $_;
542 }
543 my @result = Text::ParseWords::shellwords(@args);
544 return @result;
545 }
546 1;