AcePerl

 view release on metacpan or  search on metacpan

Ace/Browser/AceSubs.pm  view on Meta::CPAN


  my $db = get_symbolic();

  my $referer  = referer();
  $referer =~ s!^http://[^/]+!! if defined $referer;
  my $home = Configuration()->Home->[0] if Configuration()->Home;

  if ($referer && $home && index($referer,$home) >= 0) {
    my $bookmark = cookie(
			  -name=>"HOME_${db}",
			  -value=>$referer,
			  -path=>'/');
    push(@COOKIES,$bookmark);
  }

  if ($searches{$quovadis}) {
    Delete('Go');
    my $search_name = "SEARCH_${db}_${quovadis}";
    my $search_data = cookie(-name  => $search_name,
			     -value => query_string(),
			     -path=>'/',
			    );
    my $last_search = cookie(-name=>"ACEDB_$db",
			     -value=>$quovadis,
			     -path=>'/');
    push(@COOKIES,$search_data,$last_search);
  }

  print @COOKIES ? header(-cookie=>\@COOKIES,@_) : header(@_);

  @COOKIES = ();
  $HEADER++;
}

=item AceInit()

This subroutine initializes the AcePerl connection to the configured
database.  If the database cannot be opened, it generates an error
message and exits.  This subroutine is not exported by default, but is 
called by PrintTop() and Header() internally.

=cut

# Subroutines used by all scripts.
# Will generate an HTTP 'document not found' error if you try to get an 
# undefined database name.  Check the return code from this function and
# return immediately if not true (actually, not needed because we exit).
sub AceInit   {
  $HEADER   = 0;
  $TOP      = 0;
  @COOKIES  = ();

  # keeps track of what sections should be open
  %OPEN = param('open') ? map {$_ => 1} split(' ',param('open')) : () ;

  return 1 if Configuration();

  # if we get here, it is a big NOT FOUND error
  print header(-status=>'404 Not Found',-type=>'text/html');
  $HEADER++;
  print start_html(-title => 'Database Not Found',
		   -style => Ace::Browser::SiteDefs->getConfig(DEFAULT_DATABASE)->Style,
		  ),
        h1('Database not found'),
        p('The requested database',i(get_symbolic()),'is not recognized',
	  'by this server.');
  print p('Please return to the',a({-href=>referer()},'referring page.')) if referer();
  print end_html;
  Apache::exit(0) if defined &Apache::exit;  # bug out of here!
  exit(0);
}

=item AceMissing([$class,$name])

This subroutine will print out an error message indicating that an
object is present in AceDB, but that the information the user
requested is absent. It will then exit the script. This is
infrequently encountered when following XREFed objects. If the class
and name of the object are not provided as arguments, they are taken
from CGI's param() function.

=cut

sub AceMissing {
    my ($class,$name) = @_;
    $class ||= param('class');
    $name  ||= param('name');
    PrintTop(undef,undef,$name);
    print strong('There is no further information about this object in the database.');
    PrintBottom();
    Apache->exit(0) if defined &Apache::exit;
    exit(0);
}

=item AceMultipleChoices($symbol,$report,$objects)

This function is called when a search has recovered multiple objects
and the user must make a choice among them.  The user is presented
with an ordered list of the objects, and asked to click on one of
them.

The three arguements are:

   $symbol   The keyword or query string the user was searching
             on, undef if none.

   $report   The symbolic name of the current display, or undef
	     if none.

   $objects  An array reference containing the Ace objects in
	     question.

This subroutine is not exported by default.

=cut

sub AceMultipleChoices {
  my ($symbol,$report,$objects) = @_;
  if ($objects && @$objects == 1) {
    my $destination = Object2URL($objects->[0]);
    AceHeader(-Refresh => "1; URL=$destination");
    print start_html (
			   '-Title' => 'Redirect',
			   '-Style' => Style(),
			),
      h1('Redirect'),
      p("Automatically transforming this query into a request for corresponding object",
	ObjectLink($objects->[0],$objects->[0]->class.':'.$objects->[0])),
      p("Please wait..."),
      Footer(),
      end_html();
    return;
  }
  PrintTop(undef,undef,'Multiple Choices');
  print
    p("Multiple $report objects correspond to $symbol.",
      "Please choose one:"),
    ol(
       li([
	   map {ObjectLink($_,font({-color=>'red'},$_->class).': '.$_)} @$objects
	  ])
	    );
  PrintBottom();
}

=item AceNotFound([$class,$name])

This subroutine will print out an error message indicating that the
requested object is not present in AceDB, even as a name. It will then
exit the script. If the class and name of the object are not provided
as arguments, they are taken from CGI's param() function.

=cut

