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

Annotation of /Sprout/SearchHelper.pm

Parent Directory Parent Directory | Revision Log Revision Log


Revision 1.41 - (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 : parrello 1.38 # Specify the columns.
187 : parrello 1.34 $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.38 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 : parrello 1.38 my $query = $shelp->Q();
315 : parrello 1.1
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 : parrello 1.38 my $sprout = $shelp->DB();
332 : parrello 1.1
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 : parrello 1.38 my $flag = $shelp->IsNew();
353 : parrello 1.1
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 : parrello 1.38 my $sessionID = $shelp->ID();
369 : parrello 1.1
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 : parrello 1.38 my $name = $shelp->FormName();
384 : parrello 1.1
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 : parrello 1.38 $shelp->QueueFormScript($statement);
399 : parrello 1.1
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 : parrello 1.38 my $html = $shelp->FormStart($title);
434 : parrello 1.1
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 : parrello 1.41 -action => "$FIG_Config::cgi_url/SearchSkeleton.cgi",
465 : parrello 1.1 -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 : parrello 1.37 $cgi->h3("$title" . Hint($self->{class}, "Click here for more information."));
472 : parrello 1.1 # Put in an anchor tag in case there's a table of contents.
473 :     my $anchorName = $self->FormName();
474 :     $retVal .= "<a name=\"$anchorName\"></a>\n";
475 :     # Return the result.
476 :     return $retVal;
477 :     }
478 :    
479 :     =head3 FormEnd
480 :    
481 : parrello 1.38 my $htmlText = $shelp->FormEnd();
482 : parrello 1.1
483 :     Return the HTML text for closing a search form. This closes both the C<form> and
484 :     C<div> tags.
485 :    
486 :     =cut
487 :    
488 :     sub FormEnd {
489 :     # Get the parameters.
490 :     my ($self) = @_;
491 :     # Declare the return variable, closing the form and the DIV block.
492 :     my $retVal = "</form></div>\n";
493 :     # Now we flush out the statement queue.
494 :     my @statements = @{$self->{scriptQueue}};
495 :     if (@statements > 0) {
496 :     # Switch to JavaScript and set the "thisForm" variable.
497 :     $retVal .= "<SCRIPT language=\"JavaScript\">\n" .
498 :     " thisForm = document.$self->{name};\n";
499 :     # Unroll the statements.
500 :     while (@statements > 0) {
501 :     my $statement = shift @statements;
502 :     $retVal .= " $statement\n";
503 :     }
504 :     # Close the JavaScript.
505 :     $retVal .= "</SCRIPT>\n";
506 :     }
507 :     # Return the result.
508 :     return $retVal;
509 :     }
510 :    
511 :     =head3 SetMessage
512 :    
513 : parrello 1.38 $shelp->SetMessage($msg);
514 : parrello 1.1
515 :     Store the specified text as the result message. The result message is displayed
516 :     if an invalid parameter value is specified.
517 :    
518 :     =over 4
519 :    
520 :     =item msg
521 :    
522 :     Text of the result message to be displayed.
523 :    
524 :     =back
525 :    
526 :     =cut
527 :    
528 :     sub SetMessage {
529 :     # Get the parameters.
530 :     my ($self, $msg) = @_;
531 :     # Store the message.
532 :     $self->{message} = $msg;
533 :     }
534 :    
535 :     =head3 Message
536 :    
537 : parrello 1.38 my $text = $shelp->Message();
538 : parrello 1.1
539 :     Return the result message. The result message is displayed if an invalid parameter
540 :     value is specified.
541 :    
542 :     =cut
543 :    
544 :     sub Message {
545 :     # Get the parameters.
546 :     my ($self) = @_;
547 :     # Return the result.
548 :     return $self->{message};
549 :     }
550 :    
551 :     =head3 OpenSession
552 :    
553 : parrello 1.38 $shelp->OpenSession($rhelp);
554 : parrello 1.34
555 :     Set up the session cache file and write out the column headers.
556 :     This method should not be called until all the columns have
557 :     been configured, including the extra columns.
558 :    
559 :     =over 4
560 :    
561 :     =item rhelp
562 :    
563 :     Result helper for formatting the output. This has the column
564 :     headers stored in it.
565 : parrello 1.1
566 : parrello 1.34 =back
567 : parrello 1.1
568 :     =cut
569 :    
570 :     sub OpenSession {
571 :     # Get the parameters.
572 : parrello 1.34 my ($self, $rhelp) = @_;
573 :     # Insure the result helper is valid.
574 :     if (! defined($rhelp)) {
575 :     Confess("No result type specified for $self->{class}.");
576 :     } elsif(! $rhelp->isa('ResultHelper')) {
577 :     Confess("Invalid result type specified for $self->{class}.");
578 :     } else {
579 :     # Get the column headers and write them out.
580 :     my $colHdrs = $rhelp->GetColumnHeaders();
581 :     Trace(scalar(@{$colHdrs}) . " column headers written to output.") if T(3);
582 :     $self->WriteColumnHeaders(@{$colHdrs});
583 :     }
584 : parrello 1.1 }
585 :    
586 :     =head3 GetCacheFileName
587 :    
588 : parrello 1.38 my $fileName = $shelp->GetCacheFileName();
589 : parrello 1.1
590 :     Return the name to be used for this session's cache file.
591 :    
592 :     =cut
593 :    
594 :     sub GetCacheFileName {
595 :     # Get the parameters.
596 :     my ($self) = @_;
597 :     # Return the result.
598 :     return $self->GetTempFileName('cache');
599 :     }
600 :    
601 :     =head3 GetTempFileName
602 :    
603 : parrello 1.38 my $fileName = $shelp->GetTempFileName($type);
604 : parrello 1.1
605 :     Return the name to be used for a temporary file of the specified type. The
606 :     name is computed from the session name with the type as a suffix.
607 :    
608 :     =over 4
609 :    
610 :     =item type
611 :    
612 :     Type of temporary file to be generated.
613 :    
614 :     =item RETURN
615 :    
616 :     Returns a file name generated from the session name and the specified type.
617 :    
618 :     =back
619 :    
620 :     =cut
621 :    
622 :     sub GetTempFileName {
623 :     # Get the parameters.
624 :     my ($self, $type) = @_;
625 :     # Compute the file name. Note it gets stuffed in the FIG temporary
626 :     # directory.
627 : parrello 1.34 my $retVal = FIGRules::GetTempFileName(sessionID => $self->ID(), extension => $type);
628 : parrello 1.1 # Return the result.
629 :     return $retVal;
630 :     }
631 :    
632 :     =head3 WriteColumnHeaders
633 :    
634 : parrello 1.38 $shelp->WriteColumnHeaders(@colNames);
635 : parrello 1.1
636 :     Write out the column headers for the current search session. The column headers
637 :     are sent to the cache file, and then the cache is re-opened as a sort pipe and
638 :     the handle saved.
639 :    
640 :     =over 4
641 :    
642 :     =item colNames
643 :    
644 : parrello 1.34 A list of column names in the desired presentation order. For extra columns,
645 :     the column name is the hash supplied as the column definition.
646 : parrello 1.1
647 :     =back
648 :    
649 :     =cut
650 :    
651 :     sub WriteColumnHeaders {
652 :     # Get the parameters.
653 :     my ($self, @colNames) = @_;
654 :     # Get the cache file name and open it for output.
655 :     my $fileName = $self->GetCacheFileName();
656 :     my $handle1 = Open(undef, ">$fileName");
657 : parrello 1.34 # Freeze the column headers.
658 :     my @colHdrs = map { freeze($_) } @colNames;
659 : parrello 1.1 # Write the column headers and close the file.
660 : parrello 1.34 Tracer::PutLine($handle1, \@colHdrs);
661 : parrello 1.1 close $handle1;
662 :     # Now open the sort pipe and save the file handle. Note how we append the
663 :     # sorted data to the column header row already in place. The output will
664 :     # contain a sort key followed by the real columns. The sort key is
665 :     # hacked off before going to the output file.
666 :     $self->{fileHandle} = Open(undef, "| sort | cut --fields=2- >>$fileName");
667 :     }
668 :    
669 : parrello 1.34 =head3 ReadColumnHeaders
670 :    
671 : parrello 1.38 my @colHdrs = $shelp->ReadColumnHeaders($fh);
672 : parrello 1.34
673 :     Read the column headers from the specified file handle. The column headers are
674 :     frozen strings intermixed with frozen hash references. The strings represent
675 :     column names defined in the result helper. The hash references represent the
676 :     definitions of the extra columns.
677 :    
678 :     =over 4
679 :    
680 :     =item fh
681 :    
682 :     File handle from which the column headers are to be read.
683 :    
684 :     =item RETURN
685 :    
686 :     Returns a list of the column headers pulled from the specified file's first line.
687 :    
688 :     =back
689 :    
690 :     =cut
691 :    
692 :     sub ReadColumnHeaders {
693 :     # Get the parameters.
694 :     my ($self, $fh) = @_;
695 :     # Read and thaw the columns.
696 :     my @retVal = map { thaw($_) } Tracer::GetLine($fh);
697 :     # Return them to the caller.
698 :     return @retVal;
699 :     }
700 :    
701 : parrello 1.1 =head3 WriteColumnData
702 :    
703 : parrello 1.38 $shelp->WriteColumnData($key, @colValues);
704 : parrello 1.1
705 :     Write a row of column values to the current search session. It is assumed that
706 :     the session file is already open for output.
707 :    
708 :     =over 4
709 :    
710 :     =item key
711 :    
712 :     Sort key.
713 :    
714 :     =item colValues
715 :    
716 :     List of column values to write to the search result cache file for this session.
717 :    
718 :     =back
719 :    
720 :     =cut
721 :    
722 :     sub WriteColumnData {
723 :     # Get the parameters.
724 :     my ($self, $key, @colValues) = @_;
725 :     # Write them to the cache file.
726 :     Tracer::PutLine($self->{fileHandle}, [$key, @colValues]);
727 : parrello 1.32 Trace("Column data is " . join("; ", $key, @colValues) . ".") if T(4);
728 : parrello 1.1 }
729 :    
730 :     =head3 CloseSession
731 :    
732 : parrello 1.38 $shelp->CloseSession();
733 : parrello 1.1
734 :     Close the session file.
735 :    
736 :     =cut
737 :    
738 :     sub CloseSession {
739 :     # Get the parameters.
740 :     my ($self) = @_;
741 :     # Check for an open session file.
742 :     if (defined $self->{fileHandle}) {
743 :     # We found one, so close it.
744 : parrello 1.9 Trace("Closing session file.") if T(2);
745 : parrello 1.1 close $self->{fileHandle};
746 : parrello 1.28 # Tell the user.
747 :     my $cgi = $self->Q();
748 :     $self->PrintLine("Output formatting complete.<br />");
749 : parrello 1.1 }
750 :     }
751 :    
752 :     =head3 OrganismData
753 :    
754 : parrello 1.38 my ($orgName, $group) = $shelp->Organism($genomeID);
755 : parrello 1.1
756 :     Return the name and status of the organism corresponding to the specified genome ID.
757 :     For performance reasons, this information is cached in a special hash table, so we
758 :     only compute it once per run.
759 :    
760 :     =over 4
761 :    
762 :     =item genomeID
763 :    
764 :     ID of the genome whose name is desired.
765 :    
766 :     =item RETURN
767 :    
768 : parrello 1.32 Returns a list of three items. The first item in the list is the organism name,
769 : parrello 1.1 and the second is the name of the NMPDR group, or an empty string if the
770 : parrello 1.32 organism is not in an NMPDR group. The third item is the organism's domain.
771 : parrello 1.1
772 :     =back
773 :    
774 :     =cut
775 :    
776 :     sub OrganismData {
777 :     # Get the parameters.
778 :     my ($self, $genomeID) = @_;
779 :     # Declare the return variables.
780 : parrello 1.32 my ($orgName, $group, $domain);
781 : parrello 1.1 # Check the cache.
782 :     my $cache = $self->{orgs};
783 :     if (exists $cache->{$genomeID}) {
784 : parrello 1.32 ($orgName, $group, $domain) = @{$cache->{$genomeID}};
785 : parrello 1.36 Trace("Cached organism $genomeID has group \"$group\".") if T(4);
786 : parrello 1.1 } else {
787 :     # Here we have to use the database.
788 :     my $sprout = $self->DB();
789 : parrello 1.36 my ($genus, $species, $strain, $newGroup, $taxonomy) = $sprout->GetEntityValues('Genome', $genomeID,
790 : parrello 1.32 ['Genome(genus)', 'Genome(species)',
791 :     'Genome(unique-characterization)',
792 :     'Genome(primary-group)',
793 :     'Genome(taxonomy)']);
794 : parrello 1.10 # Format and cache the name and display group.
795 : parrello 1.36 Trace("Caching organism $genomeID with group \"$newGroup\".") if T(4);
796 :     ($orgName, $group, $domain) = $self->SaveOrganismData($newGroup, $genomeID, $genus, $species,
797 : parrello 1.32 $strain, $taxonomy);
798 : parrello 1.36 Trace("Returning group $group.") if T(4);
799 : parrello 1.1 }
800 :     # Return the result.
801 : parrello 1.32 return ($orgName, $group, $domain);
802 : parrello 1.1 }
803 :    
804 :     =head3 Organism
805 :    
806 : parrello 1.38 my $orgName = $shelp->Organism($genomeID);
807 : parrello 1.1
808 :     Return the name of the relevant organism. The name is computed from the genus,
809 :     species, and unique characterization. A cache is used to improve performance.
810 :    
811 :     =over 4
812 :    
813 :     =item genomeID
814 :    
815 :     ID of the genome whose name is desired.
816 :    
817 :     =item RETURN
818 :    
819 :     Returns the display name of the specified organism.
820 :    
821 :     =back
822 :    
823 :     =cut
824 :    
825 :     sub Organism {
826 :     # Get the parameters.
827 :     my ($self, $genomeID) = @_;
828 :     # Get the organism data.
829 : parrello 1.32 my ($retVal) = $self->OrganismData($genomeID);
830 : parrello 1.1 # Return the result.
831 :     return $retVal;
832 :     }
833 :    
834 :     =head3 ComputeFASTA
835 :    
836 : parrello 1.38 my $fasta = $shelp->ComputeFASTA($desiredType, $sequence, $flankingWidth);
837 : parrello 1.1
838 : parrello 1.32 Parse a sequence input and convert it into a FASTA string of the desired type with
839 :     the desired flanking width.
840 : parrello 1.1
841 :     =over 4
842 :    
843 :     =item desiredType
844 :    
845 : parrello 1.34 C<dna> to return a DNA sequence, C<prot> to return a protein sequence, C<dnaPattern>
846 :     to return a DNA search pattern, C<protPattern> to return a protein search pattern.
847 : parrello 1.1
848 :     =item sequence
849 :    
850 :     Sequence to return. It may be a DNA or protein sequence in FASTA form or a feature ID.
851 :     If a feature ID is specified, the feature's DNA or translation will be returned. The
852 :     feature ID is recognized by the presence of a vertical bar in the input. Otherwise,
853 :     if the input does not begin with a greater-than sign (FASTA label line), a default label
854 :     line will be provided.
855 :    
856 : parrello 1.32 =item flankingWidth
857 :    
858 :     If the DNA FASTA of a feature is desired, the number of base pairs to either side of the
859 :     feature that should be included. Currently we can't do this for Proteins because the
860 :     protein translation of a feature doesn't always match the DNA and is taken directly
861 :     from the database.
862 :    
863 : parrello 1.1 =item RETURN
864 :    
865 :     Returns a string in FASTA format representing the content of the desired sequence with
866 :     an appropriate label. If the input is invalid, a message will be stored and we will
867 :     return C<undef>. Note that the output will include a trailing new-line.
868 :    
869 :     =back
870 :    
871 :     =cut
872 :    
873 :     sub ComputeFASTA {
874 :     # Get the parameters.
875 : parrello 1.32 my ($self, $desiredType, $sequence, $flankingWidth) = @_;
876 : parrello 1.1 # Declare the return variable. If an error occurs, it will remain undefined.
877 :     my $retVal;
878 : parrello 1.11 # This variable will be cleared if an error is detected.
879 :     my $okFlag = 1;
880 : parrello 1.1 # Create variables to hold the FASTA label and data.
881 :     my ($fastaLabel, $fastaData);
882 : parrello 1.18 Trace("FASTA desired type is $desiredType.") if T(4);
883 : parrello 1.29 # Check for a feature specification. The smoking gun for that is a vertical bar.
884 : parrello 1.1 if ($sequence =~ /^\s*(\w+\|\S+)\s*$/) {
885 :     # Here we have a feature ID in $1. We'll need the Sprout object to process
886 :     # it.
887 :     my $fid = $1;
888 : parrello 1.11 Trace("Feature ID for fasta is $fid.") if T(3);
889 : parrello 1.1 my $sprout = $self->DB();
890 :     # Get the FIG ID. Note that we only use the first feature found. We are not
891 :     # supposed to have redundant aliases, though we may have an ID that doesn't
892 :     # exist.
893 :     my ($figID) = $sprout->FeaturesByAlias($fid);
894 :     if (! $figID) {
895 : parrello 1.17 $self->SetMessage("No gene found with the ID \"$fid\".");
896 : parrello 1.11 $okFlag = 0;
897 : parrello 1.1 } else {
898 : parrello 1.29 # Set the FASTA label. The ID is the first favored alias.
899 :     my $favored = $self->Q()->param('FavoredAlias') || 'fig';
900 :     my $favorLen = length $favored;
901 :     ($fastaLabel) = grep { substr($_, 0, $favorLen) eq $favored } $sprout->FeatureAliases($fid);
902 :     if (! $fastaLabel) {
903 :     # In an emergency, fall back to the original ID.
904 :     $fastaLabel = $fid;
905 :     }
906 : parrello 1.1 # Now proceed according to the sequence type.
907 : parrello 1.33 if ($desiredType =~ /prot/) {
908 : parrello 1.1 # We want protein, so get the translation.
909 :     $fastaData = $sprout->FeatureTranslation($figID);
910 : parrello 1.11 Trace(length $fastaData . " characters returned for translation of $fastaLabel.") if T(3);
911 : parrello 1.34 } elsif ($desiredType =~ /dna/) {
912 : parrello 1.32 # We want DNA, so get the DNA sequence. This is a two-step process. First, we get the
913 :     # locations.
914 : parrello 1.1 my @locList = $sprout->FeatureLocation($figID);
915 : parrello 1.32 if ($flankingWidth > 0) {
916 :     # Here we need to add flanking data. Convert the locations to a list
917 :     # of location objects.
918 :     my @locObjects = map { BasicLocation->new($_) } @locList;
919 :     # Initialize the return variable. We will put the DNA in here segment by segment.
920 :     $fastaData = "";
921 :     # Now we widen each location by the flanking width and stash the results. This
922 :     # requires getting the contig length for each contig so we don't fall off the end.
923 :     for my $locObject (@locObjects) {
924 :     Trace("Current location is " . $locObject->String . ".") if T(4);
925 :     # Remember the current start and length.
926 :     my ($start, $len) = ($locObject->Left, $locObject->Length);
927 :     # Get the contig length.
928 :     my $contigLen = $sprout->ContigLength($locObject->Contig);
929 :     # Widen the location and get its DNA.
930 :     $locObject->Widen($flankingWidth, $contigLen);
931 :     my $fastaSegment = $sprout->DNASeq([$locObject->String()]);
932 :     # Now we need to do some case changing. The main DNA is upper case and
933 :     # the flanking DNA is lower case.
934 :     my $leftFlank = $start - $locObject->Left;
935 :     my $rightFlank = $leftFlank + $len;
936 :     Trace("Wide location is " . $locObject->String . ". Flanks are $leftFlank and $rightFlank. Contig len is $contigLen.") if T(4);
937 :     my $fancyFastaSegment = lc(substr($fastaSegment, 0, $leftFlank)) .
938 :     uc(substr($fastaSegment, $leftFlank, $rightFlank - $leftFlank)) .
939 :     lc(substr($fastaSegment, $rightFlank));
940 :     $fastaData .= $fancyFastaSegment;
941 :     }
942 :     } else {
943 :     # Here we have just the raw sequence.
944 :     $fastaData = $sprout->DNASeq(\@locList);
945 :     }
946 :     Trace((length $fastaData) . " characters returned for DNA of $fastaLabel.") if T(3);
947 : parrello 1.1 }
948 :     }
949 :     } else {
950 : parrello 1.11 Trace("Analyzing FASTA sequence.") if T(4);
951 : parrello 1.1 # Here we are expecting a FASTA. We need to see if there's a label.
952 : parrello 1.11 if ($sequence =~ /^>[\n\s]*(\S[^\n]*)\n(.+)$/s) {
953 :     Trace("Label \"$1\" found in match to sequence:\n$sequence") if T(4);
954 : parrello 1.1 # Here we have a label, so we split it from the data.
955 :     $fastaLabel = $1;
956 :     $fastaData = $2;
957 :     } else {
958 : parrello 1.11 Trace("No label found in match to sequence:\n$sequence") if T(4);
959 : parrello 1.1 # Here we have no label, so we create one and use the entire sequence
960 :     # as data.
961 : parrello 1.34 $fastaLabel = "$desiredType sequence specified by user";
962 : parrello 1.1 $fastaData = $sequence;
963 :     }
964 : parrello 1.34 # If we are not doing a pattern search, we need to clean the junk out of the sequence.
965 :     if ($desiredType !~ /pattern/i) {
966 :     $fastaData =~ s/\n//g;
967 :     $fastaData =~ s/\s+//g;
968 :     }
969 : parrello 1.18 # Finally, verify that it's DNA if we're doing DNA stuff.
970 : parrello 1.34 if ($desiredType eq 'dna' && $fastaData =~ /[^agctxn-]/i) {
971 : parrello 1.24 $self->SetMessage("Invalid characters detected. Is the input really a DNA sequence?");
972 : parrello 1.11 $okFlag = 0;
973 : parrello 1.1 }
974 :     }
975 : parrello 1.11 Trace("FASTA data sequence: $fastaData") if T(4);
976 :     # Only proceed if no error was detected.
977 :     if ($okFlag) {
978 : parrello 1.33 if ($desiredType =~ /pattern/i) {
979 : parrello 1.34 # For a scan, there is no label and no breakup.
980 : parrello 1.33 $retVal = $fastaData;
981 :     } else {
982 :     # We need to format the sequence into 60-byte chunks. We use the infamous
983 :     # grep-split trick. The split, because of the presence of the parentheses,
984 :     # includes the matched delimiters in the output list. The grep strips out
985 :     # the empty list items that appear between the so-called delimiters, since
986 :     # the delimiters are what we want.
987 :     my @chunks = grep { $_ } split /(.{1,60})/, $fastaData;
988 :     $retVal = join("\n", ">$fastaLabel", @chunks, "");
989 :     }
990 : parrello 1.1 }
991 :     # Return the result.
992 :     return $retVal;
993 :     }
994 :    
995 : parrello 1.16 =head3 SubsystemTree
996 :    
997 : parrello 1.38 my $tree = SearchHelper::SubsystemTree($sprout, %options);
998 : parrello 1.16
999 :     This method creates a subsystem selection tree suitable for passing to
1000 :     L</SelectionTree>. Each leaf node in the tree will have a link to the
1001 :     subsystem display page. In addition, each node can have a radio button. The
1002 :     radio button alue is either C<classification=>I<string>, where I<string> is
1003 :     a classification string, or C<id=>I<string>, where I<string> is a subsystem ID.
1004 :     Thus, it can either be used to filter by a group of related subsystems or a
1005 :     single subsystem.
1006 :    
1007 :     =over 4
1008 :    
1009 :     =item sprout
1010 :    
1011 :     Sprout database object used to get the list of subsystems.
1012 :    
1013 :     =item options
1014 :    
1015 :     Hash containing options for building the tree.
1016 :    
1017 :     =item RETURN
1018 :    
1019 :     Returns a reference to a tree list suitable for passing to L</SelectionTree>.
1020 :    
1021 :     =back
1022 :    
1023 :     The supported options are as follows.
1024 :    
1025 :     =over 4
1026 :    
1027 :     =item radio
1028 :    
1029 :     TRUE if the tree should be configured for radio buttons. The default is FALSE.
1030 :    
1031 :     =item links
1032 :    
1033 :     TRUE if the tree should be configured for links. The default is TRUE.
1034 :    
1035 :     =back
1036 :    
1037 :     =cut
1038 :    
1039 :     sub SubsystemTree {
1040 :     # Get the parameters.
1041 :     my ($sprout, %options) = @_;
1042 :     # Process the options.
1043 :     my $optionThing = Tracer::GetOptions({ radio => 0, links => 1 }, \%options);
1044 :     # Read in the subsystems.
1045 :     my @subs = $sprout->GetAll(['Subsystem'], "ORDER BY Subsystem(classification), Subsystem(id)", [],
1046 :     ['Subsystem(classification)', 'Subsystem(id)']);
1047 : parrello 1.26 # Put any unclassified subsystems at the end. They will always be at the beginning, so if one
1048 :     # is at the end, ALL subsystems are unclassified and we don't bother.
1049 :     if ($#subs >= 0 && $subs[$#subs]->[0] ne '') {
1050 :     while ($subs[0]->[0] eq '') {
1051 :     my $classLess = shift @subs;
1052 :     push @subs, $classLess;
1053 :     }
1054 :     }
1055 : parrello 1.41 # Get the seedviewer URL.
1056 :     my $svURL = $FIG_Config::linkinSV || "$FIG_Config::cgi_url/seedviewer.cgi";
1057 :     Trace("Seed Viewer URL is $svURL.") if T(3);
1058 : parrello 1.16 # Declare the return variable.
1059 :     my @retVal = ();
1060 :     # Each element in @subs represents a leaf node, so as we loop through it we will be
1061 :     # producing one leaf node at a time. The leaf node is represented as a 2-tuple. The
1062 :     # first element is a semi-colon-delimited list of the classifications for the
1063 :     # subsystem. There will be a stack of currently-active classifications, which we will
1064 :     # compare to the incoming classifications from the end backward. A new classification
1065 :     # requires starting a new branch. A different classification requires closing an old
1066 :     # branch and starting a new one. Each classification in the stack will also contain
1067 :     # that classification's current branch. We'll add a fake classification at the
1068 :     # beginning that we can use to represent the tree as a whole.
1069 :     my $rootName = '<root>';
1070 :     # Create the classification stack. Note the stack is a pair of parallel lists,
1071 :     # one containing names and the other containing content.
1072 :     my @stackNames = ($rootName);
1073 :     my @stackContents = (\@retVal);
1074 :     # Add a null entry at the end of the subsystem list to force an unrolling.
1075 : parrello 1.27 push @subs, ['', undef];
1076 : parrello 1.16 # Loop through the subsystems.
1077 :     for my $sub (@subs) {
1078 :     # Pull out the classification list and the subsystem ID.
1079 :     my ($classString, $id) = @{$sub};
1080 :     Trace("Processing class \"$classString\" and subsystem $id.") if T(4);
1081 :     # Convert the classification string to a list with the root classification in
1082 :     # the front.
1083 :     my @classList = ($rootName, split($FIG_Config::splitter, $classString));
1084 :     # Find the leftmost point at which the class list differs from the stack.
1085 :     my $matchPoint = 0;
1086 :     while ($matchPoint <= $#stackNames && $matchPoint <= $#classList &&
1087 :     $stackNames[$matchPoint] eq $classList[$matchPoint]) {
1088 :     $matchPoint++;
1089 :     }
1090 :     Trace("Match point is $matchPoint. Stack length is " . scalar(@stackNames) .
1091 :     ". Class List length is " . scalar(@classList) . ".") if T(4);
1092 :     # Unroll the stack to the matchpoint.
1093 :     while ($#stackNames >= $matchPoint) {
1094 :     my $popped = pop @stackNames;
1095 :     pop @stackContents;
1096 :     Trace("\"$popped\" popped from stack.") if T(4);
1097 :     }
1098 :     # Start branches for any new classifications.
1099 :     while ($#stackNames < $#classList) {
1100 :     # The branch for a new classification contains its radio button
1101 :     # data and then a list of children. So, at this point, if radio buttons
1102 :     # are desired, we put them into the content.
1103 :     my $newLevel = scalar(@stackNames);
1104 :     my @newClassContent = ();
1105 :     if ($optionThing->{radio}) {
1106 :     my $newClassString = join($FIG_Config::splitter, @classList[1..$newLevel]);
1107 :     push @newClassContent, { value => "classification=$newClassString%" };
1108 :     }
1109 :     # The new classification node is appended to its parent's content
1110 :     # and then pushed onto the stack. First, we need the node name.
1111 :     my $nodeName = $classList[$newLevel];
1112 :     # Add the classification to its parent. This makes it part of the
1113 :     # tree we'll be returning to the user.
1114 :     push @{$stackContents[$#stackNames]}, $nodeName, \@newClassContent;
1115 :     # Push the classification onto the stack.
1116 :     push @stackContents, \@newClassContent;
1117 :     push @stackNames, $nodeName;
1118 :     Trace("\"$nodeName\" pushed onto stack.") if T(4);
1119 :     }
1120 :     # Now the stack contains all our parent branches. We add the subsystem to
1121 :     # the branch at the top of the stack, but only if it's NOT the dummy node.
1122 :     if (defined $id) {
1123 :     # Compute the node name from the ID.
1124 :     my $nodeName = $id;
1125 :     $nodeName =~ s/_/ /g;
1126 :     # Create the node's leaf hash. This depends on the value of the radio
1127 :     # and link options.
1128 :     my $nodeContent = {};
1129 :     if ($optionThing->{links}) {
1130 :     # Compute the link value.
1131 :     my $linkable = uri_escape($id);
1132 : parrello 1.41 $nodeContent->{link} = "$svURL?page=Subsystems;subsystem=$linkable";
1133 : parrello 1.16 }
1134 :     if ($optionThing->{radio}) {
1135 :     # Compute the radio value.
1136 :     $nodeContent->{value} = "id=$id";
1137 :     }
1138 :     # Push the node into its parent branch.
1139 :     Trace("\"$nodeName\" added to node list.") if T(4);
1140 :     push @{$stackContents[$#stackNames]}, $nodeName, $nodeContent;
1141 :     }
1142 :     }
1143 :     # Return the result.
1144 :     return \@retVal;
1145 :     }
1146 :    
1147 :    
1148 : parrello 1.1 =head3 NmpdrGenomeMenu
1149 :    
1150 : parrello 1.38 my $htmlText = $shelp->NmpdrGenomeMenu($menuName, $multiple, \@selected, $rows);
1151 : parrello 1.1
1152 :     This method creates a hierarchical HTML menu for NMPDR genomes organized by category. The
1153 :     category indicates the low-level NMPDR group. Organizing the genomes in this way makes it
1154 :     easier to select all genomes from a particular category.
1155 :    
1156 :     =over 4
1157 :    
1158 :     =item menuName
1159 :    
1160 :     Name to give to the menu.
1161 :    
1162 : parrello 1.3 =item multiple
1163 : parrello 1.1
1164 : parrello 1.3 TRUE if the user is allowed to select multiple genomes, else FALSE.
1165 : parrello 1.1
1166 :     =item selected
1167 :    
1168 :     Reference to a list containing the IDs of the genomes to be pre-selected. If the menu
1169 :     is not intended to allow multiple selections, the list should be a singleton. If the
1170 :     list is empty, nothing will be pre-selected.
1171 :    
1172 : parrello 1.3 =item rows (optional)
1173 :    
1174 :     Number of rows to display. If omitted, the default is 1 for a single-select list
1175 :     and 10 for a multi-select list.
1176 :    
1177 : parrello 1.8 =item crossMenu (optional)
1178 :    
1179 : parrello 1.41 This is currently not supported.
1180 : parrello 1.8
1181 : parrello 1.1 =item RETURN
1182 :    
1183 :     Returns the HTML text to generate a C<SELECT> menu inside a form.
1184 :    
1185 :     =back
1186 :    
1187 :     =cut
1188 :    
1189 :     sub NmpdrGenomeMenu {
1190 :     # Get the parameters.
1191 : parrello 1.8 my ($self, $menuName, $multiple, $selected, $rows, $cross) = @_;
1192 : parrello 1.1 # Get the Sprout and CGI objects.
1193 :     my $sprout = $self->DB();
1194 :     my $cgi = $self->Q();
1195 : parrello 1.3 # Compute the row count.
1196 :     if (! defined $rows) {
1197 :     $rows = ($multiple ? 10 : 1);
1198 :     }
1199 : parrello 1.41 # Get a comma-delimited list of the preselected genomes.
1200 :     my $preselected = "";
1201 :     if ($selected) {
1202 :     $preselected = join(", ", @$selected);
1203 :     }
1204 :     # Ask Sprout for a genome menu.
1205 :     my $retVal = $sprout->GenomeMenu(name => $menuName,
1206 :     multiSelect => $multiple,
1207 :     selected => $preselected,
1208 :     size => $rows);
1209 : parrello 1.1 # Return the result.
1210 :     return $retVal;
1211 :     }
1212 :    
1213 : parrello 1.3 =head3 PropertyMenu
1214 :    
1215 : parrello 1.38 my $htmlText = $shelp->PropertyMenu($menuName, $selected, $force);
1216 : parrello 1.3
1217 :     Generate a property name dropdown menu.
1218 :    
1219 :     =over 4
1220 :    
1221 :     =item menuName
1222 :    
1223 :     Name to give to the menu.
1224 :    
1225 :     =item selected
1226 :    
1227 :     Value of the property name to pre-select.
1228 :    
1229 :     =item force (optional)
1230 :    
1231 :     If TRUE, then the user will be forced to choose a property name. If FALSE,
1232 :     then an additional menu choice will be provided to select nothing.
1233 :    
1234 :     =item RETURN
1235 :    
1236 :     Returns a dropdown menu box that allows the user to select a property name. An additional
1237 :     selection entry will be provided for selecting no property name
1238 :    
1239 :     =back
1240 :    
1241 :     =cut
1242 :    
1243 :     sub PropertyMenu {
1244 :     # Get the parameters.
1245 :     my ($self, $menuName, $selected, $force) = @_;
1246 :     # Get the CGI and Sprout objects.
1247 :     my $sprout = $self->DB();
1248 :     my $cgi = $self->Q();
1249 :     # Create the property name list.
1250 :     my @propNames = ();
1251 :     if (! $force) {
1252 :     push @propNames, "";
1253 :     }
1254 :     # Get all the property names, putting them after the null choice if one exists.
1255 :     push @propNames, $sprout->GetChoices('Property', 'property-name');
1256 :     # Create a menu from them.
1257 :     my $retVal = $cgi->popup_menu(-name=> $menuName, -values => \@propNames,
1258 :     -default => $selected);
1259 :     # Return the result.
1260 :     return $retVal;
1261 :     }
1262 :    
1263 : parrello 1.1 =head3 MakeTable
1264 :    
1265 : parrello 1.38 my $htmlText = $shelp->MakeTable(\@rows);
1266 : parrello 1.1
1267 :     Create a table from a group of table rows. The table rows must be fully pre-formatted: in
1268 :     other words, each must have the TR and TD tags included.
1269 :    
1270 :     The purpose of this method is to provide a uniform look for search form tables. It is
1271 :     almost impossible to control a table using styles, so rather than have a table style,
1272 :     we create the TABLE tag in this method. Note also that the first TD or TH in each row will
1273 :     be updated with an explicit width so the forms look pretty when they are all on one
1274 :     page.
1275 :    
1276 :     =over 4
1277 :    
1278 :     =item rows
1279 :    
1280 :     Reference to a list of table rows. Each table row must be in HTML form with all
1281 : parrello 1.29 the TR and TD tags set up. The first TD or TH tag in the first non-colspanned row
1282 :     will be modified to set the width. Everything else will be left as is.
1283 : parrello 1.1
1284 :     =item RETURN
1285 :    
1286 :     Returns the full HTML for a table in the approved NMPDR Search Form style.
1287 :    
1288 :     =back
1289 :    
1290 :     =cut
1291 :    
1292 :     sub MakeTable {
1293 :     # Get the parameters.
1294 :     my ($self, $rows) = @_;
1295 :     # Get the CGI object.
1296 :     my $cgi = $self->Q();
1297 : parrello 1.29 # The first column of the first row must have its width fixed.
1298 :     # This flag will be set to FALSE when that happens.
1299 :     my $needWidth = 1;
1300 : parrello 1.1 # modifier becase we only want to change the first tag. Also, if a width
1301 :     # is already specified on the first column bad things will happen.
1302 :     for my $row (@{$rows}) {
1303 : parrello 1.29 # See if this row needs a width.
1304 :     if ($needWidth && $row =~ /<(td|th) ([^>]+)>/i) {
1305 :     # Here we have a first cell and its tag parameters are in $2.
1306 :     my $elements = $2;
1307 :     if ($elements !~ /colspan/i) {
1308 :     Trace("No colspan tag found in element \'$elements\'.") if T(3);
1309 :     # Here there's no colspan, so we plug in the width. We
1310 :     # eschew the "g" modifier on the substitution because we
1311 :     # only want to update the first cell.
1312 :     $row =~ s/(<(td|th))/$1 width="150"/i;
1313 :     # Denote we don't need this any more.
1314 :     $needWidth = 0;
1315 :     }
1316 :     }
1317 : parrello 1.1 }
1318 :     # Create the table.
1319 :     my $retVal = $cgi->table({border => 2, cellspacing => 2,
1320 :     width => 700, class => 'search'},
1321 :     @{$rows});
1322 :     # Return the result.
1323 :     return $retVal;
1324 :     }
1325 :    
1326 :     =head3 SubmitRow
1327 :    
1328 : parrello 1.38 my $htmlText = $shelp->SubmitRow($caption);
1329 : parrello 1.1
1330 :     Returns the HTML text for the row containing the page size control
1331 :     and the submit button. All searches should have this row somewhere
1332 :     near the top of the form.
1333 :    
1334 : parrello 1.18 =over 4
1335 :    
1336 :     =item caption (optional)
1337 :    
1338 :     Caption to be put on the search button. The default is C<Go>.
1339 :    
1340 :     =item RETURN
1341 :    
1342 :     Returns a table row containing the controls for submitting the search
1343 :     and tuning the results.
1344 :    
1345 :     =back
1346 :    
1347 : parrello 1.1 =cut
1348 :    
1349 :     sub SubmitRow {
1350 :     # Get the parameters.
1351 : parrello 1.18 my ($self, $caption) = @_;
1352 : parrello 1.1 my $cgi = $self->Q();
1353 : parrello 1.18 # Compute the button caption.
1354 :     my $realCaption = (defined $caption ? $caption : 'Go');
1355 : parrello 1.3 # Get the current page size.
1356 :     my $pageSize = $cgi->param('PageSize');
1357 : parrello 1.34 # Get the current feature ID type.
1358 :     my $aliasType = $self->GetPreferredAliasType();
1359 :     # Create the rows.
1360 : parrello 1.37 my $retVal = $cgi->Tr($cgi->td("Identifier Type "),
1361 :     $cgi->td({ colspan => 2 },
1362 :     $cgi->popup_menu(-name => 'AliasType',
1363 :     -values => ['FIG', AliasAnalysis::AliasTypes() ],
1364 :     -default => $aliasType) .
1365 : parrello 1.40 Hint("Identifier Type", "Specify how you want gene names to be displayed."))) .
1366 : parrello 1.34 "\n" .
1367 :     $cgi->Tr($cgi->td("Results/Page"),
1368 : parrello 1.1 $cgi->td($cgi->popup_menu(-name => 'PageSize',
1369 : parrello 1.7 -values => [10, 25, 50, 100, 1000],
1370 : parrello 1.25 -default => $pageSize)),
1371 : parrello 1.1 $cgi->td($cgi->submit(-class => 'goButton',
1372 :     -name => 'Search',
1373 : parrello 1.18 -value => $realCaption)));
1374 : parrello 1.1 # Return the result.
1375 :     return $retVal;
1376 :     }
1377 : parrello 1.2
1378 : parrello 1.3 =head3 GetGenomes
1379 :    
1380 : parrello 1.38 my @genomeList = $shelp->GetGenomes($parmName);
1381 : parrello 1.3
1382 :     Return the list of genomes specified by the specified CGI query parameter.
1383 :     If the request method is POST, then the list of genome IDs is returned
1384 :     without preamble. If the request method is GET and the parameter is not
1385 :     specified, then it is treated as a request for all genomes. This makes it
1386 :     easier for web pages to link to a search that wants to specify all genomes.
1387 :    
1388 :     =over 4
1389 :    
1390 :     =item parmName
1391 :    
1392 :     Name of the parameter containing the list of genomes. This will be the
1393 :     first parameter passed to the L</NmpdrGenomeMenu> call that created the
1394 :     genome selection control on the form.
1395 :    
1396 :     =item RETURN
1397 :    
1398 :     Returns a list of the genomes to process.
1399 :    
1400 :     =back
1401 :    
1402 :     =cut
1403 :    
1404 :     sub GetGenomes {
1405 :     # Get the parameters.
1406 :     my ($self, $parmName) = @_;
1407 :     # Get the CGI query object.
1408 :     my $cgi = $self->Q();
1409 :     # Get the list of genome IDs in the request header.
1410 :     my @retVal = $cgi->param($parmName);
1411 :     Trace("Genome list for $parmName is (" . join(", ", @retVal) . ") with method " . $cgi->request_method() . ".") if T(3);
1412 :     # Check for the special GET case.
1413 :     if ($cgi->request_method() eq "GET" && ! @retVal) {
1414 :     # Here the caller wants all the genomes.
1415 :     my $sprout = $self->DB();
1416 :     @retVal = $sprout->Genomes();
1417 :     }
1418 :     # Return the result.
1419 :     return @retVal;
1420 :     }
1421 :    
1422 :     =head3 ComputeSearchURL
1423 :    
1424 : parrello 1.38 my $url = $shelp->ComputeSearchURL(%overrides);
1425 : parrello 1.3
1426 :     Compute the GET-style URL for the current search. In order for this to work, there
1427 :     must be a copy of the search form on the current page. This will always be the
1428 :     case if the search is coming from C<SearchSkeleton.cgi>.
1429 :    
1430 :     A little expense is involved in order to make the URL as smart as possible. The
1431 :     main complication is that if the user specified all genomes, we'll want to
1432 :     remove the parameter entirely from a get-style URL.
1433 :    
1434 : parrello 1.19 =over 4
1435 :    
1436 :     =item overrides
1437 :    
1438 :     Hash containing override values for the parameters, where the parameter name is
1439 :     the key and the parameter value is the override value. If the override value is
1440 :     C<undef>, the parameter will be deleted from the result.
1441 :    
1442 :     =item RETURN
1443 :    
1444 :     Returns a GET-style URL for invoking the search with the specified overrides.
1445 :    
1446 :     =back
1447 :    
1448 : parrello 1.3 =cut
1449 :    
1450 :     sub ComputeSearchURL {
1451 :     # Get the parameters.
1452 : parrello 1.19 my ($self, %overrides) = @_;
1453 : parrello 1.3 # Get the database and CGI query object.
1454 :     my $cgi = $self->Q();
1455 :     my $sprout = $self->DB();
1456 :     # Start with the full URL.
1457 : parrello 1.41 my $retVal = "$FIG_Config::cgi_url/SearchSkeleton.cgi";
1458 : parrello 1.3 # Get all the query parameters in a hash.
1459 :     my %parms = $cgi->Vars();
1460 :     # Now we need to do some fixing. Each multi-valued parameter is encoded as a string with null
1461 :     # characters separating the individual values. We have to convert those to lists. In addition,
1462 :     # the multiple-selection genome parameters and the feature type parameter must be checked to
1463 :     # determine whether or not they can be removed from the URL. First, we get a list of the
1464 :     # genome parameters and a list of all genomes. Note that we only need the list if a
1465 :     # multiple-selection genome parameter has been found on the form.
1466 :     my %genomeParms = map { $_ => 1 } @{$self->{genomeParms}};
1467 :     my @genomeList;
1468 :     if (keys %genomeParms) {
1469 :     @genomeList = $sprout->Genomes();
1470 :     }
1471 :     # Create a list to hold the URL parameters we find.
1472 :     my @urlList = ();
1473 :     # Now loop through the parameters in the hash, putting them into the output URL.
1474 :     for my $parmKey (keys %parms) {
1475 :     # Get a list of the parameter values. If there's only one, we'll end up with
1476 :     # a singleton list, but that's okay.
1477 :     my @values = split (/\0/, $parms{$parmKey});
1478 :     # Check for special cases.
1479 : parrello 1.26 if (grep { $_ eq $parmKey } qw(SessionID ResultCount Page PageSize Trace TF)) {
1480 : parrello 1.3 # These are bookkeeping parameters we don't need to start a search.
1481 :     @values = ();
1482 :     } elsif ($parmKey =~ /_SearchThing$/) {
1483 :     # Here the value coming in is from a genome control's search thing. It does
1484 :     # not affect the results of the search, so we clear it.
1485 :     @values = ();
1486 :     } elsif ($genomeParms{$parmKey}) {
1487 :     # Here we need to see if the user wants all the genomes. If he does,
1488 :     # we erase all the values just like with features.
1489 :     my $allFlag = $sprout->IsAllGenomes(\@values, \@genomeList);
1490 :     if ($allFlag) {
1491 :     @values = ();
1492 :     }
1493 : parrello 1.19 } elsif (exists $overrides{$parmKey}) {
1494 :     # Here the value is being overridden, so we skip it for now.
1495 :     @values = ();
1496 : parrello 1.3 }
1497 :     # If we still have values, create the URL parameters.
1498 :     if (@values) {
1499 :     push @urlList, map { "$parmKey=" . uri_escape($_) } @values;
1500 :     }
1501 :     }
1502 : parrello 1.19 # Now do the overrides.
1503 :     for my $overKey (keys %overrides) {
1504 :     # Only use this override if it's not a delete marker.
1505 :     if (defined $overrides{$overKey}) {
1506 :     push @urlList, "$overKey=" . uri_escape($overrides{$overKey});
1507 :     }
1508 :     }
1509 : parrello 1.3 # Add the parameters to the URL.
1510 :     $retVal .= "?" . join(";", @urlList);
1511 :     # Return the result.
1512 :     return $retVal;
1513 :     }
1514 :    
1515 : parrello 1.9 =head3 AdvancedClassList
1516 :    
1517 : parrello 1.38 my @classes = SearchHelper::AdvancedClassList();
1518 : parrello 1.9
1519 :     Return a list of advanced class names. This list is used to generate the directory
1520 :     of available searches on the search page.
1521 :    
1522 : parrello 1.34 We do a file search to accomplish this, but to pull it off we need to look at %INC.
1523 : parrello 1.9
1524 :     =cut
1525 :    
1526 :     sub AdvancedClassList {
1527 : parrello 1.34 # Determine the search helper module directory.
1528 :     my $libDirectory = $INC{'SearchHelper.pm'};
1529 :     $libDirectory =~ s/SearchHelper\.pm//;
1530 :     # Read it, keeping only the helper modules.
1531 :     my @modules = grep { /^SH\w+\.pm/ } Tracer::OpenDir($libDirectory, 0);
1532 :     # Convert the file names to search types.
1533 :     my @retVal = map { $_ =~ /^SH(\w+)\.pm/; $1 } @modules;
1534 :     # Return the result in alphabetical order.
1535 : parrello 1.30 return sort @retVal;
1536 : parrello 1.9 }
1537 :    
1538 : parrello 1.16 =head3 SelectionTree
1539 :    
1540 : parrello 1.38 my $htmlText = SearchHelper::SelectionTree($cgi, \%tree, %options);
1541 : parrello 1.16
1542 :     Display a selection tree.
1543 :    
1544 :     This method creates the HTML for a tree selection control. The tree is implemented as a set of
1545 :     nested HTML unordered lists. Each selectable element of the tree will contain a radio button. In
1546 :     addition, some of the tree nodes can contain hyperlinks.
1547 :    
1548 :     The tree itself is passed in as a multi-level list containing node names followed by
1549 :     contents. Each content element is a reference to a similar list. The first element of
1550 :     each list may be a hash reference. If so, it should contain one or both of the following
1551 :     keys.
1552 :    
1553 :     =over 4
1554 :    
1555 :     =item link
1556 :    
1557 :     The navigation URL to be popped up if the user clicks on the node name.
1558 :    
1559 :     =item value
1560 :    
1561 :     The form value to be returned if the user selects the tree node.
1562 :    
1563 :     =back
1564 :    
1565 :     The presence of a C<link> key indicates the node name will be hyperlinked. The presence of
1566 :     a C<value> key indicates the node name will have a radio button. If a node has no children,
1567 :     you may pass it a hash reference instead of a list reference.
1568 :    
1569 :     The following example shows the hash for a three-level tree with links on the second level and
1570 :     radio buttons on the third.
1571 :    
1572 :     [ Objects => [
1573 :     Entities => [
1574 :     {link => "../docs/WhatIsAnEntity.html"},
1575 :     Genome => {value => 'GenomeData'},
1576 :     Feature => {value => 'FeatureData'},
1577 :     Contig => {value => 'ContigData'},
1578 :     ],
1579 :     Relationships => [
1580 :     {link => "../docs/WhatIsARelationShip.html"},
1581 :     HasFeature => {value => 'GenomeToFeature'},
1582 :     IsOnContig => {value => 'FeatureToContig'},
1583 :     ]
1584 :     ]
1585 :     ]
1586 :    
1587 :     Note how each leaf of the tree has a hash reference for its value, while the branch nodes
1588 :     all have list references.
1589 :    
1590 :     This next example shows how to set up a taxonomy selection field. The value returned
1591 :     by the tree control will be the taxonomy string for the selected node ready for use
1592 :     in a LIKE-style SQL filter. Only the single branch ending in campylobacter is shown for
1593 :     reasons of space.
1594 :    
1595 :     [ All => [
1596 :     {value => "%"},
1597 :     Bacteria => [
1598 :     {value => "Bacteria%"},
1599 :     Proteobacteria => [
1600 :     {value => "Bacteria; Proteobacteria%"},
1601 :     Epsilonproteobacteria => [
1602 :     {value => "Bacteria; Proteobacteria;Epsilonproteobacteria%"},
1603 :     Campylobacterales => [
1604 :     {value => "Bacteria; Proteobacteria; Epsilonproteobacteria; Campylobacterales%"},
1605 : parrello 1.38 Campylobacteraceae =>
1606 : parrello 1.16 {value => "Bacteria; Proteobacteria; Epsilonproteobacteria; Campylobacterales; Campylobacteraceae%"},
1607 :     ...
1608 :     ]
1609 :     ...
1610 :     ]
1611 :     ...
1612 :     ]
1613 :     ...
1614 :     ]
1615 :     ...
1616 :     ]
1617 :     ]
1618 :    
1619 :    
1620 :     This method of tree storage allows the caller to control the order in which the tree nodes
1621 :     are displayed and to completely control value selection and use of hyperlinks. It is, however
1622 :     a bit complicated. Eventually, tree-building classes will be provided to simplify things.
1623 :    
1624 :     The parameters to this method are as follows.
1625 :    
1626 :     =over 4
1627 :    
1628 :     =item cgi
1629 :    
1630 :     CGI object used to generate the HTML.
1631 :    
1632 :     =item tree
1633 :    
1634 :     Reference to a hash describing a tree. See the description above.
1635 :    
1636 :     =item options
1637 :    
1638 :     Hash containing options for the tree display.
1639 :    
1640 :     =back
1641 :    
1642 :     The allowable options are as follows
1643 :    
1644 :     =over 4
1645 :    
1646 :     =item nodeImageClosed
1647 :    
1648 :     URL of the image to display next to the tree nodes when they are collapsed. Clicking
1649 : parrello 1.41 on the image will expand a section of the tree. The default is C<plus.gif>.
1650 : parrello 1.16
1651 :     =item nodeImageOpen
1652 :    
1653 :     URL of the image to display next to the tree nodes when they are expanded. Clicking
1654 : parrello 1.41 on the image will collapse a section of the tree. The default is C<minus.gif>.
1655 : parrello 1.16
1656 :     =item style
1657 :    
1658 :     Style to use for the tree. The default is C<tree>. Because the tree style is implemented
1659 :     as nested lists, the key components of this style are the definitions for the C<ul> and
1660 :     C<li> tags. The default style file contains the following definitions.
1661 :    
1662 :     .tree ul {
1663 : parrello 1.38 margin-left: 0; padding-left: 22px
1664 : parrello 1.16 }
1665 :     .tree li {
1666 :     list-style-type: none;
1667 :     }
1668 :    
1669 :     The default image is 22 pixels wide, so in the above scheme each tree level is indented from its
1670 :     parent by the width of the node image. This use of styles limits the things we can do in formatting
1671 :     the tree, but it has the advantage of vastly simplifying the tree creation.
1672 :    
1673 :     =item name
1674 :    
1675 :     Field name to give to the radio buttons in the tree. The default is C<selection>.
1676 :    
1677 :     =item target
1678 :    
1679 :     Frame target for links. The default is C<_self>.
1680 :    
1681 :     =item selected
1682 :    
1683 :     If specified, the value of the radio button to be pre-selected.
1684 :    
1685 :     =back
1686 :    
1687 :     =cut
1688 :    
1689 :     sub SelectionTree {
1690 :     # Get the parameters.
1691 :     my ($cgi, $tree, %options) = @_;
1692 :     # Get the options.
1693 :     my $optionThing = Tracer::GetOptions({ name => 'selection',
1694 : parrello 1.41 nodeImageClosed => "$FIG_Config::cgi_url/Html/plus.gif",
1695 :     nodeImageOpen => "$FIG_Config::cgi_url/Html/minus.gif",
1696 : parrello 1.16 style => 'tree',
1697 :     target => '_self',
1698 :     selected => undef},
1699 :     \%options);
1700 :     # Declare the return variable. We'll do the standard thing with creating a list
1701 :     # of HTML lines and rolling them together at the end.
1702 :     my @retVal = ();
1703 :     # Only proceed if the tree is present.
1704 :     if (defined($tree)) {
1705 :     # Validate the tree.
1706 :     if (ref $tree ne 'ARRAY') {
1707 :     Confess("Selection tree is not a list reference.");
1708 :     } elsif (scalar @{$tree} == 0) {
1709 :     # The tree is empty, so we do nothing.
1710 :     } elsif ($tree->[0] eq 'HASH') {
1711 :     Confess("Hash reference found at start of selection tree. The tree as a whole cannot have attributes, only tree nodes.");
1712 :     } else {
1713 :     # Here we have a real tree. Apply the tree style.
1714 :     push @retVal, $cgi->start_div({ class => $optionThing->{style} });
1715 :     # Give us a DIV ID.
1716 :     my $divID = GetDivID($optionThing->{name});
1717 :     # Show the tree.
1718 :     push @retVal, ShowBranch($cgi, "(root)", $divID, $tree, $optionThing, 'block');
1719 :     # Close the DIV block.
1720 :     push @retVal, $cgi->end_div();
1721 :     }
1722 :     }
1723 :     # Return the result.
1724 :     return join("\n", @retVal, "");
1725 :     }
1726 :    
1727 :     =head3 ShowBranch
1728 :    
1729 : parrello 1.38 my @htmlLines = SearchHelper::ShowBranch($cgi, $label, $id, $branch, $options, $displayType);
1730 : parrello 1.16
1731 : parrello 1.38 This is a recursive method that displays a branch of the tree.
1732 : parrello 1.16
1733 :     =over 4
1734 :    
1735 :     =item cgi
1736 :    
1737 :     CGI object used to format HTML.
1738 :    
1739 :     =item label
1740 :    
1741 :     Label of this tree branch. It is only used in error messages.
1742 :    
1743 :     =item id
1744 :    
1745 :     ID to be given to this tree branch. The ID is used in the code that expands and collapses
1746 :     tree nodes.
1747 :    
1748 :     =item branch
1749 :    
1750 :     Reference to a list containing the content of the tree branch. The list contains an optional
1751 :     hash reference that is ignored and the list of children, each child represented by a name
1752 :     and then its contents. The contents could by a hash reference (indicating the attributes
1753 :     of a leaf node), or another tree branch.
1754 :    
1755 :     =item options
1756 :    
1757 :     Options from the original call to L</SelectionTree>.
1758 :    
1759 :     =item displayType
1760 :    
1761 :     C<block> if the contents of this list are to be displayed, C<none> if they are to be
1762 :     hidden.
1763 :    
1764 :     =item RETURN
1765 :    
1766 :     Returns one or more HTML lines that can be used to display the tree branch.
1767 :    
1768 :     =back
1769 :    
1770 :     =cut
1771 :    
1772 :     sub ShowBranch {
1773 :     # Get the parameters.
1774 :     my ($cgi, $label, $id, $branch, $options, $displayType) = @_;
1775 :     # Declare the return variable.
1776 :     my @retVal = ();
1777 :     # Start the branch.
1778 :     push @retVal, $cgi->start_ul({ id => $id, style => "display:$displayType" });
1779 :     # Check for the hash and choose the start location accordingly.
1780 :     my $i0 = (ref $branch->[0] eq 'HASH' ? 1 : 0);
1781 :     # Get the list length.
1782 :     my $i1 = scalar(@{$branch});
1783 :     # Verify we have an even number of elements.
1784 :     if (($i1 - $i0) % 2 != 0) {
1785 :     Trace("Branch elements are from $i0 to $i1.") if T(3);
1786 :     Confess("Odd number of elements in tree branch $label.");
1787 :     } else {
1788 :     # Loop through the elements.
1789 :     for (my $i = $i0; $i < $i1; $i += 2) {
1790 :     # Get this node's label and contents.
1791 :     my ($myLabel, $myContent) = ($branch->[$i], $branch->[$i+1]);
1792 :     # Get an ID for this node's children (if any).
1793 :     my $myID = GetDivID($options->{name});
1794 :     # Now we need to find the list of children and the options hash.
1795 :     # This is a bit ugly because we allow the shortcut of a hash without an
1796 :     # enclosing list. First, we need some variables.
1797 :     my $attrHash = {};
1798 :     my @childHtml = ();
1799 :     my $hasChildren = 0;
1800 :     if (! ref $myContent) {
1801 :     Confess("Invalid tree definition. Scalar found as content of node \"$myLabel\".");
1802 :     } elsif (ref $myContent eq 'HASH') {
1803 :     # Here the node is a leaf and its content contains the link/value hash.
1804 :     $attrHash = $myContent;
1805 :     } elsif (ref $myContent eq 'ARRAY') {
1806 :     # Here the node may be a branch. Its content is a list.
1807 :     my $len = scalar @{$myContent};
1808 :     if ($len >= 1) {
1809 :     # Here the first element of the list could by the link/value hash.
1810 :     if (ref $myContent->[0] eq 'HASH') {
1811 :     $attrHash = $myContent->[0];
1812 :     # If there's data in the list besides the hash, it's our child list.
1813 :     # We can pass the entire thing as the child list, because the hash
1814 :     # is ignored.
1815 :     if ($len > 1) {
1816 :     $hasChildren = 1;
1817 :     }
1818 :     } else {
1819 :     $hasChildren = 1;
1820 :     }
1821 :     # If we have children, create the child list with a recursive call.
1822 :     if ($hasChildren) {
1823 :     Trace("Processing children of $myLabel.") if T(4);
1824 :     push @childHtml, ShowBranch($cgi, $myLabel, $myID, $myContent, $options, 'none');
1825 : parrello 1.27 Trace("Children of $myLabel finished.") if T(4);
1826 : parrello 1.16 }
1827 :     }
1828 :     }
1829 :     # Okay, it's time to pause and take stock. We have the label of the current node
1830 :     # in $myLabel, its attributes in $attrHash, and if it is NOT a leaf node, we
1831 :     # have a child list in @childHtml. If it IS a leaf node, $hasChildren is 0.
1832 :     # Compute the image HTML. It's tricky, because we have to deal with the open and
1833 :     # closed images.
1834 :     my @images = ($options->{nodeImageOpen}, $options->{nodeImageClosed});
1835 :     my $image = $images[$hasChildren];
1836 :     my $prefixHtml = $cgi->img({src => $image, id => "${myID}img"});
1837 :     if ($hasChildren) {
1838 :     # If there are children, we wrap the image in a toggle hyperlink.
1839 :     $prefixHtml = $cgi->a({ onClick => "javascript:treeToggle('$myID','$images[0]', '$images[1]')" },
1840 :     $prefixHtml);
1841 :     }
1842 :     # Now the radio button, if any. Note we use "defined" in case the user wants the
1843 :     # value to be 0.
1844 :     if (defined $attrHash->{value}) {
1845 :     # Due to a glitchiness in the CGI stuff, we have to build the attribute
1846 :     # hash for the "input" method. If the item is pre-selected, we add
1847 :     # "checked => undef" to the hash. Otherwise, we can't have "checked"
1848 :     # at all.
1849 :     my $radioParms = { type => 'radio',
1850 :     name => $options->{name},
1851 :     value => $attrHash->{value},
1852 :     };
1853 :     if (defined $options->{selected} && $options->{selected} eq $attrHash->{value}) {
1854 :     $radioParms->{checked} = undef;
1855 :     }
1856 :     $prefixHtml .= $cgi->input($radioParms);
1857 :     }
1858 :     # Next, we format the label.
1859 :     my $labelHtml = $myLabel;
1860 : parrello 1.27 Trace("Formatting tree node for \"$myLabel\".") if T(4);
1861 : parrello 1.16 # Apply a hyperlink if necessary.
1862 :     if (defined $attrHash->{link}) {
1863 :     $labelHtml = $cgi->a({ href => $attrHash->{link}, target => $options->{target} },
1864 :     $labelHtml);
1865 :     }
1866 :     # Finally, roll up the child HTML. If there are no children, we'll get a null string
1867 :     # here.
1868 :     my $childHtml = join("\n", @childHtml);
1869 :     # Now we have all the pieces, so we can put them together.
1870 :     push @retVal, $cgi->li("$prefixHtml$labelHtml$childHtml");
1871 :     }
1872 :     }
1873 :     # Close the tree branch.
1874 :     push @retVal, $cgi->end_ul();
1875 :     # Return the result.
1876 :     return @retVal;
1877 :     }
1878 :    
1879 :     =head3 GetDivID
1880 :    
1881 : parrello 1.38 my $idString = SearchHelper::GetDivID($name);
1882 : parrello 1.16
1883 :     Return a new HTML ID string.
1884 :    
1885 :     =over 4
1886 :    
1887 :     =item name
1888 :    
1889 :     Name to be prefixed to the ID string.
1890 :    
1891 :     =item RETURN
1892 :    
1893 :     Returns a hopefully-unique ID string.
1894 :    
1895 :     =back
1896 :    
1897 :     =cut
1898 :    
1899 :     sub GetDivID {
1900 :     # Get the parameters.
1901 :     my ($name) = @_;
1902 :     # Compute the ID.
1903 :     my $retVal = "elt_$name$divCount";
1904 :     # Increment the counter to make sure this ID is not re-used.
1905 :     $divCount++;
1906 :     # Return the result.
1907 :     return $retVal;
1908 :     }
1909 :    
1910 : parrello 1.31 =head3 PrintLine
1911 :    
1912 : parrello 1.38 $shelp->PrintLine($message);
1913 : parrello 1.31
1914 :     Print a line of CGI output. This is used during the operation of the B<Find> method while
1915 :     searching, so the user sees progress in real-time.
1916 :    
1917 :     =over 4
1918 :    
1919 :     =item message
1920 :    
1921 :     HTML text to display.
1922 :    
1923 :     =back
1924 :    
1925 :     =cut
1926 :    
1927 :     sub PrintLine {
1928 :     # Get the parameters.
1929 :     my ($self, $message) = @_;
1930 :     # Send them to the output.
1931 :     print "$message\n";
1932 :     }
1933 :    
1934 : parrello 1.34 =head3 GetHelper
1935 : parrello 1.13
1936 : parrello 1.38 my $shelp = SearchHelper::GetHelper($parm, $type => $className);
1937 : parrello 1.1
1938 : parrello 1.34 Return a helper object with the given class name. If no such class exists, an
1939 :     error will be thrown.
1940 : parrello 1.1
1941 :     =over 4
1942 :    
1943 : parrello 1.34 =item parm
1944 : parrello 1.1
1945 : parrello 1.34 Parameter to pass to the constructor. This is a CGI object for a search helper
1946 :     and a search helper object for the result helper.
1947 : parrello 1.3
1948 :     =item type
1949 :    
1950 : parrello 1.34 Type of helper: C<RH> for a result helper and C<SH> for a search helper.
1951 : parrello 1.3
1952 : parrello 1.34 =item className
1953 : parrello 1.3
1954 : parrello 1.34 Class name for the helper object, without the preceding C<SH> or C<RH>. This is
1955 :     identical to what the script expects for the C<Class> or C<ResultType> parameter.
1956 : parrello 1.3
1957 :     =item RETURN
1958 :    
1959 : parrello 1.34 Returns a helper object for the specified class.
1960 : parrello 1.3
1961 :     =back
1962 :    
1963 :     =cut
1964 :    
1965 : parrello 1.34 sub GetHelper {
1966 : parrello 1.3 # Get the parameters.
1967 : parrello 1.34 my ($parm, $type, $className) = @_;
1968 : parrello 1.3 # Declare the return variable.
1969 : parrello 1.34 my $retVal;
1970 :     # Try to create the helper.
1971 :     eval {
1972 :     # Load it into memory. If it's already there nothing will happen here.
1973 :     my $realName = "$type$className";
1974 :     Trace("Requiring helper $realName.") if T(3);
1975 :     require "$realName.pm";
1976 :     Trace("Constructing helper object.") if T(3);
1977 :     # Construct the object.
1978 :     $retVal = eval("$realName->new(\$parm)");
1979 :     # Commit suicide if it didn't work.
1980 :     if (! defined $retVal) {
1981 :     die "Could not find a $type handler of type $className.";
1982 :     }
1983 :     };
1984 :     # Check for errors.
1985 :     if ($@) {
1986 :     Confess("Error retrieving $type$className: $@");
1987 : parrello 1.3 }
1988 :     # Return the result.
1989 :     return $retVal;
1990 :     }
1991 :    
1992 : parrello 1.10 =head3 SaveOrganismData
1993 :    
1994 : parrello 1.38 my ($name, $displayGroup, $domain) = $shelp->SaveOrganismData($group, $genomeID, $genus, $species, $strain, $taxonomy);
1995 : parrello 1.10
1996 :     Format the name of an organism and the display version of its group name. The incoming
1997 :     data should be the relevant fields from the B<Genome> record in the database. The
1998 :     data will also be stored in the genome cache for later use in posting search results.
1999 :    
2000 :     =over 4
2001 :    
2002 :     =item group
2003 :    
2004 :     Name of the genome's group as it appears in the database.
2005 :    
2006 :     =item genomeID
2007 :    
2008 :     ID of the relevant genome.
2009 :    
2010 :     =item genus
2011 :    
2012 :     Genus of the genome's organism. If undefined or null, it will be assumed the genome is not
2013 :     in the database. In this case, the organism name is derived from the genomeID and the group
2014 :     is automatically the supporting-genomes group.
2015 :    
2016 :     =item species
2017 :    
2018 :     Species of the genome's organism.
2019 :    
2020 :     =item strain
2021 :    
2022 :     Strain of the species represented by the genome.
2023 :    
2024 : parrello 1.32 =item taxonomy
2025 :    
2026 :     Taxonomy of the species represented by the genome.
2027 :    
2028 : parrello 1.10 =item RETURN
2029 :    
2030 : parrello 1.32 Returns a three-element list. The first element is the formatted genome name. The second
2031 :     element is the display name of the genome's group. The third is the genome's domain.
2032 : parrello 1.10
2033 :     =back
2034 :    
2035 :     =cut
2036 :    
2037 :     sub SaveOrganismData {
2038 :     # Get the parameters.
2039 : parrello 1.32 my ($self, $group, $genomeID, $genus, $species, $strain, $taxonomy) = @_;
2040 : parrello 1.10 # Declare the return values.
2041 :     my ($name, $displayGroup);
2042 :     # If the organism does not exist, format an unknown name and a blank group.
2043 :     if (! defined($genus)) {
2044 :     $name = "Unknown Genome $genomeID";
2045 :     $displayGroup = "";
2046 :     } else {
2047 :     # It does exist, so format the organism name.
2048 :     $name = "$genus $species";
2049 :     if ($strain) {
2050 :     $name .= " $strain";
2051 :     }
2052 :     # Compute the display group. This is currently the same as the incoming group
2053 :     # name unless it's the supporting group, which is nulled out.
2054 :     $displayGroup = ($group eq $FIG_Config::otherGroup ? "" : $group);
2055 : parrello 1.36 Trace("Group = $displayGroup, translated from \"$group\".") if T(4);
2056 : parrello 1.10 }
2057 : parrello 1.32 # Compute the domain from the taxonomy.
2058 :     my ($domain) = split /\s*;\s*/, $taxonomy, 2;
2059 : parrello 1.10 # Cache the group and organism data.
2060 :     my $cache = $self->{orgs};
2061 : parrello 1.32 $cache->{$genomeID} = [$name, $displayGroup, $domain];
2062 : parrello 1.10 # Return the result.
2063 : parrello 1.32 return ($name, $displayGroup, $domain);
2064 : parrello 1.10 }
2065 :    
2066 : parrello 1.16 =head3 ValidateKeywords
2067 :    
2068 : parrello 1.38 my $okFlag = $shelp->ValidateKeywords($keywordString, $required);
2069 : parrello 1.16
2070 :     Insure that a keyword string is reasonably valid. If it is invalid, a message will be
2071 :     set.
2072 :    
2073 :     =over 4
2074 :    
2075 :     =item keywordString
2076 :    
2077 :     Keyword string specified as a parameter to the current search.
2078 :    
2079 :     =item required
2080 :    
2081 :     TRUE if there must be at least one keyword specified, else FALSE.
2082 :    
2083 :     =item RETURN
2084 :    
2085 :     Returns TRUE if the keyword string is valid, else FALSE. Note that a null keyword string
2086 :     is acceptable if the I<$required> parameter is not specified.
2087 :    
2088 :     =back
2089 :    
2090 :     =cut
2091 :    
2092 :     sub ValidateKeywords {
2093 :     # Get the parameters.
2094 :     my ($self, $keywordString, $required) = @_;
2095 :     # Declare the return variable.
2096 :     my $retVal = 0;
2097 :     my @wordList = split /\s+/, $keywordString;
2098 :     # Right now our only real worry is a list of all minus words. The problem with it is that
2099 :     # it will return an incorrect result.
2100 :     my @plusWords = grep { $_ =~ /^[^\-]/ } @wordList;
2101 :     if (! @wordList) {
2102 :     if ($required) {
2103 :     $self->SetMessage("No search words specified.");
2104 : parrello 1.22 } else {
2105 :     $retVal = 1;
2106 : parrello 1.16 }
2107 :     } elsif (! @plusWords) {
2108 :     $self->SetMessage("At least one keyword must be positive. All the keywords entered are preceded by minus signs.");
2109 :     } else {
2110 :     $retVal = 1;
2111 :     }
2112 :     # Return the result.
2113 :     return $retVal;
2114 :     }
2115 :    
2116 : parrello 1.30 =head3 TuningParameters
2117 :    
2118 : parrello 1.38 my $options = $shelp->TuningParameters(%parmHash);
2119 : parrello 1.30
2120 :     Retrieve tuning parameters from the CGI query object. The parameter is a hash that maps parameter names
2121 :     to their default values. The parameters and their values will be returned as a hash reference.
2122 :    
2123 :     =over 4
2124 :    
2125 :     =item parmHash
2126 :    
2127 :     Hash mapping parameter names to their default values.
2128 :    
2129 :     =item RETURN
2130 :    
2131 :     Returns a reference to a hash containing the parameter names mapped to their actual values.
2132 :    
2133 :     =back
2134 :    
2135 :     =cut
2136 :    
2137 :     sub TuningParameters {
2138 :     # Get the parameters.
2139 :     my ($self, %parmHash) = @_;
2140 :     # Declare the return variable.
2141 :     my $retVal = {};
2142 :     # Get the CGI Query Object.
2143 :     my $cgi = $self->Q();
2144 :     # Loop through the parameter names.
2145 :     for my $parm (keys %parmHash) {
2146 :     # Get the incoming value for this parameter.
2147 :     my $value = $cgi->param($parm);
2148 :     # Zero might be a valid value, so we do an is-defined check rather than an OR.
2149 :     if (defined($value)) {
2150 :     $retVal->{$parm} = $value;
2151 :     } else {
2152 :     $retVal->{$parm} = $parmHash{$parm};
2153 :     }
2154 :     }
2155 :     # Return the result.
2156 :     return $retVal;
2157 :     }
2158 :    
2159 : parrello 1.34 =head3 GetPreferredAliasType
2160 :    
2161 : parrello 1.38 my $type = $shelp->GetPreferredAliasType();
2162 : parrello 1.34
2163 :     Return the preferred alias type for the current session. This information is stored
2164 :     in the C<AliasType> parameter of the CGI query object, and the default is C<FIG>
2165 :     (which indicates the FIG ID).
2166 :    
2167 :     =cut
2168 :    
2169 :     sub GetPreferredAliasType {
2170 :     # Get the parameters.
2171 :     my ($self) = @_;
2172 :     # Determine the preferred type.
2173 :     my $cgi = $self->Q();
2174 :     my $retVal = $cgi->param('AliasType') || 'FIG';
2175 :     # Return it.
2176 :     return $retVal;
2177 :     }
2178 :    
2179 : parrello 1.4 =head2 Virtual Methods
2180 :    
2181 :     =head3 Form
2182 :    
2183 : parrello 1.38 my $html = $shelp->Form();
2184 : parrello 1.4
2185 :     Generate the HTML for a form to request a new search.
2186 :    
2187 :     =head3 Find
2188 :    
2189 : parrello 1.38 my $resultCount = $shelp->Find();
2190 : parrello 1.4
2191 :     Conduct a search based on the current CGI query parameters. The search results will
2192 :     be written to the session cache file and the number of results will be
2193 :     returned. If the search parameters are invalid, a result count of C<undef> will be
2194 :     returned and a result message will be stored in this object describing the problem.
2195 :    
2196 : parrello 1.34 =cut
2197 :    
2198 :     sub Find {
2199 :     # Get the parameters.
2200 :     my ($self) = @_;
2201 :     $self->Message("Call to pure virtual Find method in helper of type " . ref($self) . ".");
2202 :     return undef;
2203 :     }
2204 :    
2205 : parrello 1.4 =head3 Description
2206 :    
2207 : parrello 1.38 my $htmlText = $shelp->Description();
2208 : parrello 1.4
2209 :     Return a description of this search. The description is used for the table of contents
2210 :     on the main search tools page. It may contain HTML, but it should be character-level,
2211 :     not block-level, since the description is going to appear in a list.
2212 :    
2213 :     =cut
2214 :    
2215 : parrello 1.34 sub Description {
2216 : parrello 1.4 # Get the parameters.
2217 : parrello 1.34 my ($self) = @_;
2218 :     $self->Message("Call to pure virtual Description method in helper of type " . ref($self) . ".");
2219 :     return "Unknown search type";
2220 : parrello 1.4 }
2221 : parrello 1.9
2222 : parrello 1.31 =head3 SearchTitle
2223 :    
2224 : parrello 1.38 my $titleHtml = $shelp->SearchTitle();
2225 : parrello 1.31
2226 :     Return the display title for this search. The display title appears above the search results.
2227 :     If no result is returned, no title will be displayed. The result should be an html string
2228 :     that can be legally put inside a block tag such as C<h3> or C<p>.
2229 :    
2230 :     =cut
2231 :    
2232 :     sub SearchTitle {
2233 :     # Get the parameters.
2234 :     my ($self) = @_;
2235 :     # Declare the return variable.
2236 : parrello 1.34 my $retVal = "";
2237 : parrello 1.31 # Return it.
2238 :     return $retVal;
2239 :     }
2240 :    
2241 : parrello 1.34 =head3 DefaultColumns
2242 : parrello 1.28
2243 : parrello 1.38 $shelp->DefaultColumns($rhelp);
2244 : parrello 1.28
2245 : parrello 1.34 Store the default columns in the result helper. The default action is just to ask
2246 :     the result helper for its default columns, but this may be changed by overriding
2247 :     this method.
2248 : parrello 1.28
2249 :     =over 4
2250 :    
2251 : parrello 1.34 =item rhelp
2252 : parrello 1.28
2253 : parrello 1.34 Result helper object in which the column list should be stored.
2254 : parrello 1.28
2255 :     =back
2256 :    
2257 :     =cut
2258 :    
2259 : parrello 1.34 sub DefaultColumns {
2260 : parrello 1.28 # Get the parameters.
2261 : parrello 1.34 my ($self, $rhelp) = @_;
2262 :     # Get the default columns from the result helper.
2263 :     my @cols = $rhelp->DefaultResultColumns();
2264 :     # Store them back.
2265 :     $rhelp->SetColumns(@cols);
2266 : parrello 1.28 }
2267 :    
2268 : parrello 1.34 =head3 Hint
2269 : parrello 1.32
2270 : parrello 1.38 my $htmlText = SearchHelper::Hint($wikiPage, $hintText);
2271 : parrello 1.32
2272 : parrello 1.34 Return the HTML for a small question mark that displays the specified hint text when it is clicked.
2273 :     This HTML can be put in forms to provide a useful hinting mechanism.
2274 : parrello 1.32
2275 :     =over 4
2276 :    
2277 : parrello 1.37 =item wikiPage
2278 :    
2279 : parrello 1.39 Name of the wiki page to be popped up when the hint mark is clicked.
2280 : parrello 1.37
2281 : parrello 1.34 =item hintText
2282 : parrello 1.32
2283 : parrello 1.34 Text to display for the hint. It is raw html, but may not contain any double quotes.
2284 : parrello 1.32
2285 :     =item RETURN
2286 :    
2287 : parrello 1.34 Returns the html for the hint facility. The resulting html shows a small button-like thing that
2288 :     uses the standard FIG popup technology.
2289 : parrello 1.32
2290 :     =back
2291 :    
2292 :     =cut
2293 :    
2294 : parrello 1.34 sub Hint {
2295 :     # Get the parameters.
2296 : parrello 1.37 my ($wikiPage, $hintText) = @_;
2297 : parrello 1.41 # Ask Sprout to draw the hint button for us.
2298 :     return Sprout::Hint($wikiPage, $hintText);
2299 : parrello 1.32 }
2300 :    
2301 :    
2302 : parrello 1.38 1;

MCS Webmaster
ViewVC Help
Powered by ViewVC 1.0.3