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

Annotation of /Sprout/SearchHelper.pm

Parent Directory Parent Directory | Revision Log Revision Log


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

MCS Webmaster
ViewVC Help
Powered by ViewVC 1.0.3