sub AceNotFound {
  my $class = shift || param('class');
  my $name  = shift || param('name');
  PrintTop(undef,undef,"$class: $name not found");
  print p(font({-color => 'red'},
	       strong("The $class named \"$name\" is not found in the database.")));
  PrintBottom();
  Apache->exit(0) if defined &Apache::exit;
  exit(0);
}

=item ($uri,$physical_path) = AcePicRoot($directory)

This function returns the physical and URL paths of a temporary
directory in which the pic script can write pictures.  Not exported by
default.  Returns a two-element list containing the URL and physical
path.

=cut

sub AcePicRoot {
  my $path = shift;
  my $umask = umask();
  umask 002;  # want this writable by group
  my ($picroot,$uri);
  if ($ENV{MOD_PERL} && Apache->can('request')) { # we have apache, so no reason not to take advantage of it
    my $r = Apache->request;
    $uri  = join('/',Configuration()->Pictures->[0],"/",$path);
    my $subr = $r->lookup_uri($uri);
    $picroot = $subr->filename if $subr;
  } else {
    ($uri,$picroot) = @{Configuration()->Pictures} if Configuration()->Pictures;
    $uri     .= "/$path";
    $picroot .= "/$path";
  }
  mkpath ($picroot,0,0777) || AceError("Can't create directory to store image in") unless -d $picroot;
  umask $umask;
  return ($uri,$picroot);
}


=item AceRedirect($report,$object)

This function redirects the user to a named display script for viewing 
an Ace object.  It is used, for example, to convert a request for a
sequence into a request for a protein:

  $obj = GetAceObject();
  if ($obj->CDS) {
    my $protein	= $obj->Corresponding_protein;
    AceRedirect('protein',$protein);
  }

AceRedirect must be called b<before> PrintTop() or  AceHeader().  It
invokes exit(), so it will not return.

This subroutine is not exported by default.  It differs from
DoRedirect() in that it displays a message to the user for two seconds
before it generates the new page. It also allows the display to be set
explicitly, rather than determined automatically by the AceBrowser
system.

=cut

###############  redirect to a different report #####################
sub AceRedirect {
  my ($report,$object) = @_;

  my $url = Configuration()->display($report,'url');

  my $args = ref($object) ? "name=$object&class=".$object->class
                          : "name=$object";
  my $destination = ResolveUrl($url => $args);
  AceHeader(-Refresh => "1; URL=$destination");
  print start_html (
			 '-Title' => 'Redirect',
			 '-Style' => Style(),
		         '-head'  => meta({-http_equiv=>'Refresh',-content=>"1; URL=$destination"})
			),
    h1('Redirect'),
    p("This request is being redirected to the \U$report\E display"),
    p("This page will automatically display the requested object in",
	   "one seconds",a({-href=>$destination},'Click on this link'),
	'to load the page immediately.'),
    end_html();
    Apache->exit(0) if defined &Apache::exit;
    exit(0);
}

=item $configuration = Configuration()

The Configuration() function returns the Ace::Browser::SiteDefs object
for the current session.  From this object you can retrieve
information from the configuration file.

=cut

# get the configuration object for this database
sub Configuration {
  my $s = get_symbolic()||return;
  return Ace::Browser::SiteDefs->getConfig($s);
}

=item $name = DB_Name()

This function returns the symbolic name of the current database, for
example "default".

=cut

*DB_Name = \&get_symbolic;

=item DoRedirect($object)

This subroutine immediately redirects to the default display for the
Ace::Object indicated by $object and exits the script.  It must be
called before PrintTop() or any other HTML-generating code.  It
differs from AceRedirect() in that it generates a fast redirect
without alerting the user.

This function is not exported by default.

=cut

# redirect to the URL responsible for an object
sub DoRedirect {
    my $obj = shift;
    print redirect(Object2URL($obj));
    Apache->exit(0) if defined &Apache::exit;
    exit(0);
}

=item $footer = Footer()

This function returns the contents of the footer as a string, but does 

Ace/Browser/AceSubs.pm  view on Meta::CPAN

  my @targ = $target ? (-target=>$target) : ();
  return a({-href=>Object2URL($object,@_),-name=>"$object",@targ},($link_text || "$object"));
}

=item $db = OpenDatabase()

This function opens the Acedb database designated by the configuration
file.  In modperl environments, this function caches database handles
and reuses them, pinging and reopening them in the case of timeouts.

This function is not exported by default.

=cut

use Carp 'cluck';

