[Bio] / Sprout / SearchHelper.pm Repository:
ViewVC logotype

Annotation of /Sprout/SearchHelper.pm

Parent Directory Parent Directory | Revision Log Revision Log


Revision 1.27 - (view) (download) (as text)

1 : parrello 1.1 #!/usr/bin/perl -w
2 :    
3 :     package SearchHelper;
4 :    
5 :     use strict;
6 :     use Tracer;
7 :     use PageBuilder;
8 :     use Digest::MD5;
9 :     use File::Basename;
10 :     use File::Path;
11 :     use File::stat;
12 :     use LWP::UserAgent;
13 :     use Time::HiRes 'gettimeofday';
14 :     use Sprout;
15 :     use SFXlate;
16 :     use FIGRules;
17 :     use HTML;
18 :     use BasicLocation;
19 : parrello 1.2 use FeatureQuery;
20 : parrello 1.3 use URI::Escape;
21 :     use PageBuilder;
22 : parrello 1.1
23 :     =head1 Search Helper Base Class
24 :    
25 :     =head2 Introduction
26 :    
27 :     The search helper is a base class for all search objects. It has methods for performing
28 :     all the common tasks required to build and manage a search cache. The subclass must
29 :     provide methods for generating and processing search forms. The base class has the
30 :     following object fields.
31 :    
32 :     =over 4
33 :    
34 :     =item cols
35 :    
36 :     Reference to a list of column header descriptions. If undefined, then the session cache
37 :     file has been opened but nothing has been written to it.
38 :    
39 :     =item fileHandle
40 :    
41 :     File handle for the session cache file.
42 :    
43 :     =item query
44 :    
45 :     CGI query object, which includes the search parameters and the various
46 :     session status variables kept between requests from the user.
47 :    
48 :     =item type
49 :    
50 :     Session type: C<old> if there is an existing cache file from which we are
51 :     displaying search results, or C<new> if the cache file needs to be built.
52 :    
53 :     =item class
54 :    
55 :     Name of the search helper class as it would appear in the CGI query object
56 :     (i.e. without the C<SH> prefix.
57 :    
58 :     =item sprout
59 :    
60 :     Sprout object for accessing the database.
61 :    
62 :     =item message
63 :    
64 :     Message to display if an error has been detected.
65 :    
66 :     =item orgs
67 :    
68 :     Reference to a hash mapping genome IDs to organism names.
69 :    
70 :     =item name
71 :    
72 :     Name to use for this object's form.
73 :    
74 :     =item scriptQueue
75 :    
76 :     List of JavaScript statements to be executed after the form is closed.
77 :    
78 : parrello 1.3 =item genomeHash
79 :    
80 :     Cache of the genome group hash used to build genome selection controls.
81 :    
82 :     =item genomeParms
83 :    
84 :     List of the parameters that are used to select multiple genomes.
85 :    
86 :     =item filtered
87 :    
88 :     TRUE if this is a feature-filtered search, else FALSE. B<NOTE> that this
89 :     field is updated by the B<FeatureQuery> object.
90 :    
91 : parrello 1.27 =item extraPos
92 :    
93 :     C<0> if the extra columns are to be at the beginning, else C<1>. The
94 :     default is zero; use the L</SetExtraPos> method to change this option.
95 :    
96 : parrello 1.1 =back
97 :    
98 : parrello 1.2 =head2 Adding a new Search Tool
99 :    
100 :     To add a new search tool to the system, you must
101 :    
102 :     =over 4
103 :    
104 :     =item 1
105 :    
106 :     Choose a class name for your search tool.
107 :    
108 :     =item 2
109 :    
110 :     Create a new subclass of this object and implement each of the virtual methods. The
111 :     name of the subclass must be C<SH>I<className>.
112 :    
113 :     =item 3
114 :    
115 :     Create an include file among the web server pages that describes how to use
116 :     the search tool. The include file must be in the B<includes> directory, and
117 :     its name must be C<SearchHelp_>I<className>C<.inc>.
118 :    
119 :     =item 4
120 :    
121 : parrello 1.15 In the C<SearchSkeleton.cgi> script and add a C<use> statement for your search tool.
122 : parrello 1.2
123 :     =back
124 :    
125 :     =head3 Building a Search Form
126 :    
127 :     All search forms are three-column tables. In general, you want one form
128 :     variable per table row. The first column should contain the label and
129 :     the second should contain the form control for specifying the variable
130 :     value. If the control is wide, you should use C<colspan="2"> to give it
131 :     extra room. B<Do not> specify a width in any of your table cells, as
132 :     width management is handled by this class.
133 :    
134 :     The general code for creating the form should be
135 :    
136 :     sub Form {
137 :     my ($self) = @_;
138 :     # Get the CGI object.
139 :     my $cgi = @self->Q();
140 :     # Start the form.
141 :     my $retVal = $self->FormStart("form title");
142 :     # Assemble the table rows.
143 :     my @rows = ();
144 :     ... push table row Html into @rows ...
145 :     push @rows, $self->SubmitRow();
146 :     ... push more Html into @rows ...
147 :     # Build the table from the rows.
148 :     $retVal .= $self->MakeTable(\@rows);
149 :     # Close the form.
150 :     $retVal .= $self->FormEnd();
151 :     # Return the form Html.
152 :     return $retVal;
153 :     }
154 :    
155 :     Several helper methods are provided for particular purposes.
156 :    
157 :     =over 4
158 :    
159 :     =item 1
160 :    
161 : parrello 1.3 L</NmpdrGenomeMenu> generates a control for selecting one or more genomes. Use
162 :     L</GetGenomes> to retrieve all the genomes passed in for a specified parameter
163 :     name. Note that as an assist to people working with GET-style links, if no
164 :     genomes are specified and the incoming request style is GET, all genomes will
165 :     be returned.
166 : parrello 1.2
167 :     =item 2
168 :    
169 :     L</FeatureFilterRow> formats several rows of controls for filtering features.
170 :     When you start building the code for the L</Find> method, you can use a
171 :     B<FeatureQuery> object to automatically filter each genome's features using
172 :     the values from the filter controls.
173 :    
174 :     =item 3
175 :    
176 :     L</QueueFormScript> allows you to queue JavaScript statements for execution
177 :     after the form is fully generated. If you are using very complicated
178 :     form controls, the L</QueueFormScript> method allows you to perform
179 :     JavaScript initialization. The L</NmpdrGenomeMenu> control uses this
180 :     facility to display a list of the pre-selected genomes.
181 :    
182 :     =back
183 :    
184 : parrello 1.14 If you are doing a feature search, you can also change the list of feature
185 :     columns displayed and their display order by overriding
186 :     L</DefaultFeatureColumns>.
187 :    
188 : parrello 1.2 Finally, when generating the code for your controls, be sure to use any incoming
189 :     query parameters as default values so that the search request is persistent.
190 :    
191 :     =head3 Finding Search Results
192 :    
193 :     The L</Find> method is used to create the search results. For a search that
194 :     wants to return features (which is most of them), the basic code structure
195 :     would work as follows. It is assumed that the L</FeatureFilterRows> method
196 :     has been used to create feature filtering parameters.
197 :    
198 :     sub Find {
199 :     my ($self) = @_;
200 :     # Get the CGI and Sprout objects.
201 :     my $cgi = $self->Q();
202 :     my $sprout = $self->DB();
203 :     # Declare the return variable. If it remains undefined, the caller will
204 :     # know that an error occurred.
205 :     my $retVal;
206 :     ... validate the parameters ...
207 :     if (... invalid parameters...) {
208 :     $self->SetMessage(...appropriate message...);
209 :     } elsif (FeatureQuery::Valid($self)) {
210 :     # Initialize the session file.
211 :     $self->OpenSession();
212 :     # Initialize the result counter.
213 :     $retVal = 0;
214 :     ... get a list of genomes ...
215 :     for my $genomeID (... each genome ...) {
216 :     my $fq = FeatureQuery->new($self, $genomeID);
217 :     while (my $feature = $fq->Fetch()) {
218 :     ... examine the feature ...
219 :     if (... we want to keep it ...) {
220 :     $self->PutFeature($fq);
221 :     $retVal++;
222 :     }
223 :     }
224 :     }
225 : parrello 1.9 # Close the session file.
226 :     $self->CloseSession();
227 : parrello 1.2 }
228 :     # Return the result count.
229 :     return $retVal;
230 :     }
231 :    
232 :     A Find method is of course much more complicated than generating a form, and there
233 : parrello 1.14 are variations on the above theme. For example, you could eschew feature filtering
234 : parrello 1.2 entirely in favor of your own custom filtering, you could include extra columns
235 :     in the output, or you could search for something that's not a feature at all. The
236 :     above code is just a loose framework.
237 :    
238 :     If you wish to add your own extra columns to the output, use the B<AddExtraColumns>
239 :     method of the feature query object.
240 :    
241 :     $fq->AddExtraColumns(score => $sc);
242 :    
243 :     The L</Find> method must return C<undef> if the search parameters are invalid. If this
244 :     is the case, then a message describing the problem should be passed to the framework
245 :     by calling L</SetMessage>. If the parameters are valid, then the method must return
246 :     the number of items found.
247 :    
248 : parrello 1.1 =cut
249 :    
250 :     # This counter is used to insure every form on the page has a unique name.
251 :     my $formCount = 0;
252 : parrello 1.16 # This counter is used to generate unique DIV IDs.
253 :     my $divCount = 0;
254 : parrello 1.1
255 :     =head2 Public Methods
256 :    
257 :     =head3 new
258 :    
259 :     C<< my $shelp = SearchHelper->new($query); >>
260 :    
261 :     Construct a new SearchHelper object.
262 :    
263 :     =over 4
264 :    
265 : parrello 1.19 =item cgi
266 : parrello 1.1
267 :     The CGI query object for the current script.
268 :    
269 :     =back
270 :    
271 :     =cut
272 :    
273 :     sub new {
274 :     # Get the parameters.
275 : parrello 1.19 my ($class, $cgi) = @_;
276 : parrello 1.1 # Check for a session ID.
277 : parrello 1.19 my $session_id = $cgi->param("SessionID");
278 : parrello 1.1 my $type = "old";
279 :     if (! $session_id) {
280 : parrello 1.26 Trace("No session ID found.") if T(3);
281 : parrello 1.1 # Here we're starting a new session. We create the session ID and
282 :     # store it in the query object.
283 :     $session_id = NewSessionID();
284 :     $type = "new";
285 : parrello 1.19 $cgi->param(-name => 'SessionID', -value => $session_id);
286 : parrello 1.26 } else {
287 :     Trace("Session ID is $session_id.") if T(3);
288 : parrello 1.1 }
289 :     # Compute the subclass name.
290 : parrello 1.19 my $subClass;
291 :     if ($class =~ /SH(.+)$/) {
292 :     # Here we have a real search class.
293 :     $subClass = $1;
294 :     } else {
295 :     # Here we have a bare class. The bare class cannot search, but it can
296 :     # process search results.
297 :     $subClass = 'SearchHelper';
298 :     }
299 : parrello 1.1 # Insure everybody knows we're in Sprout mode.
300 : parrello 1.19 $cgi->param(-name => 'SPROUT', -value => 1);
301 : parrello 1.1 # Generate the form name.
302 :     my $formName = "$class$formCount";
303 :     $formCount++;
304 :     # Create the shelp object. It contains the query object (with the session ID)
305 :     # as well as an indicator as to whether or not the session is new, plus the
306 : parrello 1.2 # class name and a placeholder for the Sprout object.
307 : parrello 1.1 my $retVal = {
308 : parrello 1.19 query => $cgi,
309 : parrello 1.1 type => $type,
310 :     class => $subClass,
311 : parrello 1.2 sprout => undef,
312 : parrello 1.1 orgs => {},
313 :     name => $formName,
314 :     scriptQueue => [],
315 : parrello 1.3 genomeList => undef,
316 :     genomeParms => [],
317 :     filtered => 0,
318 : parrello 1.27 extraPos => 0,
319 : parrello 1.1 };
320 :     # Bless and return it.
321 :     bless $retVal, $class;
322 :     return $retVal;
323 :     }
324 :    
325 :     =head3 Q
326 :    
327 :     C<< my $query = $shelp->Q(); >>
328 :    
329 :     Return the CGI query object.
330 :    
331 :     =cut
332 :    
333 :     sub Q {
334 :     # Get the parameters.
335 :     my ($self) = @_;
336 :     # Return the result.
337 :     return $self->{query};
338 :     }
339 :    
340 : parrello 1.9
341 :    
342 : parrello 1.1 =head3 DB
343 :    
344 :     C<< my $sprout = $shelp->DB(); >>
345 :    
346 :     Return the Sprout database object.
347 :    
348 :     =cut
349 :    
350 :     sub DB {
351 :     # Get the parameters.
352 :     my ($self) = @_;
353 : parrello 1.2 # Insure we have a database.
354 :     my $retVal = $self->{sprout};
355 :     if (! defined $retVal) {
356 :     $retVal = SFXlate->new_sprout_only();
357 :     $self->{sprout} = $retVal;
358 :     }
359 : parrello 1.1 # Return the result.
360 : parrello 1.2 return $retVal;
361 : parrello 1.1 }
362 :    
363 :     =head3 IsNew
364 :    
365 :     C<< my $flag = $shelp->IsNew(); >>
366 :    
367 :     Return TRUE if this is a new session, FALSE if this is an old session. An old
368 :     session already has search results ready to process.
369 :    
370 :     =cut
371 :    
372 :     sub IsNew {
373 :     # Get the parameters.
374 :     my ($self) = @_;
375 :     # Return the result.
376 :     return ($self->{type} eq 'new');
377 :     }
378 :    
379 : parrello 1.27 =head3 SetExtraPos
380 :    
381 :     C<< $shelp->SetExtraPos($newValue); >>
382 :    
383 :     Indicate whether the extra columns should be in the front (C<0>) or end (C<1>) columns of the results.
384 :    
385 :     =over 4
386 :    
387 :     =item newValue
388 :    
389 :     C<1> if the extra columns should be displayed at the end, else C<0>.
390 :    
391 :     =back
392 :    
393 :     =cut
394 :    
395 :     sub SetExtraPos {
396 :     my ($self, $newValue) = @_;
397 :     $self->{extraPos} = $newValue;
398 :     }
399 :    
400 : parrello 1.1 =head3 ID
401 :    
402 :     C<< my $sessionID = $shelp->ID(); >>
403 :    
404 :     Return the current session ID.
405 :    
406 :     =cut
407 :    
408 :     sub ID {
409 :     # Get the parameters.
410 :     my ($self) = @_;
411 :     # Return the result.
412 :     return $self->Q()->param("SessionID");
413 :     }
414 :    
415 :     =head3 FormName
416 :    
417 :     C<< my $name = $shelp->FormName(); >>
418 :    
419 :     Return the name of the form this helper object will generate.
420 :    
421 :     =cut
422 :    
423 :     sub FormName {
424 :     # Get the parameters.
425 :     my ($self) = @_;
426 :     # Return the result.
427 :     return $self->{name};
428 :     }
429 :    
430 :     =head3 QueueFormScript
431 :    
432 :     C<< $shelp->QueueFormScript($statement); >>
433 :    
434 :     Add the specified statement to the queue of JavaScript statements that are to be
435 :     executed when the form has been fully defined. This is necessary because until
436 :     the closing </FORM> tag is emitted, the form elements cannot be referenced by
437 :     name. When generating the statement, you can refer to the variable C<thisForm>
438 :     in order to reference the form in progress. Thus,
439 :    
440 :     thisForm.simLimit.value = 1e-10;
441 :    
442 :     would set the value of the form element C<simLimit> in the current form to
443 :     C<1e-10>.
444 :    
445 :     =over 4
446 :    
447 :     =item statement
448 :    
449 :     JavaScript statement to be queued for execution after the form is built.
450 :     The trailing semi-colon is required. Theoretically, you could include
451 :     multiple statements separated by semi-colons, but one at a time works
452 :     just as well.
453 :    
454 :     =back
455 :    
456 :     =cut
457 :    
458 :     sub QueueFormScript {
459 :     # Get the parameters.
460 :     my ($self, $statement) = @_;
461 :     # Push the statement onto the script queue.
462 :     push @{$self->{scriptQueue}}, $statement;
463 :     }
464 :    
465 :     =head3 FormStart
466 :    
467 :     C<< my $html = $shelp->FormStart($title); >>
468 :    
469 :     Return the initial section of a form designed to perform another search of the
470 :     same type. The form header is included along with hidden fields to persist the
471 :     tracing, sprout status, and search class.
472 :    
473 :     A call to L</FormEnd> is required to close the form.
474 :    
475 :     =over 4
476 :    
477 :     =item title
478 :    
479 :     Title to be used for the form.
480 :    
481 :     =item RETURN
482 :    
483 :     Returns the initial HTML for the search form.
484 :    
485 :     =back
486 :    
487 :     =cut
488 :    
489 :     sub FormStart {
490 :     # Get the parameters.
491 :     my ($self, $title) = @_;
492 :     # Get the CGI object.
493 :     my $cgi = $self->Q();
494 : parrello 1.18 # Start the form. Note we use the override option on the Class value, in
495 :     # case the Advanced button was used.
496 : parrello 1.1 my $retVal = "<div class=\"search\">\n" .
497 :     $cgi->start_form(-method => 'POST',
498 :     -action => $cgi->url(-relative => 1),
499 :     -name => $self->FormName()) .
500 :     $cgi->hidden(-name => 'Class',
501 : parrello 1.18 -value => $self->{class},
502 :     -override => 1) .
503 : parrello 1.1 $cgi->hidden(-name => 'SPROUT',
504 :     -value => 1) .
505 :     $cgi->h3($title);
506 :     # If tracing is on, add it to the form.
507 :     if ($cgi->param('Trace')) {
508 :     $retVal .= $cgi->hidden(-name => 'Trace',
509 :     -value => $cgi->param('Trace')) .
510 :     $cgi->hidden(-name => 'TF',
511 :     -value => ($cgi->param('TF') ? 1 : 0));
512 :     }
513 :     # Put in an anchor tag in case there's a table of contents.
514 :     my $anchorName = $self->FormName();
515 :     $retVal .= "<a name=\"$anchorName\"></a>\n";
516 :     # Return the result.
517 :     return $retVal;
518 :     }
519 :    
520 :     =head3 FormEnd
521 :    
522 :     C<< my $htmlText = $shelp->FormEnd(); >>
523 :    
524 :     Return the HTML text for closing a search form. This closes both the C<form> and
525 :     C<div> tags.
526 :    
527 :     =cut
528 :    
529 :     sub FormEnd {
530 :     # Get the parameters.
531 :     my ($self) = @_;
532 :     # Declare the return variable, closing the form and the DIV block.
533 :     my $retVal = "</form></div>\n";
534 :     # Now we flush out the statement queue.
535 :     my @statements = @{$self->{scriptQueue}};
536 :     if (@statements > 0) {
537 :     # Switch to JavaScript and set the "thisForm" variable.
538 :     $retVal .= "<SCRIPT language=\"JavaScript\">\n" .
539 :     " thisForm = document.$self->{name};\n";
540 :     # Unroll the statements.
541 :     while (@statements > 0) {
542 :     my $statement = shift @statements;
543 :     $retVal .= " $statement\n";
544 :     }
545 :     # Close the JavaScript.
546 :     $retVal .= "</SCRIPT>\n";
547 :     }
548 :     # Return the result.
549 :     return $retVal;
550 :     }
551 :    
552 :     =head3 SetMessage
553 :    
554 :     C<< $shelp->SetMessage($msg); >>
555 :    
556 :     Store the specified text as the result message. The result message is displayed
557 :     if an invalid parameter value is specified.
558 :    
559 :     =over 4
560 :    
561 :     =item msg
562 :    
563 :     Text of the result message to be displayed.
564 :    
565 :     =back
566 :    
567 :     =cut
568 :    
569 :     sub SetMessage {
570 :     # Get the parameters.
571 :     my ($self, $msg) = @_;
572 :     # Store the message.
573 :     $self->{message} = $msg;
574 :     }
575 :    
576 :     =head3 Message
577 :    
578 :     C<< my $text = $shelp->Message(); >>
579 :    
580 :     Return the result message. The result message is displayed if an invalid parameter
581 :     value is specified.
582 :    
583 :     =cut
584 :    
585 :     sub Message {
586 :     # Get the parameters.
587 :     my ($self) = @_;
588 :     # Return the result.
589 :     return $self->{message};
590 :     }
591 :    
592 :     =head3 OpenSession
593 :    
594 :     C<< $shelp->OpenSession(); >>
595 :    
596 :     Set up to open the session cache file for writing. Note we don't actually
597 :     open the file until after we know the column headers.
598 :    
599 :     =cut
600 :    
601 :     sub OpenSession {
602 :     # Get the parameters.
603 :     my ($self) = @_;
604 :     # Denote we have not yet written out the column headers.
605 :     $self->{cols} = undef;
606 :     }
607 :    
608 :     =head3 GetCacheFileName
609 :    
610 :     C<< my $fileName = $shelp->GetCacheFileName(); >>
611 :    
612 :     Return the name to be used for this session's cache file.
613 :    
614 :     =cut
615 :    
616 :     sub GetCacheFileName {
617 :     # Get the parameters.
618 :     my ($self) = @_;
619 :     # Return the result.
620 :     return $self->GetTempFileName('cache');
621 :     }
622 :    
623 :     =head3 GetTempFileName
624 :    
625 :     C<< my $fileName = $shelp->GetTempFileName($type); >>
626 :    
627 :     Return the name to be used for a temporary file of the specified type. The
628 :     name is computed from the session name with the type as a suffix.
629 :    
630 :     =over 4
631 :    
632 :     =item type
633 :    
634 :     Type of temporary file to be generated.
635 :    
636 :     =item RETURN
637 :    
638 :     Returns a file name generated from the session name and the specified type.
639 :    
640 :     =back
641 :    
642 :     =cut
643 :    
644 :     sub GetTempFileName {
645 :     # Get the parameters.
646 :     my ($self, $type) = @_;
647 :     # Compute the file name. Note it gets stuffed in the FIG temporary
648 :     # directory.
649 :     my $retVal = "$FIG_Config::temp/tmp_" . $self->ID() . ".$type";
650 :     # Return the result.
651 :     return $retVal;
652 :     }
653 :    
654 :     =head3 PutFeature
655 :    
656 : parrello 1.11 C<< $shelp->PutFeature($fdata); >>
657 : parrello 1.1
658 :     Store a feature in the result cache. This is the workhorse method for most
659 :     searches, since the primary data item in the database is features.
660 :    
661 :     For each feature, there are certain columns that are standard: the feature name, the
662 :     GBrowse and protein page links, the functional assignment, and so forth. If additional
663 : parrello 1.2 columns are required by a particular search subclass, they should be stored in
664 :     the feature query object using the B<AddExtraColumns> method. For example, the following
665 :     code adds columns for essentiality and virulence.
666 : parrello 1.1
667 : parrello 1.11 $fd->AddExtraColumns(essential => $essentialFlag, virulence => $vfactor);
668 :     $shelp->PutFeature($fd);
669 : parrello 1.1
670 :     For correct results, all values should be specified for all extra columns in all calls to
671 :     B<PutFeature>. (In particular, the column header names are computed on the first
672 :     call.) If a column is to be blank for the current feature, its value can be given
673 :     as C<undef>.
674 :    
675 :     if (! $essentialFlag) {
676 :     $essentialFlag = undef;
677 :     }
678 : parrello 1.11 $fd->AddExtraColumns(essential => $essentialFlag, virulence => $vfactor);
679 :     $shelp->PutFeature($fd);
680 : parrello 1.1
681 :     =over 4
682 :    
683 : parrello 1.11 =item fdata
684 : parrello 1.1
685 : parrello 1.11 B<FeatureData> object containing the current feature data.
686 : parrello 1.1
687 :     =back
688 :    
689 :     =cut
690 :    
691 :     sub PutFeature {
692 : parrello 1.2 # Get the parameters.
693 : parrello 1.11 my ($self, $fd) = @_;
694 : parrello 1.3 # Get the CGI query object.
695 :     my $cgi = $self->Q();
696 : parrello 1.2 # Get the feature data.
697 : parrello 1.11 my $record = $fd->Feature();
698 :     my $extraCols = $fd->ExtraCols();
699 : parrello 1.1 # Check for a first-call situation.
700 :     if (! defined $self->{cols}) {
701 : parrello 1.14 Trace("Setting up the columns.") if T(3);
702 : parrello 1.27 # Here we need to set up the column information. First we accumulate the extras,
703 : parrello 1.14 # sorted by column name.
704 : parrello 1.27 my @xtraNames = ();
705 :     for my $col (sort keys %{$extraCols}) {
706 :     push @xtraNames, "X=$col";
707 :     }
708 :     # Set up the column name array.
709 : parrello 1.14 my @colNames = ();
710 : parrello 1.27 # If extras go at the beginning, put them in first.
711 :     if (! $self->{extraPos}) {
712 :     push @colNames, @xtraNames;
713 : parrello 1.1 }
714 : parrello 1.14 # Add the default columns.
715 :     push @colNames, $self->DefaultFeatureColumns();
716 :     # Add any additional columns requested by the feature filter.
717 :     push @colNames, FeatureQuery::AdditionalColumns($self);
718 : parrello 1.27 # If extras go at the end, put them in here.
719 :     if ($self->{extraPos}) {
720 :     push @colNames, @xtraNames;
721 :     }
722 : parrello 1.23 Trace("Full column list determined.") if T(3);
723 : parrello 1.14 # Save the full list.
724 :     $self->{cols} = \@colNames;
725 : parrello 1.1 # Write out the column headers. This also prepares the cache file to receive
726 :     # output.
727 : parrello 1.23 Trace("Writing column headers.") if T(3);
728 : parrello 1.1 $self->WriteColumnHeaders(map { $self->FeatureColumnTitle($_) } @{$self->{cols}});
729 : parrello 1.23 Trace("Column headers written.") if T(3);
730 : parrello 1.1 }
731 :     # Get the feature ID.
732 : parrello 1.11 my $fid = $fd->FID();
733 : parrello 1.1 # Loop through the column headers, producing the desired data.
734 :     my @output = ();
735 :     for my $colName (@{$self->{cols}}) {
736 : parrello 1.2 push @output, $self->FeatureColumnValue($colName, $record, $extraCols);
737 : parrello 1.1 }
738 : parrello 1.9 # Compute the sort key. The sort key usually floats NMPDR organism features to the
739 : parrello 1.1 # top of the return list.
740 : parrello 1.11 my $key = $self->SortKey($fd);
741 : parrello 1.1 # Write the feature data.
742 :     $self->WriteColumnData($key, @output);
743 :     }
744 :    
745 :     =head3 WriteColumnHeaders
746 :    
747 :     C<< $shelp->WriteColumnHeaders(@colNames); >>
748 :    
749 :     Write out the column headers for the current search session. The column headers
750 :     are sent to the cache file, and then the cache is re-opened as a sort pipe and
751 :     the handle saved.
752 :    
753 :     =over 4
754 :    
755 :     =item colNames
756 :    
757 :     A list of column names in the desired presentation order.
758 :    
759 :     =back
760 :    
761 :     =cut
762 :    
763 :     sub WriteColumnHeaders {
764 :     # Get the parameters.
765 :     my ($self, @colNames) = @_;
766 :     # Get the cache file name and open it for output.
767 :     my $fileName = $self->GetCacheFileName();
768 :     my $handle1 = Open(undef, ">$fileName");
769 :     # Write the column headers and close the file.
770 :     Tracer::PutLine($handle1, \@colNames);
771 :     close $handle1;
772 :     # Now open the sort pipe and save the file handle. Note how we append the
773 :     # sorted data to the column header row already in place. The output will
774 :     # contain a sort key followed by the real columns. The sort key is
775 :     # hacked off before going to the output file.
776 :     $self->{fileHandle} = Open(undef, "| sort | cut --fields=2- >>$fileName");
777 :     }
778 :    
779 :     =head3 WriteColumnData
780 :    
781 :     C<< $shelp->WriteColumnData($key, @colValues); >>
782 :    
783 :     Write a row of column values to the current search session. It is assumed that
784 :     the session file is already open for output.
785 :    
786 :     =over 4
787 :    
788 :     =item key
789 :    
790 :     Sort key.
791 :    
792 :     =item colValues
793 :    
794 :     List of column values to write to the search result cache file for this session.
795 :    
796 :     =back
797 :    
798 :     =cut
799 :    
800 :     sub WriteColumnData {
801 :     # Get the parameters.
802 :     my ($self, $key, @colValues) = @_;
803 :     # Write them to the cache file.
804 :     Tracer::PutLine($self->{fileHandle}, [$key, @colValues]);
805 :     }
806 :    
807 :     =head3 CloseSession
808 :    
809 :     C<< $shelp->CloseSession(); >>
810 :    
811 :     Close the session file.
812 :    
813 :     =cut
814 :    
815 :     sub CloseSession {
816 :     # Get the parameters.
817 :     my ($self) = @_;
818 :     # Check for an open session file.
819 :     if (defined $self->{fileHandle}) {
820 :     # We found one, so close it.
821 : parrello 1.9 Trace("Closing session file.") if T(2);
822 : parrello 1.1 close $self->{fileHandle};
823 :     }
824 :     }
825 :    
826 :     =head3 NewSessionID
827 :    
828 :     C<< my $id = SearchHelpers::NewSessionID(); >>
829 :    
830 :     Generate a new session ID for the current user.
831 :    
832 :     =cut
833 :    
834 :     sub NewSessionID {
835 :     # Declare the return variable.
836 :     my $retVal;
837 :     # Get a digest encoder.
838 :     my $md5 = Digest::MD5->new();
839 : parrello 1.4 # Add the PID, the IP, and the time stamp. Note that the time stamp is
840 :     # actually two numbers, and we get them both because we're in list
841 :     # context.
842 :     $md5->add($$, $ENV{REMOTE_ADDR}, $ENV{REMOTE_PORT}, gettimeofday());
843 :     # Hash up all this identifying data.
844 :     $retVal = $md5->hexdigest();
845 :     # Return the result.
846 : parrello 1.1 return $retVal;
847 :     }
848 :    
849 :     =head3 OrganismData
850 :    
851 :     C<< my ($orgName, $group) = $shelp->Organism($genomeID); >>
852 :    
853 :     Return the name and status of the organism corresponding to the specified genome ID.
854 :     For performance reasons, this information is cached in a special hash table, so we
855 :     only compute it once per run.
856 :    
857 :     =over 4
858 :    
859 :     =item genomeID
860 :    
861 :     ID of the genome whose name is desired.
862 :    
863 :     =item RETURN
864 :    
865 :     Returns a list of two items. The first item in the list is the organism name,
866 :     and the second is the name of the NMPDR group, or an empty string if the
867 :     organism is not in an NMPDR group.
868 :    
869 :     =back
870 :    
871 :     =cut
872 :    
873 :     sub OrganismData {
874 :     # Get the parameters.
875 :     my ($self, $genomeID) = @_;
876 :     # Declare the return variables.
877 :     my ($orgName, $group);
878 :     # Check the cache.
879 :     my $cache = $self->{orgs};
880 :     if (exists $cache->{$genomeID}) {
881 :     ($orgName, $group) = @{$cache->{$genomeID}};
882 :     } else {
883 :     # Here we have to use the database.
884 :     my $sprout = $self->DB();
885 :     my ($genus, $species, $strain, $group) = $sprout->GetEntityValues('Genome', $genomeID,
886 :     ['Genome(genus)', 'Genome(species)',
887 :     'Genome(unique-characterization)',
888 :     'Genome(primary-group)']);
889 : parrello 1.10 # Format and cache the name and display group.
890 :     ($orgName, $group) = $self->SaveOrganismData($group, $genomeID, $genus, $species,
891 :     $strain);
892 : parrello 1.1 }
893 :     # Return the result.
894 :     return ($orgName, $group);
895 :     }
896 :    
897 :     =head3 Organism
898 :    
899 :     C<< my $orgName = $shelp->Organism($genomeID); >>
900 :    
901 :     Return the name of the relevant organism. The name is computed from the genus,
902 :     species, and unique characterization. A cache is used to improve performance.
903 :    
904 :     =over 4
905 :    
906 :     =item genomeID
907 :    
908 :     ID of the genome whose name is desired.
909 :    
910 :     =item RETURN
911 :    
912 :     Returns the display name of the specified organism.
913 :    
914 :     =back
915 :    
916 :     =cut
917 :    
918 :     sub Organism {
919 :     # Get the parameters.
920 :     my ($self, $genomeID) = @_;
921 :     # Get the organism data.
922 :     my ($retVal, $group) = $self->OrganismData($genomeID);
923 :     # Return the result.
924 :     return $retVal;
925 :     }
926 :    
927 :     =head3 FeatureGroup
928 :    
929 :     C<< my $groupName = $shelp->FeatureGroup($fid); >>
930 :    
931 :     Return the group name for the specified feature.
932 :    
933 :     =over 4
934 :    
935 :     =item fid
936 :    
937 :     ID of the relevant feature.
938 :    
939 :     =item RETURN
940 :    
941 :     Returns the name of the NMPDR group to which the feature belongs, or an empty
942 :     string if it is not part of an NMPDR group.
943 :    
944 :     =back
945 :    
946 :     =cut
947 :    
948 :     sub FeatureGroup {
949 :     # Get the parameters.
950 :     my ($self, $fid) = @_;
951 :     # Parse the feature ID to get the genome ID.
952 :     my ($genomeID) = FIGRules::ParseFeatureID($fid);
953 :     # Get the organism data.
954 :     my (undef, $retVal) = $self->OrganismData($genomeID);
955 :     # Return the result.
956 :     return $retVal;
957 :     }
958 :    
959 :     =head3 FeatureName
960 :    
961 :     C<< my $fidName = $shelp->FeatureName($fid); >>
962 :    
963 :     Return the display name of the specified feature.
964 :    
965 :     =over 4
966 :    
967 :     =item fid
968 :    
969 :     ID of the feature whose name is desired.
970 :    
971 :     =item RETURN
972 :    
973 :     A displayable feature name, consisting of the organism name plus some feature
974 :     type and location information.
975 :    
976 :     =back
977 :    
978 :     =cut
979 :    
980 :     sub FeatureName {
981 :     # Get the parameters.
982 :     my ($self, $fid) = @_;
983 :     # Declare the return variable
984 :     my $retVal;
985 :     # Parse the feature ID.
986 :     my ($genomeID, $type, $num) = FIGRules::ParseFeatureID($fid);
987 :     if (! defined $genomeID) {
988 :     # Here the feature ID has an invalid format.
989 :     $retVal = "External: $fid";
990 :     } else {
991 :     # Here we can get its genome data.
992 :     $retVal = $self->Organism($genomeID);
993 : parrello 1.4 # Append the FIG ID.
994 :     $retVal .= " [$fid]";
995 : parrello 1.1 }
996 :     # Return the result.
997 :     return $retVal;
998 :     }
999 :    
1000 :     =head3 ComputeFASTA
1001 :    
1002 : parrello 1.18 C<< my $fasta = $shelp->ComputeFASTA($desiredType, $sequence); >>
1003 : parrello 1.1
1004 : parrello 1.18 Parse a sequence input and convert it into a FASTA string of the desired type.
1005 : parrello 1.1
1006 :     =over 4
1007 :    
1008 :     =item desiredType
1009 :    
1010 : parrello 1.18 C<dna> to return a DNA sequence, C<prot> to return a protein sequence.
1011 : parrello 1.1
1012 :     =item sequence
1013 :    
1014 :     Sequence to return. It may be a DNA or protein sequence in FASTA form or a feature ID.
1015 :     If a feature ID is specified, the feature's DNA or translation will be returned. The
1016 :     feature ID is recognized by the presence of a vertical bar in the input. Otherwise,
1017 :     if the input does not begin with a greater-than sign (FASTA label line), a default label
1018 :     line will be provided.
1019 :    
1020 :     =item RETURN
1021 :    
1022 :     Returns a string in FASTA format representing the content of the desired sequence with
1023 :     an appropriate label. If the input is invalid, a message will be stored and we will
1024 :     return C<undef>. Note that the output will include a trailing new-line.
1025 :    
1026 :     =back
1027 :    
1028 :     =cut
1029 :    
1030 :     sub ComputeFASTA {
1031 :     # Get the parameters.
1032 : parrello 1.20 my ($self, $desiredType, $sequence) = @_;
1033 : parrello 1.1 # Declare the return variable. If an error occurs, it will remain undefined.
1034 :     my $retVal;
1035 : parrello 1.11 # This variable will be cleared if an error is detected.
1036 :     my $okFlag = 1;
1037 : parrello 1.1 # Create variables to hold the FASTA label and data.
1038 :     my ($fastaLabel, $fastaData);
1039 : parrello 1.18 Trace("FASTA desired type is $desiredType.") if T(4);
1040 : parrello 1.1 # Check for a feature specification.
1041 :     if ($sequence =~ /^\s*(\w+\|\S+)\s*$/) {
1042 :     # Here we have a feature ID in $1. We'll need the Sprout object to process
1043 :     # it.
1044 :     my $fid = $1;
1045 : parrello 1.11 Trace("Feature ID for fasta is $fid.") if T(3);
1046 : parrello 1.1 my $sprout = $self->DB();
1047 :     # Get the FIG ID. Note that we only use the first feature found. We are not
1048 :     # supposed to have redundant aliases, though we may have an ID that doesn't
1049 :     # exist.
1050 :     my ($figID) = $sprout->FeaturesByAlias($fid);
1051 :     if (! $figID) {
1052 : parrello 1.17 $self->SetMessage("No gene found with the ID \"$fid\".");
1053 : parrello 1.11 $okFlag = 0;
1054 : parrello 1.1 } else {
1055 :     # Set the FASTA label.
1056 :     my $fastaLabel = $fid;
1057 :     # Now proceed according to the sequence type.
1058 : parrello 1.11 if ($desiredType eq 'prot') {
1059 : parrello 1.1 # We want protein, so get the translation.
1060 :     $fastaData = $sprout->FeatureTranslation($figID);
1061 : parrello 1.11 Trace(length $fastaData . " characters returned for translation of $fastaLabel.") if T(3);
1062 : parrello 1.1 } else {
1063 :     # We want DNA, so get the DNA sequence. This is a two-step process.
1064 :     my @locList = $sprout->FeatureLocation($figID);
1065 :     $fastaData = $sprout->DNASeq(\@locList);
1066 : parrello 1.11 Trace(length $fastaData . " characters returned for DNA of $fastaLabel.") if T(3);
1067 : parrello 1.1 }
1068 :     }
1069 :     } else {
1070 : parrello 1.11 Trace("Analyzing FASTA sequence.") if T(4);
1071 : parrello 1.1 # Here we are expecting a FASTA. We need to see if there's a label.
1072 : parrello 1.11 if ($sequence =~ /^>[\n\s]*(\S[^\n]*)\n(.+)$/s) {
1073 :     Trace("Label \"$1\" found in match to sequence:\n$sequence") if T(4);
1074 : parrello 1.1 # Here we have a label, so we split it from the data.
1075 :     $fastaLabel = $1;
1076 :     $fastaData = $2;
1077 :     } else {
1078 : parrello 1.11 Trace("No label found in match to sequence:\n$sequence") if T(4);
1079 : parrello 1.1 # Here we have no label, so we create one and use the entire sequence
1080 :     # as data.
1081 : parrello 1.18 $fastaLabel = "User-specified $desiredType sequence";
1082 : parrello 1.1 $fastaData = $sequence;
1083 :     }
1084 :     # The next step is to clean the junk out of the sequence.
1085 :     $fastaData =~ s/\n//g;
1086 :     $fastaData =~ s/\s+//g;
1087 : parrello 1.18 # Finally, verify that it's DNA if we're doing DNA stuff.
1088 : parrello 1.24 if ($desiredType eq 'dna' && $fastaData =~ /[^agctxn]/i) {
1089 :     $self->SetMessage("Invalid characters detected. Is the input really a DNA sequence?");
1090 : parrello 1.11 $okFlag = 0;
1091 : parrello 1.1 }
1092 :     }
1093 : parrello 1.11 Trace("FASTA data sequence: $fastaData") if T(4);
1094 :     # Only proceed if no error was detected.
1095 :     if ($okFlag) {
1096 : parrello 1.1 # We need to format the sequence into 60-byte chunks. We use the infamous
1097 :     # grep-split trick. The split, because of the presence of the parentheses,
1098 :     # includes the matched delimiters in the output list. The grep strips out
1099 :     # the empty list items that appear between the so-called delimiters, since
1100 :     # the delimiters are what we want.
1101 :     my @chunks = grep { $_ } split /(.{1,60})/, $fastaData;
1102 : parrello 1.11 $retVal = join("\n", ">$fastaLabel", @chunks, "");
1103 : parrello 1.1 }
1104 :     # Return the result.
1105 :     return $retVal;
1106 :     }
1107 :    
1108 : parrello 1.16 =head3 SubsystemTree
1109 :    
1110 :     C<< my $tree = SearchHelper::SubsystemTree($sprout, %options); >>
1111 :    
1112 :     This method creates a subsystem selection tree suitable for passing to
1113 :     L</SelectionTree>. Each leaf node in the tree will have a link to the
1114 :     subsystem display page. In addition, each node can have a radio button. The
1115 :     radio button alue is either C<classification=>I<string>, where I<string> is
1116 :     a classification string, or C<id=>I<string>, where I<string> is a subsystem ID.
1117 :     Thus, it can either be used to filter by a group of related subsystems or a
1118 :     single subsystem.
1119 :    
1120 :     =over 4
1121 :    
1122 :     =item sprout
1123 :    
1124 :     Sprout database object used to get the list of subsystems.
1125 :    
1126 :     =item options
1127 :    
1128 :     Hash containing options for building the tree.
1129 :    
1130 :     =item RETURN
1131 :    
1132 :     Returns a reference to a tree list suitable for passing to L</SelectionTree>.
1133 :    
1134 :     =back
1135 :    
1136 :     The supported options are as follows.
1137 :    
1138 :     =over 4
1139 :    
1140 :     =item radio
1141 :    
1142 :     TRUE if the tree should be configured for radio buttons. The default is FALSE.
1143 :    
1144 :     =item links
1145 :    
1146 :     TRUE if the tree should be configured for links. The default is TRUE.
1147 :    
1148 :     =back
1149 :    
1150 :     =cut
1151 :    
1152 :     sub SubsystemTree {
1153 :     # Get the parameters.
1154 :     my ($sprout, %options) = @_;
1155 :     # Process the options.
1156 :     my $optionThing = Tracer::GetOptions({ radio => 0, links => 1 }, \%options);
1157 :     # Read in the subsystems.
1158 :     my @subs = $sprout->GetAll(['Subsystem'], "ORDER BY Subsystem(classification), Subsystem(id)", [],
1159 :     ['Subsystem(classification)', 'Subsystem(id)']);
1160 : parrello 1.26 # Put any unclassified subsystems at the end. They will always be at the beginning, so if one
1161 :     # is at the end, ALL subsystems are unclassified and we don't bother.
1162 :     if ($#subs >= 0 && $subs[$#subs]->[0] ne '') {
1163 :     while ($subs[0]->[0] eq '') {
1164 :     my $classLess = shift @subs;
1165 :     push @subs, $classLess;
1166 :     }
1167 :     }
1168 : parrello 1.16 # Declare the return variable.
1169 :     my @retVal = ();
1170 :     # Each element in @subs represents a leaf node, so as we loop through it we will be
1171 :     # producing one leaf node at a time. The leaf node is represented as a 2-tuple. The
1172 :     # first element is a semi-colon-delimited list of the classifications for the
1173 :     # subsystem. There will be a stack of currently-active classifications, which we will
1174 :     # compare to the incoming classifications from the end backward. A new classification
1175 :     # requires starting a new branch. A different classification requires closing an old
1176 :     # branch and starting a new one. Each classification in the stack will also contain
1177 :     # that classification's current branch. We'll add a fake classification at the
1178 :     # beginning that we can use to represent the tree as a whole.
1179 :     my $rootName = '<root>';
1180 :     # Create the classification stack. Note the stack is a pair of parallel lists,
1181 :     # one containing names and the other containing content.
1182 :     my @stackNames = ($rootName);
1183 :     my @stackContents = (\@retVal);
1184 :     # Add a null entry at the end of the subsystem list to force an unrolling.
1185 : parrello 1.27 push @subs, ['', undef];
1186 : parrello 1.16 # Loop through the subsystems.
1187 :     for my $sub (@subs) {
1188 :     # Pull out the classification list and the subsystem ID.
1189 :     my ($classString, $id) = @{$sub};
1190 :     Trace("Processing class \"$classString\" and subsystem $id.") if T(4);
1191 :     # Convert the classification string to a list with the root classification in
1192 :     # the front.
1193 :     my @classList = ($rootName, split($FIG_Config::splitter, $classString));
1194 :     # Find the leftmost point at which the class list differs from the stack.
1195 :     my $matchPoint = 0;
1196 :     while ($matchPoint <= $#stackNames && $matchPoint <= $#classList &&
1197 :     $stackNames[$matchPoint] eq $classList[$matchPoint]) {
1198 :     $matchPoint++;
1199 :     }
1200 :     Trace("Match point is $matchPoint. Stack length is " . scalar(@stackNames) .
1201 :     ". Class List length is " . scalar(@classList) . ".") if T(4);
1202 :     # Unroll the stack to the matchpoint.
1203 :     while ($#stackNames >= $matchPoint) {
1204 :     my $popped = pop @stackNames;
1205 :     pop @stackContents;
1206 :     Trace("\"$popped\" popped from stack.") if T(4);
1207 :     }
1208 :     # Start branches for any new classifications.
1209 :     while ($#stackNames < $#classList) {
1210 :     # The branch for a new classification contains its radio button
1211 :     # data and then a list of children. So, at this point, if radio buttons
1212 :     # are desired, we put them into the content.
1213 :     my $newLevel = scalar(@stackNames);
1214 :     my @newClassContent = ();
1215 :     if ($optionThing->{radio}) {
1216 :     my $newClassString = join($FIG_Config::splitter, @classList[1..$newLevel]);
1217 :     push @newClassContent, { value => "classification=$newClassString%" };
1218 :     }
1219 :     # The new classification node is appended to its parent's content
1220 :     # and then pushed onto the stack. First, we need the node name.
1221 :     my $nodeName = $classList[$newLevel];
1222 :     # Add the classification to its parent. This makes it part of the
1223 :     # tree we'll be returning to the user.
1224 :     push @{$stackContents[$#stackNames]}, $nodeName, \@newClassContent;
1225 :     # Push the classification onto the stack.
1226 :     push @stackContents, \@newClassContent;
1227 :     push @stackNames, $nodeName;
1228 :     Trace("\"$nodeName\" pushed onto stack.") if T(4);
1229 :     }
1230 :     # Now the stack contains all our parent branches. We add the subsystem to
1231 :     # the branch at the top of the stack, but only if it's NOT the dummy node.
1232 :     if (defined $id) {
1233 :     # Compute the node name from the ID.
1234 :     my $nodeName = $id;
1235 :     $nodeName =~ s/_/ /g;
1236 :     # Create the node's leaf hash. This depends on the value of the radio
1237 :     # and link options.
1238 :     my $nodeContent = {};
1239 :     if ($optionThing->{links}) {
1240 :     # Compute the link value.
1241 :     my $linkable = uri_escape($id);
1242 :     $nodeContent->{link} = "../FIG/display_subsys.cgi?ssa_name=$linkable;request=show_ssa;sort=by_phylo;SPROUT=1";
1243 :     }
1244 :     if ($optionThing->{radio}) {
1245 :     # Compute the radio value.
1246 :     $nodeContent->{value} = "id=$id";
1247 :     }
1248 :     # Push the node into its parent branch.
1249 :     Trace("\"$nodeName\" added to node list.") if T(4);
1250 :     push @{$stackContents[$#stackNames]}, $nodeName, $nodeContent;
1251 :     }
1252 :     }
1253 :     # Return the result.
1254 :     return \@retVal;
1255 :     }
1256 :    
1257 :    
1258 : parrello 1.1 =head3 NmpdrGenomeMenu
1259 :    
1260 : parrello 1.3 C<< my $htmlText = $shelp->NmpdrGenomeMenu($menuName, $multiple, \@selected, $rows); >>
1261 : parrello 1.1
1262 :     This method creates a hierarchical HTML menu for NMPDR genomes organized by category. The
1263 :     category indicates the low-level NMPDR group. Organizing the genomes in this way makes it
1264 :     easier to select all genomes from a particular category.
1265 :    
1266 :     =over 4
1267 :    
1268 :     =item menuName
1269 :    
1270 :     Name to give to the menu.
1271 :    
1272 : parrello 1.3 =item multiple
1273 : parrello 1.1
1274 : parrello 1.3 TRUE if the user is allowed to select multiple genomes, else FALSE.
1275 : parrello 1.1
1276 :     =item selected
1277 :    
1278 :     Reference to a list containing the IDs of the genomes to be pre-selected. If the menu
1279 :     is not intended to allow multiple selections, the list should be a singleton. If the
1280 :     list is empty, nothing will be pre-selected.
1281 :    
1282 : parrello 1.3 =item rows (optional)
1283 :    
1284 :     Number of rows to display. If omitted, the default is 1 for a single-select list
1285 :     and 10 for a multi-select list.
1286 :    
1287 : parrello 1.8 =item crossMenu (optional)
1288 :    
1289 :     If specified, is presumed to be the name of another genome menu whose contents
1290 :     are to be mutually exclusive with the contents of this menu. As a result, instead
1291 :     of the standard onChange event, the onChange event will deselect any entries in
1292 :     the other menu.
1293 :    
1294 : parrello 1.1 =item RETURN
1295 :    
1296 :     Returns the HTML text to generate a C<SELECT> menu inside a form.
1297 :    
1298 :     =back
1299 :    
1300 :     =cut
1301 :    
1302 :     sub NmpdrGenomeMenu {
1303 :     # Get the parameters.
1304 : parrello 1.8 my ($self, $menuName, $multiple, $selected, $rows, $cross) = @_;
1305 : parrello 1.1 # Get the Sprout and CGI objects.
1306 :     my $sprout = $self->DB();
1307 :     my $cgi = $self->Q();
1308 : parrello 1.3 # Compute the row count.
1309 :     if (! defined $rows) {
1310 :     $rows = ($multiple ? 10 : 1);
1311 :     }
1312 :     # Create the multiple tag.
1313 :     my $multipleTag = ($multiple ? " multiple" : "");
1314 : parrello 1.1 # Get the form name.
1315 :     my $formName = $self->FormName();
1316 : parrello 1.3 # Check to see if we already have a genome list in memory.
1317 :     my $genomes = $self->{genomeList};
1318 :     my $groupHash;
1319 :     if (defined $genomes) {
1320 :     # We have a list ready to use.
1321 :     $groupHash = $genomes;
1322 :     } else {
1323 :     # Get a list of all the genomes in group order. In fact, we only need them ordered
1324 :     # by name (genus,species,strain), but putting primary-group in front enables us to
1325 :     # take advantage of an existing index.
1326 :     my @genomeList = $sprout->GetAll(['Genome'],
1327 :     "ORDER BY Genome(primary-group), Genome(genus), Genome(species), Genome(unique-characterization)",
1328 :     [], ['Genome(primary-group)', 'Genome(id)',
1329 :     'Genome(genus)', 'Genome(species)',
1330 :     'Genome(unique-characterization)']);
1331 :     # Create a hash to organize the genomes by group. Each group will contain a list of
1332 :     # 2-tuples, the first element being the genome ID and the second being the genome
1333 :     # name.
1334 :     my %gHash = ();
1335 :     for my $genome (@genomeList) {
1336 :     # Get the genome data.
1337 :     my ($group, $genomeID, $genus, $species, $strain) = @{$genome};
1338 : parrello 1.10 # Compute and cache its name and display group.
1339 :     my ($name, $displayGroup) = $self->SaveOrganismData($group, $genomeID, $genus, $species,
1340 :     $strain);
1341 :     # Push the genome into the group's list. Note that we use the real group
1342 :     # name here, not the display group name.
1343 : parrello 1.3 push @{$gHash{$group}}, [$genomeID, $name];
1344 : parrello 1.1 }
1345 : parrello 1.3 # Save the genome list for future use.
1346 :     $self->{genomeList} = \%gHash;
1347 :     $groupHash = \%gHash;
1348 : parrello 1.1 }
1349 :     # Now we are ready to unroll the menu out of the group hash. First, we sort the groups, putting
1350 :     # the supporting-genome group last.
1351 : parrello 1.3 my @groups = sort grep { $_ ne $FIG_Config::otherGroup } keys %{$groupHash};
1352 : parrello 1.1 push @groups, $FIG_Config::otherGroup;
1353 : parrello 1.3 # Next, create a hash that specifies the pre-selected entries. Note that we need to deal
1354 :     # with the possibility of undefined values in the incoming list.
1355 :     my %selectedHash = ();
1356 :     if (defined $selected) {
1357 :     %selectedHash = map { $_ => 1 } grep { defined($_) } @{$selected};
1358 :     }
1359 : parrello 1.13 # Now it gets complicated. We need a way to mark all the NMPDR genomes. We take advantage
1360 :     # of the fact they come first in the list. We'll accumulate a count of the NMPDR genomes
1361 :     # and use that to make the selections.
1362 :     my $nmpdrCount = 0;
1363 : parrello 1.1 # Create the type counters.
1364 :     my $groupCount = 1;
1365 :     # Compute the ID for the status display.
1366 :     my $divID = "${formName}_${menuName}_status";
1367 :     # Compute the JavaScript call for updating the status.
1368 :     my $showSelect = "showSelected($menuName, '$divID', 1000);";
1369 :     # If multiple selection is supported, create an onChange event.
1370 :     my $onChange = "";
1371 : parrello 1.8 if ($cross) {
1372 : parrello 1.13 # Here we have a paired menu. Selecting something in our menu unselects it in the
1373 :     # other and redisplays the status of both.
1374 : parrello 1.8 $onChange = " onChange=\"crossUnSelect($menuName, '$divID', $cross, '${formName}_${cross}_status', 1000)\"";
1375 :     } elsif ($multiple) {
1376 : parrello 1.13 # This is an unpaired menu, so all we do is redisplay our status.
1377 : parrello 1.1 $onChange = " onChange=\"$showSelect\"";
1378 :     }
1379 :     # Create the SELECT tag and stuff it into the output array.
1380 : parrello 1.13 my @lines = ("<SELECT name=\"$menuName\"$onChange$multipleTag size=\"$rows\">");
1381 : parrello 1.1 # Loop through the groups.
1382 :     for my $group (@groups) {
1383 :     # Create the option group tag.
1384 :     my $tag = "<OPTGROUP label=\"$group\">";
1385 :     push @lines, " $tag";
1386 :     # Get the genomes in the group.
1387 : parrello 1.3 for my $genome (@{$groupHash->{$group}}) {
1388 : parrello 1.13 # Count this organism if it's NMPDR.
1389 :     if ($group ne $FIG_Config::otherGroup) {
1390 :     $nmpdrCount++;
1391 :     }
1392 :     # Get the organism ID and name.
1393 : parrello 1.1 my ($genomeID, $name) = @{$genome};
1394 :     # See if it's selected.
1395 :     my $select = ($selectedHash{$genomeID} ? " selected" : "");
1396 :     # Generate the option tag.
1397 : parrello 1.13 my $optionTag = "<OPTION value=\"$genomeID\"$select>$name <em>($genomeID)</em></OPTION>";
1398 : parrello 1.1 push @lines, " $optionTag";
1399 :     }
1400 :     # Close the option group.
1401 :     push @lines, " </OPTGROUP>";
1402 :     }
1403 :     # Close the SELECT tag.
1404 :     push @lines, "</SELECT>";
1405 :     # Check for multiple selection.
1406 : parrello 1.3 if ($multiple) {
1407 : parrello 1.15 # Multi-select is on, so we need to add some selection helpers. First is
1408 :     # the search box. This allows the user to type text and have all genomes containing
1409 :     # the text selected automatically.
1410 :     my $searchThingName = "${menuName}_SearchThing";
1411 : parrello 1.18 push @lines, "<br />" .
1412 :     "<INPUT type=\"button\" name=\"Search\" class=\"button\" value=\"Select genomes containing\" onClick=\"selectViaSearch($menuName, $searchThingName); $showSelect\" />&nbsp;" .
1413 :     "<INPUT type=\"text\" name=\"$searchThingName\" size=\"30\" />";
1414 : parrello 1.15 # Next are the buttons to set and clear selections.
1415 : parrello 1.1 push @lines, "<br />";
1416 : parrello 1.15 push @lines, "<INPUT type=\"button\" name=\"ClearAll\" class=\"bigButton\" value=\"Clear All\" onClick=\"clearAll($menuName); $showSelect\" />";
1417 : parrello 1.1 push @lines, "<INPUT type=\"button\" name=\"SelectAll\" class=\"bigButton\" value=\"Select All\" onClick=\"selectAll($menuName); $showSelect\" />";
1418 : parrello 1.13 push @lines, "<INPUT type=\"button\" name=\"NMPDROnly\" class=\"bigButton\" value=\"Select NMPDR\" onClick=\"selectSome($menuName, $nmpdrCount, true); $showSelect\" />";
1419 :     push @lines, "<INPUT type=\"button\" name=\"OtherOnly\" class=\"bigButton\" value=\"Select Supporting\" onClick=\"selectSome($menuName, $nmpdrCount, false); $showSelect\" />";
1420 : parrello 1.1 # Add the status display, too.
1421 :     push @lines, "<DIV id=\"$divID\" class=\"selectStatus\"></DIV>";
1422 :     # Queue to update the status display when the form loads. We need to modify the show statement
1423 :     # slightly because the queued statements are executed outside the form. This may seem like a lot of
1424 :     # trouble, but we want all of the show statement calls to be generated from a single line of code,
1425 :     # in case we decide to twiddle the parameters.
1426 :     $showSelect =~ s/showSelected\(/showSelected\(thisForm\./;
1427 :     $self->QueueFormScript($showSelect);
1428 : parrello 1.3 # Finally, add this parameter to the list of genome parameters. This enables us to
1429 :     # easily find all the parameters used to select one or more genomes.
1430 :     push @{$self->{genomeParms}}, $menuName;
1431 : parrello 1.1 }
1432 :     # Assemble all the lines into a string.
1433 :     my $retVal = join("\n", @lines, "");
1434 :     # Return the result.
1435 :     return $retVal;
1436 :     }
1437 :    
1438 : parrello 1.3 =head3 PropertyMenu
1439 :    
1440 :     C<< my $htmlText = $shelp->PropertyMenu($menuName, $selected, $force); >>
1441 :    
1442 :     Generate a property name dropdown menu.
1443 :    
1444 :     =over 4
1445 :    
1446 :     =item menuName
1447 :    
1448 :     Name to give to the menu.
1449 :    
1450 :     =item selected
1451 :    
1452 :     Value of the property name to pre-select.
1453 :    
1454 :     =item force (optional)
1455 :    
1456 :     If TRUE, then the user will be forced to choose a property name. If FALSE,
1457 :     then an additional menu choice will be provided to select nothing.
1458 :    
1459 :     =item RETURN
1460 :    
1461 :     Returns a dropdown menu box that allows the user to select a property name. An additional
1462 :     selection entry will be provided for selecting no property name
1463 :    
1464 :     =back
1465 :    
1466 :     =cut
1467 :    
1468 :     sub PropertyMenu {
1469 :     # Get the parameters.
1470 :     my ($self, $menuName, $selected, $force) = @_;
1471 :     # Get the CGI and Sprout objects.
1472 :     my $sprout = $self->DB();
1473 :     my $cgi = $self->Q();
1474 :     # Create the property name list.
1475 :     my @propNames = ();
1476 :     if (! $force) {
1477 :     push @propNames, "";
1478 :     }
1479 :     # Get all the property names, putting them after the null choice if one exists.
1480 :     push @propNames, $sprout->GetChoices('Property', 'property-name');
1481 :     # Create a menu from them.
1482 :     my $retVal = $cgi->popup_menu(-name=> $menuName, -values => \@propNames,
1483 :     -default => $selected);
1484 :     # Return the result.
1485 :     return $retVal;
1486 :     }
1487 :    
1488 : parrello 1.1 =head3 MakeTable
1489 :    
1490 :     C<< my $htmlText = $shelp->MakeTable(\@rows); >>
1491 :    
1492 :     Create a table from a group of table rows. The table rows must be fully pre-formatted: in
1493 :     other words, each must have the TR and TD tags included.
1494 :    
1495 :     The purpose of this method is to provide a uniform look for search form tables. It is
1496 :     almost impossible to control a table using styles, so rather than have a table style,
1497 :     we create the TABLE tag in this method. Note also that the first TD or TH in each row will
1498 :     be updated with an explicit width so the forms look pretty when they are all on one
1499 :     page.
1500 :    
1501 :     =over 4
1502 :    
1503 :     =item rows
1504 :    
1505 :     Reference to a list of table rows. Each table row must be in HTML form with all
1506 :     the TR and TD tags set up. The first TD or TH tag in each row will be modified to
1507 :     set the width. Everything else will be left as is.
1508 :    
1509 :     =item RETURN
1510 :    
1511 :     Returns the full HTML for a table in the approved NMPDR Search Form style.
1512 :    
1513 :     =back
1514 :    
1515 :     =cut
1516 :    
1517 :     sub MakeTable {
1518 :     # Get the parameters.
1519 :     my ($self, $rows) = @_;
1520 :     # Get the CGI object.
1521 :     my $cgi = $self->Q();
1522 :     # Fix the widths on the first column. Note that we eschew the use of the "g"
1523 :     # modifier becase we only want to change the first tag. Also, if a width
1524 :     # is already specified on the first column bad things will happen.
1525 :     for my $row (@{$rows}) {
1526 :     $row =~ s/(<td|th)/$1 width="150"/i;
1527 :     }
1528 :     # Create the table.
1529 :     my $retVal = $cgi->table({border => 2, cellspacing => 2,
1530 :     width => 700, class => 'search'},
1531 :     @{$rows});
1532 :     # Return the result.
1533 :     return $retVal;
1534 :     }
1535 :    
1536 :     =head3 SubmitRow
1537 :    
1538 : parrello 1.18 C<< my $htmlText = $shelp->SubmitRow($caption); >>
1539 : parrello 1.1
1540 :     Returns the HTML text for the row containing the page size control
1541 :     and the submit button. All searches should have this row somewhere
1542 :     near the top of the form.
1543 :    
1544 : parrello 1.18 =over 4
1545 :    
1546 :     =item caption (optional)
1547 :    
1548 :     Caption to be put on the search button. The default is C<Go>.
1549 :    
1550 :     =item RETURN
1551 :    
1552 :     Returns a table row containing the controls for submitting the search
1553 :     and tuning the results.
1554 :    
1555 :     =back
1556 :    
1557 : parrello 1.1 =cut
1558 :    
1559 :     sub SubmitRow {
1560 :     # Get the parameters.
1561 : parrello 1.18 my ($self, $caption) = @_;
1562 : parrello 1.1 my $cgi = $self->Q();
1563 : parrello 1.18 # Compute the button caption.
1564 :     my $realCaption = (defined $caption ? $caption : 'Go');
1565 : parrello 1.3 # Get the current page size.
1566 :     my $pageSize = $cgi->param('PageSize');
1567 :     # Get the incoming external-link flag.
1568 :     my $aliases = ($cgi->param('ShowAliases') ? 1 : 0);
1569 :     # Create the row.
1570 : parrello 1.1 my $retVal = $cgi->Tr($cgi->td("Results/Page"),
1571 :     $cgi->td($cgi->popup_menu(-name => 'PageSize',
1572 : parrello 1.7 -values => [10, 25, 50, 100, 1000],
1573 : parrello 1.25 -default => $pageSize)),
1574 : parrello 1.1 $cgi->td($cgi->submit(-class => 'goButton',
1575 :     -name => 'Search',
1576 : parrello 1.18 -value => $realCaption)));
1577 : parrello 1.1 # Return the result.
1578 :     return $retVal;
1579 :     }
1580 : parrello 1.2
1581 :     =head3 FeatureFilterRows
1582 :    
1583 : parrello 1.27 C<< my $htmlText = $shelp->FeatureFilterRows(@subset); >>
1584 : parrello 1.2
1585 : parrello 1.11 This method creates table rows that can be used to filter features. The form
1586 :     values can be used to select features by genome using the B<FeatureQuery>
1587 :     object.
1588 : parrello 1.2
1589 : parrello 1.27 =over 4
1590 :    
1591 :     =item subset
1592 :    
1593 :     List of rows to display. The default (C<all>) is to display all rows.
1594 :     C<words> displays the word search box, C<subsys> displays the subsystem
1595 :     selector, and C<options> displays the options row.
1596 :    
1597 :     =item RETURN
1598 :    
1599 :     Returns the html text for table rows containing the desired feature filtering controls.
1600 :    
1601 :     =back
1602 :    
1603 : parrello 1.2 =cut
1604 :    
1605 :     sub FeatureFilterRows {
1606 :     # Get the parameters.
1607 : parrello 1.27 my ($self, @subset) = @_;
1608 :     if (@subset == 0 || $subset[0] eq 'all') {
1609 :     @subset = qw(words subsys options);
1610 :     }
1611 : parrello 1.2 # Return the result.
1612 : parrello 1.27 return FeatureQuery::FilterRows($self, @subset);
1613 : parrello 1.2 }
1614 :    
1615 : parrello 1.1 =head3 GBrowseFeatureURL
1616 :    
1617 :     C<< my $url = SearchHelper::GBrowseFeatureURL($sprout, $feat); >>
1618 :    
1619 :     Compute the URL required to pull up a Gbrowse page for the the specified feature.
1620 :     In order to do this, we need to pull out the ID of the feature's Genome, its
1621 :     contig ID, and some rough starting and stopping offsets.
1622 :    
1623 :     =over 4
1624 :    
1625 :     =item sprout
1626 :    
1627 :     Sprout object for accessing the database.
1628 :    
1629 :     =item feat
1630 :    
1631 :     ID of the feature whose Gbrowse URL is desired.
1632 :    
1633 :     =item RETURN
1634 :    
1635 :     Returns a GET-style URL for the Gbrowse CGI, with parameters specifying the genome
1636 :     ID, contig ID, starting offset, and stopping offset.
1637 :    
1638 :     =back
1639 :    
1640 :     =cut
1641 :    
1642 :     sub GBrowseFeatureURL {
1643 :     # Get the parameters.
1644 :     my ($sprout, $feat) = @_;
1645 :     # Declare the return variable.
1646 :     my $retVal;
1647 :     # Compute the genome ID.
1648 :     my ($genomeID) = FIGRules::ParseFeatureID($feat);
1649 :     # Only proceed if the feature ID produces a valid genome.
1650 :     if ($genomeID) {
1651 :     # Get the feature location string.
1652 :     my $loc = $sprout->FeatureLocation($feat);
1653 :     # Compute the contig, start, and stop points.
1654 : parrello 1.6 my($contig, $start, $stop) = BasicLocation::Parse($loc);
1655 : parrello 1.5 Trace("Start and stop are ($start,$stop) on contig $contig.") if T(3);
1656 : parrello 1.1 # Now we need to do some goofiness to insure that the location is not too
1657 :     # big and that we get some surrounding stuff.
1658 :     my $mid = int(($start + $stop) / 2);
1659 :     my $chunk_len = 20000;
1660 :     my $max_feature = 40000;
1661 :     my $feat_len = abs($stop - $start);
1662 :     if ($feat_len > $chunk_len) {
1663 :     if ($feat_len > $max_feature) {
1664 :     $chunk_len = $max_feature;
1665 :     } else {
1666 :     $chunk_len = $feat_len + 100;
1667 :     }
1668 :     }
1669 :     my($show_start, $show_stop);
1670 :     if ($chunk_len == $max_feature) {
1671 :     $show_start = $start - 300;
1672 :     } else {
1673 :     $show_start = $mid - int($chunk_len / 2);
1674 :     }
1675 :     if ($show_start < 1) {
1676 :     $show_start = 1;
1677 :     }
1678 :     $show_stop = $show_start + $chunk_len - 1;
1679 :     my $clen = $sprout->ContigLength($contig);
1680 :     if ($show_stop > $clen) {
1681 :     $show_stop = $clen;
1682 :     }
1683 :     my $seg_id = $contig;
1684 :     $seg_id =~ s/:/--/g;
1685 : parrello 1.5 Trace("Show limits are ($show_start,$show_stop) in genome $genomeID with ref $seg_id.") if T(3);
1686 : parrello 1.1 # Assemble all the pieces.
1687 : parrello 1.18 $retVal = "gbrowse.cgi/GB_$genomeID?ref=$seg_id;start=$show_start;stop=$show_stop";
1688 : parrello 1.1 }
1689 :     # Return the result.
1690 :     return $retVal;
1691 :     }
1692 :    
1693 : parrello 1.3 =head3 GetGenomes
1694 :    
1695 :     C<< my @genomeList = $shelp->GetGenomes($parmName); >>
1696 :    
1697 :     Return the list of genomes specified by the specified CGI query parameter.
1698 :     If the request method is POST, then the list of genome IDs is returned
1699 :     without preamble. If the request method is GET and the parameter is not
1700 :     specified, then it is treated as a request for all genomes. This makes it
1701 :     easier for web pages to link to a search that wants to specify all genomes.
1702 :    
1703 :     =over 4
1704 :    
1705 :     =item parmName
1706 :    
1707 :     Name of the parameter containing the list of genomes. This will be the
1708 :     first parameter passed to the L</NmpdrGenomeMenu> call that created the
1709 :     genome selection control on the form.
1710 :    
1711 :     =item RETURN
1712 :    
1713 :     Returns a list of the genomes to process.
1714 :    
1715 :     =back
1716 :    
1717 :     =cut
1718 :    
1719 :     sub GetGenomes {
1720 :     # Get the parameters.
1721 :     my ($self, $parmName) = @_;
1722 :     # Get the CGI query object.
1723 :     my $cgi = $self->Q();
1724 :     # Get the list of genome IDs in the request header.
1725 :     my @retVal = $cgi->param($parmName);
1726 :     Trace("Genome list for $parmName is (" . join(", ", @retVal) . ") with method " . $cgi->request_method() . ".") if T(3);
1727 :     # Check for the special GET case.
1728 :     if ($cgi->request_method() eq "GET" && ! @retVal) {
1729 :     # Here the caller wants all the genomes.
1730 :     my $sprout = $self->DB();
1731 :     @retVal = $sprout->Genomes();
1732 :     }
1733 :     # Return the result.
1734 :     return @retVal;
1735 :     }
1736 :    
1737 :     =head3 GetHelpText
1738 :    
1739 :     C<< my $htmlText = $shelp->GetHelpText(); >>
1740 :    
1741 :     Get the help text for this search. The help text is stored in files on the template
1742 :     server. The help text for a specific search is taken from a file named
1743 :     C<SearchHelp_>I<class>C<.inc> in the template directory C<$FIG_Config::template_url>.
1744 :     There are also three standard help files: C<SearchHelp1_Filtering.inc> describes the
1745 :     feature filtering performed by the B<FeatureQuery> object, C<SearchHelp1_GenomeControl.inc>
1746 :     describes how to use a multiple-selection genome control, and C<SearchHelp1_Standard.inc>
1747 :     describes the standard controls for a search, such as page size, URL display, and
1748 :     external alias display.
1749 :    
1750 :     =cut
1751 :    
1752 :     sub GetHelpText {
1753 :     # Get the parameters.
1754 :     my ($self) = @_;
1755 :     # Create a list to hold the pieces of the help.
1756 :     my @helps = ();
1757 :     # Get the template directory URL.
1758 :     my $urlBase = $FIG_Config::template_url;
1759 :     # Start with the specific help.
1760 :     my $class = $self->{class};
1761 :     push @helps, PageBuilder::GetPage("$urlBase/SearchHelp_$class.inc");
1762 :     # Add the genome control help if needed.
1763 :     if (scalar @{$self->{genomeParms}}) {
1764 :     push @helps, PageBuilder::GetPage("$urlBase/SearchHelp1_GenomeControl.inc");
1765 :     }
1766 :     # Next the filter help.
1767 :     if ($self->{filtered}) {
1768 :     push @helps, PageBuilder::GetPage("$urlBase/SearchHelp1_Filtering.inc");
1769 :     }
1770 :     # Finally, the standard help.
1771 :     push @helps, PageBuilder::GetPage("$urlBase/SearchHelp1_Standard.inc");
1772 :     # Assemble the pieces.
1773 :     my $retVal = join("\n<p>&nbsp;</p>\n", @helps);
1774 :     # Return the result.
1775 :     return $retVal;
1776 :     }
1777 :    
1778 :     =head3 ComputeSearchURL
1779 :    
1780 : parrello 1.19 C<< my $url = $shelp->ComputeSearchURL(%overrides); >>
1781 : parrello 1.3
1782 :     Compute the GET-style URL for the current search. In order for this to work, there
1783 :     must be a copy of the search form on the current page. This will always be the
1784 :     case if the search is coming from C<SearchSkeleton.cgi>.
1785 :    
1786 :     A little expense is involved in order to make the URL as smart as possible. The
1787 :     main complication is that if the user specified all genomes, we'll want to
1788 :     remove the parameter entirely from a get-style URL.
1789 :    
1790 : parrello 1.19 =over 4
1791 :    
1792 :     =item overrides
1793 :    
1794 :     Hash containing override values for the parameters, where the parameter name is
1795 :     the key and the parameter value is the override value. If the override value is
1796 :     C<undef>, the parameter will be deleted from the result.
1797 :    
1798 :     =item RETURN
1799 :    
1800 :     Returns a GET-style URL for invoking the search with the specified overrides.
1801 :    
1802 :     =back
1803 :    
1804 : parrello 1.3 =cut
1805 :    
1806 :     sub ComputeSearchURL {
1807 :     # Get the parameters.
1808 : parrello 1.19 my ($self, %overrides) = @_;
1809 : parrello 1.3 # Get the database and CGI query object.
1810 :     my $cgi = $self->Q();
1811 :     my $sprout = $self->DB();
1812 :     # Start with the full URL.
1813 :     my $retVal = $cgi->url(-full => 1);
1814 :     # Get all the query parameters in a hash.
1815 :     my %parms = $cgi->Vars();
1816 :     # Now we need to do some fixing. Each multi-valued parameter is encoded as a string with null
1817 :     # characters separating the individual values. We have to convert those to lists. In addition,
1818 :     # the multiple-selection genome parameters and the feature type parameter must be checked to
1819 :     # determine whether or not they can be removed from the URL. First, we get a list of the
1820 :     # genome parameters and a list of all genomes. Note that we only need the list if a
1821 :     # multiple-selection genome parameter has been found on the form.
1822 :     my %genomeParms = map { $_ => 1 } @{$self->{genomeParms}};
1823 :     my @genomeList;
1824 :     if (keys %genomeParms) {
1825 :     @genomeList = $sprout->Genomes();
1826 :     }
1827 :     # Create a list to hold the URL parameters we find.
1828 :     my @urlList = ();
1829 :     # Now loop through the parameters in the hash, putting them into the output URL.
1830 :     for my $parmKey (keys %parms) {
1831 :     # Get a list of the parameter values. If there's only one, we'll end up with
1832 :     # a singleton list, but that's okay.
1833 :     my @values = split (/\0/, $parms{$parmKey});
1834 :     # Check for special cases.
1835 : parrello 1.26 if (grep { $_ eq $parmKey } qw(SessionID ResultCount Page PageSize Trace TF)) {
1836 : parrello 1.3 # These are bookkeeping parameters we don't need to start a search.
1837 :     @values = ();
1838 :     } elsif ($parmKey =~ /_SearchThing$/) {
1839 :     # Here the value coming in is from a genome control's search thing. It does
1840 :     # not affect the results of the search, so we clear it.
1841 :     @values = ();
1842 :     } elsif ($genomeParms{$parmKey}) {
1843 :     # Here we need to see if the user wants all the genomes. If he does,
1844 :     # we erase all the values just like with features.
1845 :     my $allFlag = $sprout->IsAllGenomes(\@values, \@genomeList);
1846 :     if ($allFlag) {
1847 :     @values = ();
1848 :     }
1849 : parrello 1.19 } elsif (exists $overrides{$parmKey}) {
1850 :     # Here the value is being overridden, so we skip it for now.
1851 :     @values = ();
1852 : parrello 1.3 }
1853 :     # If we still have values, create the URL parameters.
1854 :     if (@values) {
1855 :     push @urlList, map { "$parmKey=" . uri_escape($_) } @values;
1856 :     }
1857 :     }
1858 : parrello 1.19 # Now do the overrides.
1859 :     for my $overKey (keys %overrides) {
1860 :     # Only use this override if it's not a delete marker.
1861 :     if (defined $overrides{$overKey}) {
1862 :     push @urlList, "$overKey=" . uri_escape($overrides{$overKey});
1863 :     }
1864 :     }
1865 : parrello 1.3 # Add the parameters to the URL.
1866 :     $retVal .= "?" . join(";", @urlList);
1867 :     # Return the result.
1868 :     return $retVal;
1869 :     }
1870 :    
1871 :     =head3 GetRunTimeValue
1872 :    
1873 :     C<< my $htmlText = $shelp->GetRunTimeValue($text); >>
1874 :    
1875 :     Compute a run-time column value.
1876 :    
1877 :     =over 4
1878 :    
1879 :     =item text
1880 :    
1881 :     The run-time column text. It consists of 2 percent signs, a column type, an equal
1882 :     sign, and the data for the current row.
1883 :    
1884 :     =item RETURN
1885 :    
1886 :     Returns the fully-formatted HTML text to go into the current column of the current row.
1887 :    
1888 :     =back
1889 :    
1890 :     =cut
1891 :    
1892 :     sub GetRunTimeValue {
1893 :     # Get the parameters.
1894 :     my ($self, $text) = @_;
1895 :     # Declare the return variable.
1896 :     my $retVal;
1897 :     # Parse the incoming text.
1898 :     if ($text =~ /^%%([^=]+)=(.*)$/) {
1899 :     $retVal = $self->RunTimeColumns($1, $2);
1900 :     } else {
1901 :     Confess("Invalid run-time column string \"$text\" encountered in session file.");
1902 :     }
1903 :     # Return the result.
1904 :     return $retVal;
1905 :     }
1906 :    
1907 : parrello 1.9 =head3 AdvancedClassList
1908 :    
1909 :     C<< my @classes = SearchHelper::AdvancedClassList(); >>
1910 :    
1911 :     Return a list of advanced class names. This list is used to generate the directory
1912 :     of available searches on the search page.
1913 :    
1914 : parrello 1.15 We use the %INC variable to accomplish this.
1915 : parrello 1.9
1916 :     =cut
1917 :    
1918 :     sub AdvancedClassList {
1919 : parrello 1.15 my @retVal = map { $_ =~ /^SH(\w+)\.pm/; $1 } grep { $_ =~ /^SH/ } keys %INC;
1920 :     return @retVal;
1921 : parrello 1.9 }
1922 :    
1923 : parrello 1.16 =head3 SelectionTree
1924 :    
1925 :     C<< my $htmlText = SearchHelper::SelectionTree($cgi, \%tree, %options); >>
1926 :    
1927 :     Display a selection tree.
1928 :    
1929 :     This method creates the HTML for a tree selection control. The tree is implemented as a set of
1930 :     nested HTML unordered lists. Each selectable element of the tree will contain a radio button. In
1931 :     addition, some of the tree nodes can contain hyperlinks.
1932 :    
1933 :     The tree itself is passed in as a multi-level list containing node names followed by
1934 :     contents. Each content element is a reference to a similar list. The first element of
1935 :     each list may be a hash reference. If so, it should contain one or both of the following
1936 :     keys.
1937 :    
1938 :     =over 4
1939 :    
1940 :     =item link
1941 :    
1942 :     The navigation URL to be popped up if the user clicks on the node name.
1943 :    
1944 :     =item value
1945 :    
1946 :     The form value to be returned if the user selects the tree node.
1947 :    
1948 :     =back
1949 :    
1950 :     The presence of a C<link> key indicates the node name will be hyperlinked. The presence of
1951 :     a C<value> key indicates the node name will have a radio button. If a node has no children,
1952 :     you may pass it a hash reference instead of a list reference.
1953 :    
1954 :     The following example shows the hash for a three-level tree with links on the second level and
1955 :     radio buttons on the third.
1956 :    
1957 :     [ Objects => [
1958 :     Entities => [
1959 :     {link => "../docs/WhatIsAnEntity.html"},
1960 :     Genome => {value => 'GenomeData'},
1961 :     Feature => {value => 'FeatureData'},
1962 :     Contig => {value => 'ContigData'},
1963 :     ],
1964 :     Relationships => [
1965 :     {link => "../docs/WhatIsARelationShip.html"},
1966 :     HasFeature => {value => 'GenomeToFeature'},
1967 :     IsOnContig => {value => 'FeatureToContig'},
1968 :     ]
1969 :     ]
1970 :     ]
1971 :    
1972 :     Note how each leaf of the tree has a hash reference for its value, while the branch nodes
1973 :     all have list references.
1974 :    
1975 :     This next example shows how to set up a taxonomy selection field. The value returned
1976 :     by the tree control will be the taxonomy string for the selected node ready for use
1977 :     in a LIKE-style SQL filter. Only the single branch ending in campylobacter is shown for
1978 :     reasons of space.
1979 :    
1980 :     [ All => [
1981 :     {value => "%"},
1982 :     Bacteria => [
1983 :     {value => "Bacteria%"},
1984 :     Proteobacteria => [
1985 :     {value => "Bacteria; Proteobacteria%"},
1986 :     Epsilonproteobacteria => [
1987 :     {value => "Bacteria; Proteobacteria;Epsilonproteobacteria%"},
1988 :     Campylobacterales => [
1989 :     {value => "Bacteria; Proteobacteria; Epsilonproteobacteria; Campylobacterales%"},
1990 :     Campylobacteraceae =>
1991 :     {value => "Bacteria; Proteobacteria; Epsilonproteobacteria; Campylobacterales; Campylobacteraceae%"},
1992 :     ...
1993 :     ]
1994 :     ...
1995 :     ]
1996 :     ...
1997 :     ]
1998 :     ...
1999 :     ]
2000 :     ...
2001 :     ]
2002 :     ]
2003 :    
2004 :    
2005 :     This method of tree storage allows the caller to control the order in which the tree nodes
2006 :     are displayed and to completely control value selection and use of hyperlinks. It is, however
2007 :     a bit complicated. Eventually, tree-building classes will be provided to simplify things.
2008 :    
2009 :     The parameters to this method are as follows.
2010 :    
2011 :     =over 4
2012 :    
2013 :     =item cgi
2014 :    
2015 :     CGI object used to generate the HTML.
2016 :    
2017 :     =item tree
2018 :    
2019 :     Reference to a hash describing a tree. See the description above.
2020 :    
2021 :     =item options
2022 :    
2023 :     Hash containing options for the tree display.
2024 :    
2025 :     =back
2026 :    
2027 :     The allowable options are as follows
2028 :    
2029 :     =over 4
2030 :    
2031 :     =item nodeImageClosed
2032 :    
2033 :     URL of the image to display next to the tree nodes when they are collapsed. Clicking
2034 :     on the image will expand a section of the tree. The default is C<../FIG/Html/plus.gif>.
2035 :    
2036 :     =item nodeImageOpen
2037 :    
2038 :     URL of the image to display next to the tree nodes when they are expanded. Clicking
2039 :     on the image will collapse a section of the tree. The default is C<../FIG/Html/minus.gif>.
2040 :    
2041 :     =item style
2042 :    
2043 :     Style to use for the tree. The default is C<tree>. Because the tree style is implemented
2044 :     as nested lists, the key components of this style are the definitions for the C<ul> and
2045 :     C<li> tags. The default style file contains the following definitions.
2046 :    
2047 :     .tree ul {
2048 :     margin-left: 0; padding-left: 22px
2049 :     }
2050 :     .tree li {
2051 :     list-style-type: none;
2052 :     }
2053 :    
2054 :     The default image is 22 pixels wide, so in the above scheme each tree level is indented from its
2055 :     parent by the width of the node image. This use of styles limits the things we can do in formatting
2056 :     the tree, but it has the advantage of vastly simplifying the tree creation.
2057 :    
2058 :     =item name
2059 :    
2060 :     Field name to give to the radio buttons in the tree. The default is C<selection>.
2061 :    
2062 :     =item target
2063 :    
2064 :     Frame target for links. The default is C<_self>.
2065 :    
2066 :     =item selected
2067 :    
2068 :     If specified, the value of the radio button to be pre-selected.
2069 :    
2070 :     =back
2071 :    
2072 :     =cut
2073 :    
2074 :     sub SelectionTree {
2075 :     # Get the parameters.
2076 :     my ($cgi, $tree, %options) = @_;
2077 :     # Get the options.
2078 :     my $optionThing = Tracer::GetOptions({ name => 'selection',
2079 :     nodeImageClosed => '../FIG/Html/plus.gif',
2080 :     nodeImageOpen => '../FIG/Html/minus.gif',
2081 :     style => 'tree',
2082 :     target => '_self',
2083 :     selected => undef},
2084 :     \%options);
2085 :     # Declare the return variable. We'll do the standard thing with creating a list
2086 :     # of HTML lines and rolling them together at the end.
2087 :     my @retVal = ();
2088 :     # Only proceed if the tree is present.
2089 :     if (defined($tree)) {
2090 :     # Validate the tree.
2091 :     if (ref $tree ne 'ARRAY') {
2092 :     Confess("Selection tree is not a list reference.");
2093 :     } elsif (scalar @{$tree} == 0) {
2094 :     # The tree is empty, so we do nothing.
2095 :     } elsif ($tree->[0] eq 'HASH') {
2096 :     Confess("Hash reference found at start of selection tree. The tree as a whole cannot have attributes, only tree nodes.");
2097 :     } else {
2098 :     # Here we have a real tree. Apply the tree style.
2099 :     push @retVal, $cgi->start_div({ class => $optionThing->{style} });
2100 :     # Give us a DIV ID.
2101 :     my $divID = GetDivID($optionThing->{name});
2102 :     # Show the tree.
2103 :     push @retVal, ShowBranch($cgi, "(root)", $divID, $tree, $optionThing, 'block');
2104 :     # Close the DIV block.
2105 :     push @retVal, $cgi->end_div();
2106 :     }
2107 :     }
2108 :     # Return the result.
2109 :     return join("\n", @retVal, "");
2110 :     }
2111 :    
2112 :     =head3 ShowBranch
2113 :    
2114 :     C<< my @htmlLines = SearchHelper::ShowBranch($cgi, $label, $id, $branch, $options, $displayType); >>
2115 :    
2116 :     This is a recursive method that displays a branch of the tree.
2117 :    
2118 :     =over 4
2119 :    
2120 :     =item cgi
2121 :    
2122 :     CGI object used to format HTML.
2123 :    
2124 :     =item label
2125 :    
2126 :     Label of this tree branch. It is only used in error messages.
2127 :    
2128 :     =item id
2129 :    
2130 :     ID to be given to this tree branch. The ID is used in the code that expands and collapses
2131 :     tree nodes.
2132 :    
2133 :     =item branch
2134 :    
2135 :     Reference to a list containing the content of the tree branch. The list contains an optional
2136 :     hash reference that is ignored and the list of children, each child represented by a name
2137 :     and then its contents. The contents could by a hash reference (indicating the attributes
2138 :     of a leaf node), or another tree branch.
2139 :    
2140 :     =item options
2141 :    
2142 :     Options from the original call to L</SelectionTree>.
2143 :    
2144 :     =item displayType
2145 :    
2146 :     C<block> if the contents of this list are to be displayed, C<none> if they are to be
2147 :     hidden.
2148 :    
2149 :     =item RETURN
2150 :    
2151 :     Returns one or more HTML lines that can be used to display the tree branch.
2152 :    
2153 :     =back
2154 :    
2155 :     =cut
2156 :    
2157 :     sub ShowBranch {
2158 :     # Get the parameters.
2159 :     my ($cgi, $label, $id, $branch, $options, $displayType) = @_;
2160 :     # Declare the return variable.
2161 :     my @retVal = ();
2162 :     # Start the branch.
2163 :     push @retVal, $cgi->start_ul({ id => $id, style => "display:$displayType" });
2164 :     # Check for the hash and choose the start location accordingly.
2165 :     my $i0 = (ref $branch->[0] eq 'HASH' ? 1 : 0);
2166 :     # Get the list length.
2167 :     my $i1 = scalar(@{$branch});
2168 :     # Verify we have an even number of elements.
2169 :     if (($i1 - $i0) % 2 != 0) {
2170 :     Trace("Branch elements are from $i0 to $i1.") if T(3);
2171 :     Confess("Odd number of elements in tree branch $label.");
2172 :     } else {
2173 :     # Loop through the elements.
2174 :     for (my $i = $i0; $i < $i1; $i += 2) {
2175 :     # Get this node's label and contents.
2176 :     my ($myLabel, $myContent) = ($branch->[$i], $branch->[$i+1]);
2177 :     # Get an ID for this node's children (if any).
2178 :     my $myID = GetDivID($options->{name});
2179 :     # Now we need to find the list of children and the options hash.
2180 :     # This is a bit ugly because we allow the shortcut of a hash without an
2181 :     # enclosing list. First, we need some variables.
2182 :     my $attrHash = {};
2183 :     my @childHtml = ();
2184 :     my $hasChildren = 0;
2185 :     if (! ref $myContent) {
2186 :     Confess("Invalid tree definition. Scalar found as content of node \"$myLabel\".");
2187 :     } elsif (ref $myContent eq 'HASH') {
2188 :     # Here the node is a leaf and its content contains the link/value hash.
2189 :     $attrHash = $myContent;
2190 :     } elsif (ref $myContent eq 'ARRAY') {
2191 :     # Here the node may be a branch. Its content is a list.
2192 :     my $len = scalar @{$myContent};
2193 :     if ($len >= 1) {
2194 :     # Here the first element of the list could by the link/value hash.
2195 :     if (ref $myContent->[0] eq 'HASH') {
2196 :     $attrHash = $myContent->[0];
2197 :     # If there's data in the list besides the hash, it's our child list.
2198 :     # We can pass the entire thing as the child list, because the hash
2199 :     # is ignored.
2200 :     if ($len > 1) {
2201 :     $hasChildren = 1;
2202 :     }
2203 :     } else {
2204 :     $hasChildren = 1;
2205 :     }
2206 :     # If we have children, create the child list with a recursive call.
2207 :     if ($hasChildren) {
2208 :     Trace("Processing children of $myLabel.") if T(4);
2209 :     push @childHtml, ShowBranch($cgi, $myLabel, $myID, $myContent, $options, 'none');
2210 : parrello 1.27 Trace("Children of $myLabel finished.") if T(4);
2211 : parrello 1.16 }
2212 :     }
2213 :     }
2214 :     # Okay, it's time to pause and take stock. We have the label of the current node
2215 :     # in $myLabel, its attributes in $attrHash, and if it is NOT a leaf node, we
2216 :     # have a child list in @childHtml. If it IS a leaf node, $hasChildren is 0.
2217 :     # Compute the image HTML. It's tricky, because we have to deal with the open and
2218 :     # closed images.
2219 :     my @images = ($options->{nodeImageOpen}, $options->{nodeImageClosed});
2220 :     my $image = $images[$hasChildren];
2221 :     my $prefixHtml = $cgi->img({src => $image, id => "${myID}img"});
2222 :     if ($hasChildren) {
2223 :     # If there are children, we wrap the image in a toggle hyperlink.
2224 :     $prefixHtml = $cgi->a({ onClick => "javascript:treeToggle('$myID','$images[0]', '$images[1]')" },
2225 :     $prefixHtml);
2226 :     }
2227 :     # Now the radio button, if any. Note we use "defined" in case the user wants the
2228 :     # value to be 0.
2229 :     if (defined $attrHash->{value}) {
2230 :     # Due to a glitchiness in the CGI stuff, we have to build the attribute
2231 :     # hash for the "input" method. If the item is pre-selected, we add
2232 :     # "checked => undef" to the hash. Otherwise, we can't have "checked"
2233 :     # at all.
2234 :     my $radioParms = { type => 'radio',
2235 :     name => $options->{name},
2236 :     value => $attrHash->{value},
2237 :     };
2238 :     if (defined $options->{selected} && $options->{selected} eq $attrHash->{value}) {
2239 :     $radioParms->{checked} = undef;
2240 :     }
2241 :     $prefixHtml .= $cgi->input($radioParms);
2242 :     }
2243 :     # Next, we format the label.
2244 :     my $labelHtml = $myLabel;
2245 : parrello 1.27 Trace("Formatting tree node for \"$myLabel\".") if T(4);
2246 : parrello 1.16 # Apply a hyperlink if necessary.
2247 :     if (defined $attrHash->{link}) {
2248 :     $labelHtml = $cgi->a({ href => $attrHash->{link}, target => $options->{target} },
2249 :     $labelHtml);
2250 :     }
2251 :     # Finally, roll up the child HTML. If there are no children, we'll get a null string
2252 :     # here.
2253 :     my $childHtml = join("\n", @childHtml);
2254 :     # Now we have all the pieces, so we can put them together.
2255 :     push @retVal, $cgi->li("$prefixHtml$labelHtml$childHtml");
2256 :     }
2257 :     }
2258 :     # Close the tree branch.
2259 :     push @retVal, $cgi->end_ul();
2260 :     # Return the result.
2261 :     return @retVal;
2262 :     }
2263 :    
2264 :     =head3 GetDivID
2265 :    
2266 :     C<< my $idString = SearchHelper::GetDivID($name); >>
2267 :    
2268 :     Return a new HTML ID string.
2269 :    
2270 :     =over 4
2271 :    
2272 :     =item name
2273 :    
2274 :     Name to be prefixed to the ID string.
2275 :    
2276 :     =item RETURN
2277 :    
2278 :     Returns a hopefully-unique ID string.
2279 :    
2280 :     =back
2281 :    
2282 :     =cut
2283 :    
2284 :     sub GetDivID {
2285 :     # Get the parameters.
2286 :     my ($name) = @_;
2287 :     # Compute the ID.
2288 :     my $retVal = "elt_$name$divCount";
2289 :     # Increment the counter to make sure this ID is not re-used.
2290 :     $divCount++;
2291 :     # Return the result.
2292 :     return $retVal;
2293 :     }
2294 :    
2295 : parrello 1.1 =head2 Feature Column Methods
2296 :    
2297 : parrello 1.19 The methods in this section manage feature column data. If you want to provide the
2298 : parrello 1.1 capability to include new types of data in feature columns, then all the changes
2299 :     are made to this section of the source file. Technically, this should be implemented
2300 :     using object-oriented methods, but this is simpler for non-programmers to maintain.
2301 :     To add a new column of feature data, you must first give it a name. For example,
2302 :     the name for the protein page link column is C<protlink>. If the column is to appear
2303 :     in the default list of feature columns, add it to the list returned by
2304 :     L</DefaultFeatureColumns>. Then add code to produce the column title to
2305 :     L</FeatureColumnTitle> and code to produce its value to L</FeatureColumnValue>, and
2306 :     everything else will happen automatically.
2307 :    
2308 :     There is one special column name syntax for extra columns (that is, nonstandard
2309 :     feature columns). If the column name begins with C<X=>, then it is presumed to be
2310 :     an extra column. The column title is the text after the C<X=>, and its value is
2311 :     pulled from the extra column hash.
2312 :    
2313 :     =head3 DefaultFeatureColumns
2314 :    
2315 : parrello 1.14 C<< my @colNames = $shelp->DefaultFeatureColumns(); >>
2316 : parrello 1.1
2317 : parrello 1.14 Return a list of the default feature column identifiers. These identifiers can
2318 :     be passed to L</FeatureColumnTitle> and L</FeatureColumnValue> in order to
2319 :     produce the column titles and row values.
2320 : parrello 1.1
2321 :     =cut
2322 :    
2323 :     sub DefaultFeatureColumns {
2324 :     # Get the parameters.
2325 :     my ($self) = @_;
2326 :     # Return the result.
2327 : parrello 1.14 return qw(orgName function gblink protlink);
2328 : parrello 1.1 }
2329 :    
2330 :     =head3 FeatureColumnTitle
2331 :    
2332 :     C<< my $title = $shelp->FeatureColumnTitle($colName); >>
2333 :    
2334 :     Return the column heading title to be used for the specified feature column.
2335 :    
2336 :     =over 4
2337 :    
2338 :     =item name
2339 :    
2340 :     Name of the desired feature column.
2341 :    
2342 :     =item RETURN
2343 :    
2344 :     Returns the title to be used as the column header for the named feature column.
2345 :    
2346 :     =back
2347 :    
2348 :     =cut
2349 :    
2350 :     sub FeatureColumnTitle {
2351 :     # Get the parameters.
2352 :     my ($self, $colName) = @_;
2353 :     # Declare the return variable. We default to a blank column name.
2354 :     my $retVal = "&nbsp;";
2355 :     # Process the column name.
2356 :     if ($colName =~ /^X=(.+)$/) {
2357 :     # Here we have an extra column.
2358 :     $retVal = $1;
2359 : parrello 1.13 } elsif ($colName eq 'alias') {
2360 :     $retVal = "External Aliases";
2361 : parrello 1.1 } elsif ($colName eq 'fid') {
2362 :     $retVal = "FIG ID";
2363 :     } elsif ($colName eq 'function') {
2364 :     $retVal = "Functional Assignment";
2365 :     } elsif ($colName eq 'gblink') {
2366 :     $retVal = "GBrowse";
2367 : parrello 1.13 } elsif ($colName eq 'group') {
2368 :     $retVal = "NMDPR Group";
2369 :     } elsif ($colName =~ /^keyword:(.+)$/) {
2370 :     $retVal = ucfirst $1;
2371 :     } elsif ($colName eq 'orgName') {
2372 : parrello 1.21 $retVal = "Organism and Gene ID";
2373 : parrello 1.1 } elsif ($colName eq 'protlink') {
2374 :     $retVal = "NMPDR Protein Page";
2375 : parrello 1.13 } elsif ($colName eq 'subsystem') {
2376 :     $retVal = "Subsystems";
2377 : parrello 1.1 }
2378 :     # Return the result.
2379 :     return $retVal;
2380 :     }
2381 :    
2382 : parrello 1.13
2383 : parrello 1.1 =head3 FeatureColumnValue
2384 :    
2385 :     C<< my $value = $shelp->FeatureColumnValue($colName, $fid, \%extraCols); >>
2386 :    
2387 :     Return the value to be displayed in the specified feature column.
2388 :    
2389 :     =over 4
2390 :    
2391 :     =item colName
2392 :    
2393 :     Name of the column to be displayed.
2394 :    
2395 :     =item record
2396 :    
2397 :     DBObject record for the feature being displayed in the current row.
2398 :    
2399 :     =item extraCols
2400 :    
2401 :     Reference to a hash of extra column names to values. If the incoming column name
2402 :     begins with C<X=>, its value will be taken from this hash.
2403 :    
2404 :     =item RETURN
2405 :    
2406 :     Returns the HTML to be displayed in the named column for the specified feature.
2407 :    
2408 :     =back
2409 :    
2410 :     =cut
2411 :    
2412 :     sub FeatureColumnValue {
2413 :     # Get the parameters.
2414 :     my ($self, $colName, $record, $extraCols) = @_;
2415 :     # Get the sprout and CGI objects.
2416 :     my $cgi = $self->Q();
2417 :     my $sprout = $self->DB();
2418 :     # Get the feature ID.
2419 :     my ($fid) = $record->Value('Feature(id)');
2420 :     # Declare the return variable. Denote that we default to a non-breaking space,
2421 :     # which will translate to an empty table cell (rather than a table cell with no
2422 :     # interior, which is what you get for a null string).
2423 :     my $retVal = "&nbsp;";
2424 :     # Process according to the column name.
2425 :     if ($colName =~ /^X=(.+)$/) {
2426 :     # Here we have an extra column. Only update if the value exists. Note that
2427 :     # a value of C<undef> is treated as a non-existent value, because the
2428 :     # caller may have put "colName => undef" in the "PutFeature" call in order
2429 :     # to insure we know the extra column exists.
2430 :     if (defined $extraCols->{$1}) {
2431 :     $retVal = $extraCols->{$1};
2432 :     }
2433 : parrello 1.13 } elsif ($colName eq 'alias') {
2434 :     # In this case, the user wants a list of external aliases for the feature.
2435 :     # These are very expensive, so we compute them when the row is displayed.
2436 :     $retVal = "%%alias=$fid";
2437 : parrello 1.1 } elsif ($colName eq 'fid') {
2438 :     # Here we have the raw feature ID. We hyperlink it to the protein page.
2439 :     $retVal = HTML::set_prot_links($fid);
2440 :     } elsif ($colName eq 'function') {
2441 :     # The functional assignment is just a matter of getting some text.
2442 :     ($retVal) = $record->Value('Feature(assignment)');
2443 :     } elsif ($colName eq 'gblink') {
2444 :     # Here we want a link to the GBrowse page using the official GBrowse button.
2445 : parrello 1.23 $retVal = FakeButton('GBrowse', "GetGBrowse.cgi", undef,
2446 : parrello 1.18 fid => $fid);
2447 : parrello 1.13 } elsif ($colName eq 'group') {
2448 :     # Get the NMPDR group name.
2449 :     my (undef, $group) = $self->OrganismData($fid);
2450 :     # Dress it with a URL to the group's main page.
2451 :     my $nurl = $sprout->GroupPageName($group);
2452 :     $retVal = $cgi->a({ href => $nurl, title => "$group summary" },
2453 :     $group);
2454 :     } elsif ($colName =~ /^keyword:(.+)$/) {
2455 :     # Here we want keyword-related values. This is also expensive, so
2456 :     # we compute them when the row is displayed.
2457 : parrello 1.14 $retVal = "%%$colName=$fid";
2458 : parrello 1.13 } elsif ($colName eq 'orgName') {
2459 :     # Here we want the formatted organism name and feature number.
2460 :     $retVal = $self->FeatureName($fid);
2461 : parrello 1.1 } elsif ($colName eq 'protlink') {
2462 :     # Here we want a link to the protein page using the official NMPDR button.
2463 : parrello 1.23 $retVal = FakeButton('NMPDR', "protein.cgi", undef,
2464 : parrello 1.18 prot => $fid, SPROUT => 1, new_framework => 0,
2465 :     user => '');
2466 : parrello 1.13 }elsif ($colName eq 'subsystem') {
2467 :     # Another run-time column: subsystem list.
2468 :     $retVal = "%%subsystem=$fid";
2469 : parrello 1.1 }
2470 :     # Return the result.
2471 :     return $retVal;
2472 :     }
2473 :    
2474 : parrello 1.3 =head3 RunTimeColumns
2475 :    
2476 :     C<< my $htmlText = $shelp->RunTimeColumns($type, $text); >>
2477 :    
2478 :     Return the HTML text for a run-time column. Run-time columns are evaluated when the
2479 :     list is displayed, rather than when it is generated.
2480 :    
2481 :     =over 4
2482 :    
2483 :     =item type
2484 :    
2485 :     Type of column.
2486 :    
2487 :     =item text
2488 :    
2489 :     Data relevant to this row of the column.
2490 :    
2491 :     =item RETURN
2492 :    
2493 :     Returns the fully-formatted HTML text to go in the specified column.
2494 :    
2495 :     =back
2496 :    
2497 :     =cut
2498 :    
2499 :     sub RunTimeColumns {
2500 :     # Get the parameters.
2501 :     my ($self, $type, $text) = @_;
2502 :     # Declare the return variable.
2503 :     my $retVal = "";
2504 :     # Get the Sprout and CGI objects.
2505 :     my $sprout = $self->DB();
2506 :     my $cgi = $self->Q();
2507 : parrello 1.14 Trace("Runtime column $type with text \"$text\" found.") if T(4);
2508 : parrello 1.3 # Separate the text into a type and data.
2509 : parrello 1.13 if ($type eq 'alias') {
2510 : parrello 1.3 # Here the caller wants external alias links for a feature. The text
2511 :     # is the feature ID.
2512 :     my $fid = $text;
2513 :     # The complicated part is we have to hyperlink them. First, get the
2514 :     # aliases.
2515 :     Trace("Generating aliases for feature $fid.") if T(4);
2516 :     my @aliases = $sprout->FeatureAliases($fid);
2517 :     # Only proceed if we found some.
2518 :     if (@aliases) {
2519 :     # Join the aliases into a comma-delimited list.
2520 :     my $aliasList = join(", ", @aliases);
2521 :     # Ask the HTML processor to hyperlink them.
2522 :     $retVal = HTML::set_prot_links($cgi, $aliasList);
2523 :     }
2524 : parrello 1.13 } elsif ($type eq 'subsystem') {
2525 :     # Here the caller wants the subsystems in which this feature participates.
2526 :     # The text is the feature ID. We will list the subsystem names with links
2527 :     # to the subsystem's summary page.
2528 :     my $fid = $text;
2529 :     # Get the subsystems.
2530 :     Trace("Generating subsystems for feature $fid.") if T(4);
2531 :     my %subs = $sprout->SubsystemsOf($fid);
2532 : parrello 1.19 # Extract the subsystem names.
2533 :     my @names = map { HTML::sub_link($cgi, $_) } sort keys %subs;
2534 : parrello 1.13 # String them into a list.
2535 : parrello 1.19 $retVal = join(", ", @names);
2536 : parrello 1.13 } elsif ($type =~ /^keyword:(.+)$/) {
2537 :     # Here the caller wants the value of the named keyword. The text is the
2538 :     # feature ID.
2539 :     my $keywordName = $1;
2540 :     my $fid = $text;
2541 :     # Get the attribute values.
2542 :     Trace("Getting $keywordName values for feature $fid.") if T(4);
2543 :     my @values = $sprout->GetFlat(['Feature'], "Feature(id) = ?", [$fid],
2544 :     "Feature($keywordName)");
2545 :     # String them into a list.
2546 :     $retVal = join(", ", @values);
2547 : parrello 1.3 }
2548 :     # Return the result.
2549 :     return $retVal;
2550 :     }
2551 :    
2552 : parrello 1.10 =head3 SaveOrganismData
2553 :    
2554 :     C<< my ($name, $displayGroup) = $shelp->SaveOrganismData($group, $genomeID, $genus, $species, $strain); >>
2555 :    
2556 :     Format the name of an organism and the display version of its group name. The incoming
2557 :     data should be the relevant fields from the B<Genome> record in the database. The
2558 :     data will also be stored in the genome cache for later use in posting search results.
2559 :    
2560 :     =over 4
2561 :    
2562 :     =item group
2563 :    
2564 :     Name of the genome's group as it appears in the database.
2565 :    
2566 :     =item genomeID
2567 :    
2568 :     ID of the relevant genome.
2569 :    
2570 :     =item genus
2571 :    
2572 :     Genus of the genome's organism. If undefined or null, it will be assumed the genome is not
2573 :     in the database. In this case, the organism name is derived from the genomeID and the group
2574 :     is automatically the supporting-genomes group.
2575 :    
2576 :     =item species
2577 :    
2578 :     Species of the genome's organism.
2579 :    
2580 :     =item strain
2581 :    
2582 :     Strain of the species represented by the genome.
2583 :    
2584 :     =item RETURN
2585 :    
2586 :     Returns a two-element list. The first element is the formatted genome name. The second
2587 :     element is the display name of the genome's group.
2588 :    
2589 :     =back
2590 :    
2591 :     =cut
2592 :    
2593 :     sub SaveOrganismData {
2594 :     # Get the parameters.
2595 :     my ($self, $group, $genomeID, $genus, $species, $strain) = @_;
2596 :     # Declare the return values.
2597 :     my ($name, $displayGroup);
2598 :     # If the organism does not exist, format an unknown name and a blank group.
2599 :     if (! defined($genus)) {
2600 :     $name = "Unknown Genome $genomeID";
2601 :     $displayGroup = "";
2602 :     } else {
2603 :     # It does exist, so format the organism name.
2604 :     $name = "$genus $species";
2605 :     if ($strain) {
2606 :     $name .= " $strain";
2607 :     }
2608 :     # Compute the display group. This is currently the same as the incoming group
2609 :     # name unless it's the supporting group, which is nulled out.
2610 :     $displayGroup = ($group eq $FIG_Config::otherGroup ? "" : $group);
2611 :     }
2612 :     # Cache the group and organism data.
2613 :     my $cache = $self->{orgs};
2614 :     $cache->{$genomeID} = [$name, $displayGroup];
2615 :     # Return the result.
2616 :     return ($name, $displayGroup);
2617 :     }
2618 :    
2619 : parrello 1.16 =head3 ValidateKeywords
2620 :    
2621 :     C<< my $okFlag = $shelp->ValidateKeywords($keywordString, $required); >>
2622 :    
2623 :     Insure that a keyword string is reasonably valid. If it is invalid, a message will be
2624 :     set.
2625 :    
2626 :     =over 4
2627 :    
2628 :     =item keywordString
2629 :    
2630 :     Keyword string specified as a parameter to the current search.
2631 :    
2632 :     =item required
2633 :    
2634 :     TRUE if there must be at least one keyword specified, else FALSE.
2635 :    
2636 :     =item RETURN
2637 :    
2638 :     Returns TRUE if the keyword string is valid, else FALSE. Note that a null keyword string
2639 :     is acceptable if the I<$required> parameter is not specified.
2640 :    
2641 :     =back
2642 :    
2643 :     =cut
2644 :    
2645 :     sub ValidateKeywords {
2646 :     # Get the parameters.
2647 :     my ($self, $keywordString, $required) = @_;
2648 :     # Declare the return variable.
2649 :     my $retVal = 0;
2650 :     my @wordList = split /\s+/, $keywordString;
2651 :     # Right now our only real worry is a list of all minus words. The problem with it is that
2652 :     # it will return an incorrect result.
2653 :     my @plusWords = grep { $_ =~ /^[^\-]/ } @wordList;
2654 :     if (! @wordList) {
2655 :     if ($required) {
2656 :     $self->SetMessage("No search words specified.");
2657 : parrello 1.22 } else {
2658 :     $retVal = 1;
2659 : parrello 1.16 }
2660 :     } elsif (! @plusWords) {
2661 :     $self->SetMessage("At least one keyword must be positive. All the keywords entered are preceded by minus signs.");
2662 :     } else {
2663 :     $retVal = 1;
2664 :     }
2665 :     # Return the result.
2666 :     return $retVal;
2667 :     }
2668 :    
2669 : parrello 1.23 =head3 FakeButton
2670 :    
2671 :     C<< my $html = SearchHelper::FakeButton($caption, $url, $target, %parms); >>
2672 :    
2673 :     Create a fake button that hyperlinks to the specified URL with the specified parameters.
2674 :     Unlike a real button, this one won't visibly click, but it will take the user to the
2675 :     correct place.
2676 :    
2677 :     The parameters of this method are deliberately identical to L</Formlet> so that we
2678 :     can switch easily from real buttons to fake ones in the code.
2679 :    
2680 :     =over 4
2681 :    
2682 :     =item caption
2683 :    
2684 :     Caption to be put on the button.
2685 :    
2686 :     =item url
2687 :    
2688 :     URL for the target page or script.
2689 :    
2690 :     =item target
2691 :    
2692 :     Frame or target in which the new page should appear. If C<undef> is specified,
2693 :     the default target will be used.
2694 :    
2695 :     =item parms
2696 :    
2697 :     Hash containing the parameter names as keys and the parameter values as values.
2698 :     These will be appended to the URL.
2699 :    
2700 :     =back
2701 :    
2702 :     =cut
2703 :    
2704 :     sub FakeButton {
2705 :     # Get the parameters.
2706 :     my ($caption, $url, $target, %parms) = @_;
2707 :     # Declare the return variable.
2708 :     my $retVal;
2709 :     # Compute the target URL.
2710 :     my $targetUrl = "$url?" . join(";", map { "$_=" . uri_escape($parms{$_}) } keys %parms);
2711 :     # Compute the target-frame HTML.
2712 :     my $targetHtml = ($target ? " target=\"$target\"" : "");
2713 :     # Assemble the result.
2714 :     return "<a href=\"$targetUrl\" $targetHtml><div class=\"button2 button\">$caption</div></a>";
2715 :     }
2716 :    
2717 : parrello 1.18 =head3 Formlet
2718 :    
2719 :     C<< my $html = SearchHelper::Formlet($caption, $url, $target, %parms); >>
2720 :    
2721 :     Create a mini-form that posts to the specified URL with the specified parameters. The
2722 :     parameters will be stored in hidden fields, and the form's only visible control will
2723 :     be a submit button with the specified caption.
2724 :    
2725 :     Note that we don't use B<CGI.pm> services here because they generate forms with extra characters
2726 :     and tags that we don't want to deal with.
2727 :    
2728 :     =over 4
2729 :    
2730 :     =item caption
2731 :    
2732 :     Caption to be put on the form button.
2733 :    
2734 :     =item url
2735 :    
2736 :     URL to be put in the form's action parameter.
2737 :    
2738 :     =item target
2739 :    
2740 :     Frame or target in which the form results should appear. If C<undef> is specified,
2741 :     the default target will be used.
2742 :    
2743 :     =item parms
2744 :    
2745 :     Hash containing the parameter names as keys and the parameter values as values.
2746 :    
2747 :     =back
2748 :    
2749 :     =cut
2750 :    
2751 :     sub Formlet {
2752 :     # Get the parameters.
2753 :     my ($caption, $url, $target, %parms) = @_;
2754 :     # Compute the target HTML.
2755 :     my $targetHtml = ($target ? " target=\"$target\"" : "");
2756 :     # Start the form.
2757 :     my $retVal = "<form method=\"POST\" action=\"$url\"$target>";
2758 :     # Add the parameters.
2759 :     for my $parm (keys %parms) {
2760 :     $retVal .= "<input type=\"hidden\" name=\"$parm\" value=\"$parms{$parm}\" />";
2761 :     }
2762 :     # Put in the button.
2763 :     $retVal .= "<input type=\"submit\" name=\"submit\" value=\"$caption\" class=\"button\" />";
2764 :     # Close the form.
2765 :     $retVal .= "</form>";
2766 :     # Return the result.
2767 :     return $retVal;
2768 :     }
2769 :    
2770 : parrello 1.4 =head2 Virtual Methods
2771 :    
2772 :     =head3 Form
2773 :    
2774 :     C<< my $html = $shelp->Form(); >>
2775 :    
2776 :     Generate the HTML for a form to request a new search.
2777 :    
2778 :     =head3 Find
2779 :    
2780 :     C<< my $resultCount = $shelp->Find(); >>
2781 :    
2782 :     Conduct a search based on the current CGI query parameters. The search results will
2783 :     be written to the session cache file and the number of results will be
2784 :     returned. If the search parameters are invalid, a result count of C<undef> will be
2785 :     returned and a result message will be stored in this object describing the problem.
2786 :    
2787 :     =head3 Description
2788 :    
2789 :     C<< my $htmlText = $shelp->Description(); >>
2790 :    
2791 :     Return a description of this search. The description is used for the table of contents
2792 :     on the main search tools page. It may contain HTML, but it should be character-level,
2793 :     not block-level, since the description is going to appear in a list.
2794 :    
2795 :     =head3 SortKey
2796 :    
2797 : parrello 1.11 C<< my $key = $shelp->SortKey($fdata); >>
2798 : parrello 1.4
2799 : parrello 1.11 Return the sort key for the specified feature data. The default is to sort by feature name,
2800 : parrello 1.10 floating NMPDR organisms to the top. If a full-text search is used, then the default
2801 :     sort is by relevance followed by feature name. This sort may be overridden by the
2802 :     search class to provide fancier functionality. This method is called by
2803 :     B<PutFeature>, so it is only used for feature searches. A non-feature search
2804 :     would presumably have its own sort logic.
2805 : parrello 1.4
2806 :     =over 4
2807 :    
2808 :     =item record
2809 :    
2810 : parrello 1.11 The C<FeatureData> containing the current feature.
2811 : parrello 1.4
2812 :     =item RETURN
2813 :    
2814 :     Returns a key field that can be used to sort this row in among the results.
2815 :    
2816 :     =back
2817 :    
2818 :     =cut
2819 :    
2820 :     sub SortKey {
2821 :     # Get the parameters.
2822 : parrello 1.11 my ($self, $fdata) = @_;
2823 : parrello 1.4 # Get the feature ID from the record.
2824 : parrello 1.11 my $fid = $fdata->FID();
2825 : parrello 1.4 # Get the group from the feature ID.
2826 :     my $group = $self->FeatureGroup($fid);
2827 :     # Ask the feature query object to form the sort key.
2828 : parrello 1.11 my $retVal = $fdata->SortKey($self, $group);
2829 : parrello 1.4 # Return the result.
2830 :     return $retVal;
2831 :     }
2832 : parrello 1.9
2833 : parrello 1.1 1;

MCS Webmaster
ViewVC Help
Powered by ViewVC 1.0.3