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

Annotation of /Sprout/SearchHelper.pm

Parent Directory Parent Directory | Revision Log Revision Log


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

MCS Webmaster
ViewVC Help
Powered by ViewVC 1.0.3