################ open a database #################
sub OpenDatabase {
  my $name = shift || get_symbolic();
  AceInit();
  $name =~ s!/$!!;
  my $db = $DB{$name};
  return $db if $db && $db->ping;

  my ($host,$port,$user,$password,
      $cache_root,$cache_size,$cache_expires,$auto_purge_interval)
    = getDatabasePorts($name);
  my @auth  = (-user=>$user,-pass=>$password) if $user && $password;
  my @cache = (-cache => { cache_root=>$cache_root,
			   max_size            => $cache_size || $Cache::SizeAwareCache::NO_MAX_SIZE || -1,  # hardcoded $NO_MAX_SIZE constant
			   default_expires_in  => $cache_expires       || '1 day',
			   auto_purge_interval => $auto_purge_interval || '6 hours',
			 } 
	      ) if $cache_root;
  $DB{$name} = Ace->connect(-host=>$host,-port=>$port,-timeout=>50,@auth,@cache);
  return $DB{$name};
}

=item PrintTop($object,$class,$title,@html_headers)

The PrintTop() function generates all the boilerplate at the top of a
typical AceBrowser page, including the HTTP header information, the
page title, the navigation bar for searches, the web site banner, the
type selector for choosing alternative displays, and a level-one
header.

Call it with one or more arguments.  The arguments are:

  $object    An AceDB object.  The navigation bar and title will be
	     customized for the object.

  $class     If no AceDB object is available, then you can pass 
	     a string containing the AceDB class that this page is
	     designed to display.

  $title     A title to use for the HTML page and the first level-one
	     header.  If not provided, a generic title "Report for
	     Object" is generated.

  @html_headers  Additional HTML headers to pass to the the CGI.pm
             start_html. 
	

=cut

# boilerplate for the top of the page
sub PrintTop {
  my ($object,$class,$title,@additional_header_stuff) = @_;
  return if $TOP++;
  $class = $object->class if defined $object && ref($object);
  $class ||= param('class') unless defined($title);
  AceHeader();
  $title ||= defined($object) ? "$class Report for: $object" : $class ? "$class Report" : ''
    unless defined($title);
  print start_html (
                    '-Title'   => $title,
                    '-Style'   => Style(),
                    @additional_header_stuff,
                    );
  print Header();
  print TypeSelector($object,$class) if defined $object;
  print h1($title) if $title;
}

=item PrintBottom()

The PrintBottom() function outputs all the boilerplate at the bottom
of a typical AceBrowser page.  If a user-defined footer is present in
the configuration file, that is printed.  Otherwise, the method prints 
a horizontal rule followed by links to the site home page, the AcePerl 
home page, the privacy policy, and the feedback page.

=cut

sub PrintBottom {
  print hr,Footer(),end_html();
}


=item $hashref = Style()

This subroutine returns a hashref containing a reference to the
configured stylesheet, in the following format:

  { -src => '/ace/stylesheets/current_stylesheet.css' }

This hash is suitable for passing to the -style argument of CGI.pm's
start_html() function, or for use as an additional header in
PrintTop().  You may add locally-defined stylesheet elements to the
hash before calling start_html().  See the pic script for an example
of how this is done this.

This function is not exported by default.

=cut

=item $url = ResolveUrl($url,$param)

Given a URL and a set of parameters, this function does the necessary
magic to add the symbolic database name to the end of the URL (if
needed) and then tack the parameters onto the end.

A typical call is:

  $url = ResolveUrl('/cgi-bin/ace/generic/tree','name=fred;class=Author');

This function is not exported by default.

=cut

sub ResolveUrl {
    my ($url,$param) = @_;
    my ($main,$query,$frag) = $url =~ /^([^?\#]+)\??([^\#]*)\#?(.*)$/ if defined $url;
    $main ||= '';
    
    if (!defined $APACHE_CONF) {
      $APACHE_CONF = eval { Apache->request->dir_config('AceBrowserConf') } ? 1 : 0;
    }

    $main = Configuration()->resolvePath($main) unless $main =~ m!^/!;
    if (my $id = get_symbolic()) {
      $main .= "/$id" unless $main =~ /$id/ or $APACHE_CONF;
    }

    $main .= "?$query" if $query; # put the query string back
    $main .= "?$param" if $param and !$query;
    $main .= ";$param" if $param and  $query;
    $main .= "#$frag" if $frag;
    return $main;
}

# A consistent stylesheet across pages
sub Style {
    my $stylesheet = Configuration()->Stylesheet;
    return { -src => $stylesheet };
}

=item $boolean = Toggle($section,[$label,$object_count,$add_plural,$add_count])

=item ($link,$bool) = Toggle($section,$label,$object_count,$add_plural,$add_count)

The Toggle() subroutine makes it easy to create HTML sections that
open and close when the user selects a toggle icon (a yellow
triangle).

Toggle() can be used to manage multiple collapsible HTML sections, but
each section must have a unique name.  The required first argument is
the section name.  Optional arguments are:

  $label         The text of the generated link, for example "sequence"



( run in 2.171 seconds using v1.01-cache-2.11-cpan-d8267643d1d )