File:  [LON-CAPA] / loncom / interface / lonsearchcat.pm
Revision 1.143: download - view: text, annotated - select for diffs
Tue Jul 16 15:02:06 2002 UTC (21 years, 10 months ago) by matthew
Branches: MAIN
CVS tags: HEAD
Very beginnings of results database started.
&handler, &parse_basic_search, and &parse_advanced_search
    Added support for 'pretty' version of query string which appears at the
    top of the search results page.
&search_results_header
    Print out the pretty query string.

    1: # The LearningOnline Network with CAPA
    2: # Search Catalog
    3: #
    4: # $Id: lonsearchcat.pm,v 1.143 2002/07/16 15:02:06 matthew Exp $
    5: #
    6: # Copyright Michigan State University Board of Trustees
    7: #
    8: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
    9: #
   10: # LON-CAPA is free software; you can redistribute it and/or modify
   11: # it under the terms of the GNU General Public License as published by
   12: # the Free Software Foundation; either version 2 of the License, or
   13: # (at your option) any later version.
   14: #
   15: # LON-CAPA is distributed in the hope that it will be useful,
   16: # but WITHOUT ANY WARRANTY; without even the implied warranty of
   17: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   18: # GNU General Public License for more details.
   19: #
   20: # You should have received a copy of the GNU General Public License
   21: # along with LON-CAPA; if not, write to the Free Software
   22: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
   23: #
   24: # /home/httpd/html/adm/gpl.txt
   25: #
   26: # http://www.lon-capa.org/
   27: #
   28: # YEAR=2001
   29: # 3/8, 3/12, 3/13, 3/14, 3/15, 3/19 Scott Harrison
   30: # 3/20, 3/21, 3/22, 3/26, 3/27, 4/2, 8/15, 8/24, 8/25 Scott Harrison
   31: # 10/12,10/14,10/15,10/16,11/28,11/29,12/10,12/12,12/16 Scott Harrison
   32: # YEAR=2002
   33: # 1/17 Scott Harrison
   34: # 6/17 Matthew Hall
   35: #
   36: ###############################################################################
   37: ###############################################################################
   38: 
   39: =pod 
   40: 
   41: =head1 NAME
   42: 
   43: lonsearchcat - LONCAPA Search Interface
   44: 
   45: =head1 SYNOPSIS
   46: 
   47: Search interface to LON-CAPAs digital library
   48: 
   49: =head1 DESCRIPTION
   50: 
   51: This module enables searching for a distributed browseable catalog.
   52: 
   53: This is part of the LearningOnline Network with CAPA project
   54: described at http://www.lon-capa.org.
   55: 
   56: lonsearchcat presents the user with an interface to search the LON-CAPA
   57: digital library.  lonsearchcat also initiates the execution of a search
   58: by sending the search parameters to LON-CAPA servers.  The progress of 
   59: search (on a server basis) is displayed to the user in a seperate window.
   60: 
   61: =head1 Internals
   62: 
   63: =over 4
   64: 
   65: =cut
   66: 
   67: ###############################################################################
   68: ###############################################################################
   69: 
   70: ###############################################################################
   71: ##                                                                           ##
   72: ## ORGANIZATION OF THIS PERL MODULE                                          ##
   73: ##                                                                           ##
   74: ## 1. Modules used by this module                                            ##
   75: ## 2. Variables used throughout the module                                   ##
   76: ## 3. handler subroutine called via Apache and mod_perl                      ##
   77: ## 4. Other subroutines                                                      ##
   78: ##                                                                           ##
   79: ###############################################################################
   80: 
   81: package Apache::lonsearchcat;
   82: 
   83: # ------------------------------------------------- modules used by this module
   84: use strict;
   85: use Apache::Constants qw(:common);
   86: use Apache::lonnet();
   87: use Apache::File();
   88: use CGI qw(:standard);
   89: use Text::Query;
   90: use GDBM_File;
   91: use Apache::loncommon();
   92: 
   93: # ---------------------------------------- variables used throughout the module
   94: 
   95: ######################################################################
   96: ######################################################################
   97: 
   98: =pod 
   99: 
  100: =item Global variables
  101: 
  102: =over 4
  103: 
  104: =item $closebutton
  105: 
  106: button that closes the search window
  107: 
  108: =item $importbutton
  109: 
  110: button to take the select results and go to group sorting
  111: 
  112: =item %groupsearch_db   
  113: 
  114: Database hash used to save values for the groupsearch RAT interface.
  115: 
  116: =item $diropendb 
  117: 
  118: The full path to the (temporary) search database file.  This is set and
  119: used in &handler() and is also used in &output_results().
  120: 
  121: =item %Views
  122: 
  123: Hash which associates an output view description with the function
  124: that produces it.  Adding a new view type should be as easy as
  125: adding a line to the definition of this hash and making sure the function
  126: takes the proper parameters.
  127: 
  128: =item $results_db
  129: 
  130: The name of the database results from searches are put in.
  131: 
  132: =back 
  133: 
  134: =cut
  135: 
  136: ######################################################################
  137: ######################################################################
  138: 
  139: # -- dynamically rendered interface components
  140: my $closebutton;  # button that closes the search window
  141: my $importbutton; # button to take the selected results and go to group sorting
  142: 
  143: # -- miscellaneous variables
  144: my %groupsearch_db;     # database hash
  145: my $diropendb = "";    # db file
  146: 
  147: my $results_db = "";
  148: #             View Description           Function Pointer
  149: my %Views = ("Detailed Citation View" => \&detailed_citation_view,
  150:              "Summary View"           => \&summary_view,
  151:              "Fielded Format"         => \&fielded_format_view,
  152:              "XML/SGML"               => \&xml_sgml_view );
  153: 
  154: ######################################################################
  155: ######################################################################
  156: 
  157: =pod 
  158: 
  159: =item &handler() - main handler invoked by httpd child
  160: 
  161: =item Variables
  162: 
  163: =over 4
  164: 
  165: =item $hidden
  166: 
  167: holds 'hidden' html forms
  168: 
  169: =item $scrout
  170: 
  171: string that holds portions of the screen output
  172: 
  173: =back 
  174: 
  175: =cut
  176: 
  177: ######################################################################
  178: ######################################################################
  179: sub handler {
  180:     my $r = shift;
  181:     untie %groupsearch_db;
  182: 
  183:     $r->content_type('text/html');
  184:     $r->send_http_header;
  185:     return OK if $r->header_only;
  186:     ##
  187:     ## Initialize global variables
  188:     ##
  189:     my $domain  = $r->dir_config('lonDefDomain');
  190:     $diropendb= "/home/httpd/perl/tmp/".&Apache::lonnet::escape($domain).
  191:             "\_".&Apache::lonnet::escape($ENV{'user.name'})."_searchcat.db";
  192:     $results_db = "/home/httpd/perl/tmp/".&Apache::lonnet::escape($domain).
  193:         '_'.&Apache::lonnet::escape($ENV{'user.name'})."_searchresults.db";
  194:     &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
  195:              ['catalogmode','launch','acts','mode','form','element',
  196:               'reqinterface']);
  197:     ##
  198:     ## Clear out old values from groupsearch database
  199:     ##
  200:     if ($ENV{'form.launch'} eq '1') {
  201: 	if (tie(%groupsearch_db,'GDBM_File',$diropendb,&GDBM_WRCREAT,0640)) {
  202: 	    &start_fresh_session();
  203: 	    untie %groupsearch_db;
  204: 	} else {
  205: 	    $r->print('<html><head></head><body>Unable to tie hash to db '.
  206: 		      'file</body></html>');
  207: 	    return OK;
  208: 	}
  209:     }
  210:     ##
  211:     ## Produce some output, so people know it is working
  212:     ##
  213:     $r->print("\n");
  214:     $r->rflush;
  215:     ##
  216:     ## Configure dynamic components of interface
  217:     ##
  218:     my $hidden;       # Holds 'hidden' html forms
  219:     if ($ENV{'form.catalogmode'} eq 'interactive') {
  220: 	$hidden="<input type='hidden' name='catalogmode' value='interactive'>".
  221: 	    "\n";
  222:         $closebutton="<input type='button' name='close' value='CLOSE' ".
  223: 	    "onClick='self.close()'>"."\n";
  224:     } elsif ($ENV{'form.catalogmode'} eq 'groupsearch') {
  225: 	$hidden=<<END;
  226: <input type='hidden' name='catalogmode' value='groupsearch'>
  227: END
  228:         $closebutton=<<END;
  229: <input type='button' name='close' value='CLOSE' onClick='self.close()'>
  230: END
  231:         $importbutton=<<END;
  232: <input type='button' name='import' value='IMPORT'
  233: onClick='javascript:select_group()'>
  234: END
  235:     }
  236:     $hidden .= &make_persistent({ "form.mode"    => $ENV{'form.mode'},
  237:                                   "form.form"    => $ENV{'form.form'},
  238:                                   "form.element" => $ENV{'form.element'},
  239:                                   "form.date"    => 2 });
  240:     ##
  241:     ##  What are we doing?
  242:     ##
  243:     my $searchtype;
  244:     $searchtype = 'Basic'    if ($ENV{'form.basicsubmit'}    eq 'SEARCH');
  245:     $searchtype = 'Advanced' if ($ENV{'form.advancedsubmit'} eq 'SEARCH');
  246:     if ($searchtype) {
  247:         # We are running a search
  248:         my ($query,$customquery,$customshow,$libraries) = 
  249:             (undef,undef,undef,undef);
  250:         my $pretty_string;
  251:         if ($searchtype eq 'Basic') {
  252:             ($query,$pretty_string) = &parse_basic_search($r);
  253:         } elsif ($ENV{'form.advancedsubmit'} eq 'SEARCH') {
  254:             ($query,$customquery,$customshow,$libraries,$pretty_string) 
  255:                 = &parse_advanced_search($r);
  256:             return OK if (! defined($query));
  257:         }
  258:         # Output some information to the user.
  259:         $r->print(&search_results_header($searchtype,$pretty_string));
  260:         $r->print("Sending search request to LON-CAPA servers.<br />\n");
  261:         $r->rflush();
  262:         # Send query statements over the network to be processed by 
  263:         # either the SQL database or a recursive scheme of 'grep'-like 
  264:         # actions (for custom metadata).
  265:         my $reply=&Apache::lonnet::metadata_query($query,$customquery,
  266:                                                $customshow,$libraries);
  267:         $r->rflush();
  268:         &output_results($searchtype,$r,$reply,$hidden);
  269:     } else {
  270:         #
  271:         # We need to get information to search on
  272:         #
  273:         # Set the default view if it is not already set.
  274:         if (!defined($ENV{'form.viewselect'})) {
  275:             $ENV{'form.viewselect'} ="Detailed Citation View";
  276:         }
  277:         # Output the advanced interface
  278:         if ($ENV{'form.reqinterface'} eq 'advanced') {
  279:             $r->print(&advanced_search_form($closebutton,$hidden));
  280:         } else { 
  281:             # Output normal search interface
  282:             $r->print(&basic_search_form($closebutton,$hidden));
  283:         }
  284:     }
  285:     return OK;
  286: } 
  287: 
  288: ######################################################################
  289: ######################################################################
  290: 
  291: =pod 
  292: 
  293: =item &basic_search_form() 
  294: 
  295: Returns a scalar which holds html for the basic search form.
  296: 
  297: =cut
  298: 
  299: ######################################################################
  300: ######################################################################
  301: 
  302: sub basic_search_form{
  303:     my ($closebutton,$hidden) = @_;
  304:     my $scrout=<<"ENDDOCUMENT";
  305: <html>
  306: <head>
  307: <title>The LearningOnline Network with CAPA</title>
  308: <script type="text/javascript">
  309:     function openhelp(val) {
  310: 	openhelpwin=open('/adm/help/searchcat.html','helpscreen',
  311: 	     'scrollbars=1,width=600,height=300');
  312: 	openhelpwin.focus();
  313:     }
  314: </script>
  315: </head>
  316: <body bgcolor="#FFFFFF">
  317: <img align='right' src='/adm/lonIcons/lonlogos.gif' />
  318: <h1>Search Catalog</h1>
  319: <form method="post" action="/adm/searchcat">
  320: $hidden
  321: <h3>Basic Search</h3>
  322: <p>
  323: Enter terms or phrases separated by AND, OR, or NOT 
  324: then press SEARCH below.
  325: </p>
  326: <p>
  327: <table>
  328: <tr><td>
  329: ENDDOCUMENT
  330:     $scrout.='&nbsp;'.&simpletextfield('basicexp',$ENV{'form.basicexp'},40).
  331:         '&nbsp;';
  332: #    $scrout.=&simplecheckbox('allversions',$ENV{'form.allversions'});
  333: #    $scrout.='<font color="#800000">Search historic archives</font>';
  334:     my $checkbox = &simplecheckbox('related',$ENV{'form.related'});
  335:     $scrout.=<<END;
  336: </td><td><a href="/adm/searchcat?reqinterface=advanced">Advanced Search</a></td></tr>
  337: <tr><td>$checkbox use related words</td><td></td></tr>
  338: </table>
  339: </p>
  340: <p>
  341: &nbsp;<input type="submit" name="basicsubmit" value='SEARCH' />&nbsp;
  342: $closebutton
  343: END
  344:     $scrout.=&selectbox(undef,'viewselect',
  345: 			$ENV{'form.viewselect'},
  346: 			undef,undef,undef,
  347: 			sort(keys(%Views)));
  348:     $scrout.=<<ENDDOCUMENT;
  349: <input type="button" value="HELP" onClick="openhelp()" />
  350: </p>
  351: </form>
  352: </body>
  353: </html>
  354: ENDDOCUMENT
  355:     return $scrout;
  356: }
  357: ######################################################################
  358: ######################################################################
  359: 
  360: =pod 
  361: 
  362: =item &advanced_search_form() 
  363: 
  364: Returns a scalar which holds html for the advanced search form.
  365: 
  366: =cut
  367: 
  368: ######################################################################
  369: ######################################################################
  370: 
  371: sub advanced_search_form{
  372:     my ($closebutton,$hidden) = @_;
  373:     my $advanced_buttons = <<"END";
  374: <p>
  375: <input type="submit" name="advancedsubmit" value='SEARCH' />
  376: <input type="reset" name="reset" value='RESET' />
  377: $closebutton
  378: <input type="button" value="HELP" onClick="openhelp()" />
  379: </p>
  380: END
  381:     if (!defined($ENV{'form.viewselect'})) {
  382:         $ENV{'form.viewselect'} ="Detailed Citation View";
  383:     }
  384:     my $scrout=<<"ENDHEADER";
  385: <html>
  386: <head>
  387: <title>The LearningOnline Network with CAPA</title>
  388: <script type="text/javascript">
  389:     function openhelp(val) {
  390: 	openhelpwin=open('/adm/help/searchcat.html','helpscreen',
  391: 	     'scrollbars=1,width=600,height=300');
  392: 	openhelpwin.focus();
  393:     }
  394: </script>
  395: </head>
  396: <body bgcolor="#FFFFFF">
  397: <img align='right' src='/adm/lonIcons/lonlogos.gif' />
  398: <h1>Advanced Catalog Search</h1>
  399: <hr />
  400: Enter terms or phrases separated by search operators 
  401: such as AND, OR, or NOT.<br />
  402: <form method="post" action="/adm/searchcat">
  403: $advanced_buttons
  404: $hidden
  405: <table>
  406: <tr><td><font color="#800000" face="helvetica"><b>VIEW:</b></font></td>
  407: <td>
  408: ENDHEADER
  409:     $scrout.=&selectbox(undef,'viewselect',
  410: 			$ENV{'form.viewselect'},
  411: 			undef,undef,undef,
  412: 			sort(keys(%Views)));
  413:     $scrout.="</td><td>Related<br />Words</td></tr>\n";
  414:     $scrout.=&searchphrasefield_with_related('title',   'title'   ,
  415:                                              $ENV{'form.title'});
  416:     $scrout.=&searchphrasefield('author',  'author'  ,$ENV{'form.author'});
  417:     $scrout.=&searchphrasefield_with_related('subject', 'subject' ,
  418:                                              $ENV{'form.subject'});
  419:     $scrout.=&searchphrasefield_with_related('keywords','keywords',
  420:                                              $ENV{'form.keywords'});
  421:     $scrout.=&searchphrasefield('URL',     'url'     ,$ENV{'form.url'});
  422:     $scrout.=&searchphrasefield_with_related('notes',   'notes'   ,
  423:                                              $ENV{'form.notes'});
  424:     $scrout.=&searchphrasefield_with_related('abstract','abstract',
  425:                                              $ENV{'form.abstract'});
  426:     # Hack - an empty table row.
  427:     $scrout.="<tr><td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td></tr>\n";
  428:     $scrout.=&searchphrasefield('file<br />extension','mime',
  429:                         $ENV{'form.mime'});
  430:     $scrout.="<tr><td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td></tr>\n";
  431:     $scrout.=&searchphrasefield('publisher<br />owner','owner',
  432: 				$ENV{'form.owner'});
  433:     $scrout.="</table>\n";
  434:     $ENV{'form.category'}='any' unless length($ENV{'form.category'});
  435:     $scrout.=&selectbox('File Category','category',
  436: 			$ENV{'form.category'},
  437: 			'any','Any category',
  438: 			undef,
  439: 			(&Apache::loncommon::filecategories()));
  440:     $ENV{'form.language'}='any' unless length($ENV{'form.language'});
  441:     #----------------------------------------------------------------
  442:     # Allow restriction to multiple domains.
  443:     #   I make the crazy assumption that there will never be a domain 'any'.
  444:     #
  445:     $ENV{'form.domains'} = 'any' if (! exists($ENV{'form.domains'}));
  446:     my @allowed_domains = (ref($ENV{'form.domains'}) ? @{$ENV{'form.domains'}} 
  447:                            :  ($ENV{'form.domains'}) );
  448:     my %domain_hash = ();
  449:     foreach (@allowed_domains) {
  450:         $domain_hash{$_}++;
  451:     }
  452:     my @domains =&Apache::loncommon::get_domains();
  453:     # adjust the size of the select box
  454:     my $size = 4;
  455:     my $size = (scalar @domains < ($size - 1) ? scalar @domains + 1 : $size);
  456:     # standalone machines do not get to choose a domain to search.
  457:     if ((scalar @domains) == 1) {
  458:         $scrout .='<input type="hidden" name="domains" value="any" />'."\n";
  459:     } else {
  460:         $scrout.="\n".'<font color="#800000" face="helvetica"><b>'.
  461:             'DOMAINS</b></font><br />'.
  462:                 '<select name="domains" size="'.$size.'" multiple>'."\n".
  463:                     '<option name="any" value="any" '.
  464:                         ($domain_hash{'any'}? 'selected ' :'').
  465:                         '>all domains</option>'."\n";
  466:         foreach my $dom (sort @domains) {
  467:             $scrout.="<option name=\"$dom\" ".
  468:                 ($domain_hash{$dom} ? 'selected ' :'').">$dom</option>\n";
  469:         }
  470:         $scrout.="</select>\n";
  471:     }
  472:     #----------------------------------------------------------------
  473:     $scrout.=&selectbox('Limit by language','language',
  474: 			$ENV{'form.language'},'any','Any Language',
  475: 			\&{Apache::loncommon::languagedescription},
  476: 			(&Apache::loncommon::languageids),
  477: 			);
  478: # ------------------------------------------------ Compute date selection boxes
  479:     $scrout.=<<CREATIONDATESTART;
  480: <p>
  481: <font color="#800000" face="helvetica"><b>LIMIT BY CREATION DATE RANGE:</b>
  482: </font>
  483: <br />
  484: between:
  485: CREATIONDATESTART
  486:     $scrout.=&dateboxes('creationdatestart',1,1,1976,
  487: 			$ENV{'form.creationdatestart_month'},
  488: 			$ENV{'form.creationdatestart_day'},
  489: 			$ENV{'form.creationdatestart_year'},
  490: 			);
  491:     $scrout.="and:\n";
  492:     $scrout.=&dateboxes('creationdateend',12,31,2051,
  493: 			$ENV{'form.creationdateend_month'},
  494: 			$ENV{'form.creationdateend_day'},
  495: 			$ENV{'form.creationdateend_year'},
  496: 			);
  497:     $scrout.="</p>";
  498:     $scrout.=<<LASTREVISIONDATESTART;
  499: <p>
  500: <font color="#800000" face="helvetica"><b>LIMIT BY LAST REVISION DATE RANGE:
  501: </b></font>
  502: <br />between:
  503: LASTREVISIONDATESTART
  504:     $scrout.=&dateboxes('lastrevisiondatestart',1,1,1976,
  505: 			$ENV{'form.lastrevisiondatestart_month'},
  506: 			$ENV{'form.lastrevisiondatestart_day'},
  507: 			$ENV{'form.lastrevisiondatestart_year'},
  508: 			);
  509:     $scrout.=<<LASTREVISIONDATEEND;
  510: and:
  511: LASTREVISIONDATEEND
  512:     $scrout.=&dateboxes('lastrevisiondateend',12,31,2051,
  513: 			$ENV{'form.lastrevisiondateend_month'},
  514: 			$ENV{'form.lastrevisiondateend_day'},
  515: 			$ENV{'form.lastrevisiondateend_year'},
  516: 			);
  517:     $scrout.='</p>';
  518:     $ENV{'form.copyright'}='any' unless length($ENV{'form.copyright'});
  519:     $scrout.=&selectbox('Limit by copyright/distribution','copyright',
  520: 			 $ENV{'form.copyright'},
  521: 			 'any','Any copyright/distribution',
  522: 			 \&{Apache::loncommon::copyrightdescription},
  523: 			 (&Apache::loncommon::copyrightids),
  524: 			 );
  525: # ------------------------------------------- Compute customized metadata field
  526:     $scrout.=<<CUSTOMMETADATA;
  527: <p>
  528: <font color="#800000" face="helvetica"><b>LIMIT BY SPECIAL METADATA FIELDS:</b>
  529: </font>
  530: For resource-specific metadata, enter in an expression in the form of 
  531: <i>key</i>=<i>value</i> separated by operators such as AND, OR or NOT.<br />
  532: <b>Example:</b> grandmother=75 OR grandfather=85
  533: <br />
  534: CUSTOMMETADATA
  535:     $scrout.=&simpletextfield('custommetadata',$ENV{'form.custommetadata'});
  536:     $scrout.=<<CUSTOMSHOW;
  537: <p>
  538: <font color="#800000" face="helvetica"><b>SHOW SPECIAL METADATA FIELDS:</b>
  539: </font>
  540: Enter in a space-separated list of special metadata fields to show
  541: in a fielded listing for each record result.
  542: <br />
  543: CUSTOMSHOW
  544:     $scrout.=&simpletextfield('customshow',$ENV{'form.customshow'});
  545:     $scrout.=<<ENDDOCUMENT;
  546: $advanced_buttons
  547: </form>
  548: </body>
  549: </html>
  550: ENDDOCUMENT
  551:     return $scrout;
  552: }
  553: 
  554: ######################################################################
  555: ######################################################################
  556: 
  557: =pod 
  558: 
  559: =item &make_persistent() 
  560: 
  561: Returns a scalar which holds the current ENV{'form.*'} values in
  562: a 'hidden' html input tag.  This allows search interface information
  563: to be somewhat persistent.
  564: 
  565: =cut
  566: 
  567: ######################################################################
  568: ######################################################################
  569: 
  570: sub make_persistent {
  571:     my %save = %{shift()};
  572:     my $persistent='';
  573:     foreach my $name (keys %save) {
  574: 	if ($name =~ /^form\./ && $name !~ /submit/) {
  575:             my @values = (ref($save{$name}) ? @{$save{$name}} : ($save{$name}));
  576: 	    $name=~s/^form\.//;
  577:             foreach (@values) {
  578:                 s/\"/\'/g; # do not mess with html field syntax
  579:                 next if (! $_ );
  580:                 $persistent.=<<END;
  581: <input type="hidden" name="$name" value="$_" />
  582: END
  583:             }
  584:         }
  585:     }
  586:     return $persistent;
  587: }
  588: 
  589: ######################################################################
  590: #                HTML form building functions                        #  
  591: ######################################################################
  592: 
  593: =pod 
  594: 
  595: =item HTML form building functions
  596: 
  597: =over 4
  598: 
  599: =cut
  600: 
  601: ###############################################
  602: ###############################################
  603: 
  604: =pod
  605: 
  606: =item &simpletextfield() 
  607: 
  608: Inputs: $name,$value,$size
  609: 
  610: Returns a text input field with the given name, value, and size.  
  611: If size is not specified, a value of 20 is used.
  612: 
  613: =cut
  614: 
  615: ###############################################
  616: ###############################################
  617: 
  618: sub simpletextfield {
  619:     my ($name,$value,$size)=@_;
  620:     $size = 20 if (! defined($size));
  621:     return '<input type="text" name="'.$name.
  622:         '" size="'.$size.'" value="'.$value.'" />';
  623: }
  624: 
  625: ###############################################
  626: ###############################################
  627: 
  628: =pod
  629: 
  630: =item &simplecheckbox()
  631: 
  632: Inputs: $name,$value
  633: 
  634: Returns a simple check box with the given $name.
  635: If $value eq 'on' the box is checked.
  636: 
  637: =cut
  638: 
  639: ###############################################
  640: ###############################################
  641: 
  642: sub simplecheckbox {
  643:     my ($name,$value)=@_;
  644:     my $checked='';
  645:     $checked="checked" if $value eq 'on';
  646:     return '<input type="checkbox" name="'.$name.'" '. $checked . ' />';
  647: }
  648: 
  649: ###############################################
  650: ###############################################
  651: 
  652: =pod
  653: 
  654: =item &fieldtitle()
  655: 
  656: Input: $title
  657: 
  658: Returns a scalar with html which will display $title as a search
  659: field heading.
  660: 
  661: =cut
  662: 
  663: ###############################################
  664: ###############################################
  665: 
  666: sub fieldtitle {
  667:     my $title = uc(shift());
  668:     return '<font color="#800000" face="helvetica"><b>'.$title.
  669:         ':&nbsp;</b></font>';
  670: }
  671: 
  672: ###############################################
  673: ###############################################
  674: 
  675: =pod
  676: 
  677: =item &searchphrasefield()
  678: 
  679: Inputs: $title,$name,$value
  680: 
  681: Returns html for a title line and an input field for entering search terms.
  682: The entry field (which is where the $name and $value are used) is a 50 column 
  683: simpletextfield.  The html returned is for a row in a three column table.
  684: 
  685: =cut
  686: 
  687: ###############################################
  688: ###############################################
  689:     
  690: sub searchphrasefield {
  691:     my ($title,$name,$value)=@_;
  692:     return '<tr><td>'.&fieldtitle($title).'</td><td>'.
  693:         &simpletextfield($name,$value,50)."</td><td>&nbsp;</td></tr>\n";
  694: }
  695: 
  696: ###############################################
  697: ###############################################
  698: 
  699: =pod
  700: 
  701: =item &searchphrasefield_with_related()
  702: 
  703: Inputs: $title,$name,$value
  704: 
  705: Returns html for a title line and an input field for entering search terms
  706: and a check box for 'related words'.  The entry field (which is where the 
  707: $name and $value are used) is a 50 column simpletextfield.  The name of
  708: the related words checkbox is "$name_related".
  709: 
  710: =cut
  711: 
  712: ###############################################
  713: ###############################################
  714:     
  715: sub searchphrasefield_with_related {
  716:     my ($title,$name,$value)=@_;
  717:     return '<tr><td>'.&fieldtitle($title).'</td><td>'.
  718:         &simpletextfield($name,$value,50).'</td><td align="center">&nbsp;'.
  719:             &simplecheckbox($name.'_related',$ENV{'form.'.$name.'_related'}).
  720:                 "&nbsp;</td></tr>\n";
  721: }
  722: 
  723: ###############################################
  724: ###############################################
  725: 
  726: =pod
  727: 
  728: =item &dateboxes()
  729: 
  730: Returns html selection form elements for the specification of 
  731: the day, month, and year.
  732: 
  733: =cut
  734: 
  735: ###############################################
  736: ###############################################
  737: 
  738: sub dateboxes {
  739:     my ($name,$defaultmonth,$defaultday,$defaultyear,
  740: 	$currentmonth,$currentday,$currentyear)=@_;
  741:     ($defaultmonth,$defaultday,$defaultyear)=('','','');
  742:     #
  743:     # Day
  744:     my $day=<<END;
  745: <select name="${name}_day">
  746: <option value='$defaultday'> </option>
  747: END
  748:     for (my $i = 1; $i<=31; $i++) {
  749: 	$day.="<option value=\"$i\">$i</option>\n";
  750:     }
  751:     $day.="</select>\n";
  752:     $day=~s/(\"$currentday\")/$1 SELECTED/ if length($currentday);
  753:     #
  754:     # Month
  755:     my $month=<<END;
  756: <select name="${name}_month">
  757: <option value='$defaultmonth'> </option>
  758: END
  759:     my $i = 1;
  760:     foreach (qw/January February March April May June 
  761: 	     July August September October November December /){
  762: 	$month .="<option value=\"$i\">$_</option>\n";
  763: 	$i++;
  764:     }
  765:     $month.="</select>\n";
  766:     $month=~s/(\"$currentmonth\")/$1 SELECTED/ if length($currentmonth);
  767:     #
  768:     # Year (obviously)
  769:     my $year=<<END;
  770: <select name="${name}_year">
  771: <option value='$defaultyear'> </option>
  772: END
  773:     my $maxyear = 2051; 
  774:     for (my $i = 1976; $i<=$maxyear; $i++) {
  775: 	$year.="<option value=\"$i\">$i</option>\n";
  776:     }
  777:     $year.="</select>\n";
  778:     $year=~s/(\"$currentyear\")/$1 SELECTED/ if length($currentyear);
  779:     return "$month$day$year";
  780: }
  781: 
  782: ###############################################
  783: ###############################################
  784: 
  785: =pod
  786: 
  787: =item &selectbox()
  788: 
  789: Returns a scalar containing an html <select> form.  
  790: 
  791: Inputs: 
  792: 
  793: =over 4
  794: 
  795: =item $title 
  796: 
  797: Printed above the select box, in uppercase.  If undefined, only a select
  798: box will be returned, with no additional html.
  799: 
  800: =item $name 
  801: 
  802: The name element of the <select> tag.
  803: 
  804: =item $default 
  805: 
  806: The default value of the form.  Can be $anyvalue, or in @idlist.
  807: 
  808: =item $anyvalue 
  809: 
  810: The <option value="..."> used to indicate a default of 
  811: none of the values.  Can be undef.
  812: 
  813: =item $anytag 
  814: 
  815: The text associate with $anyvalue above.
  816: 
  817: =item $functionref 
  818: 
  819: Each element in @idlist will be passed as a parameter 
  820: to the function referenced here.  The return value of the function should
  821: be a scalar description of the items.  If this value is undefined the 
  822: description of each item in @idlist will be the item name.
  823: 
  824: =item @idlist 
  825: 
  826: The items to be selected from.  One of these or $anyvalue will be the 
  827: value returned by the form element, $ENV{form.$name}.
  828: 
  829: =back
  830: 
  831: =cut
  832: 
  833: ###############################################
  834: 
  835: sub selectbox {
  836:     my ($title,$name,$default,$anyvalue,$anytag,$functionref,@idlist)=@_;
  837:     if (! defined($functionref)) { $functionref = sub { $_[0]}; }
  838:     my $selout='';
  839:     if (defined($title)) {
  840:         my $uctitle=uc($title);
  841:         $selout="\n".'<p><font color="#800000" face="helvetica">'.
  842:             '<b>'.$uctitle.': </b></font>';
  843:     }
  844:     $selout .= '<select name="'.$name.'">';
  845:     unshift @idlist,$anyvalue if (defined($anyvalue));
  846:     foreach (@idlist) {
  847:         $selout.='<option value="'.$_.'"';
  848:         if ($_ eq $default and !/^any$/) {
  849: 	    $selout.=' selected >'.&{$functionref}($_).'</option>';
  850: 	}
  851: 	elsif ($_ eq $default and /^$anyvalue$/) {
  852: 	    $selout.=' selected >'.$anytag.'</option>';
  853: 	}
  854:         else {$selout.='>'.&{$functionref}($_).'</option>';}
  855:     }
  856:     return $selout.'</select>'.(defined($title)?'</p>':' ');
  857: }
  858: 
  859: ######################################################################
  860: #                End of HTML form building functions                 #  
  861: ######################################################################
  862: 
  863: =pod
  864: 
  865: =back 
  866: 
  867: =cut
  868: 
  869: 
  870: ######################################################################
  871: ######################################################################
  872: 
  873: =pod 
  874: 
  875: =item &parse_advanced_search()
  876: 
  877: Parse advanced search form and return the following:
  878: 
  879: =over 4
  880: 
  881: =item $query Scalar containing an SQL query.
  882: 
  883: =item $customquery Scalar containing a custom query.
  884: 
  885: =item $customshow Scalar containing commands to show custom metadata.
  886: 
  887: =item $libraries_to_query Reference to array of domains to search.
  888: 
  889: =back
  890: 
  891: =cut
  892: 
  893: ######################################################################
  894: ######################################################################
  895: sub parse_advanced_search {
  896:     my ($r)=@_;
  897:     my $fillflag=0;
  898:     my $pretty_search_string = "<br />\n";
  899:     # Clean up fields for safety
  900:     for my $field ('title','author','subject','keywords','url','version',
  901: 		   'creationdatestart_month','creationdatestart_day',
  902: 		   'creationdatestart_year','creationdateend_month',
  903: 		   'creationdateend_day','creationdateend_year',
  904: 		   'lastrevisiondatestart_month','lastrevisiondatestart_day',
  905: 		   'lastrevisiondatestart_year','lastrevisiondateend_month',
  906: 		   'lastrevisiondateend_day','lastrevisiondateend_year',
  907: 		   'notes','abstract','mime','language','owner',
  908: 		   'custommetadata','customshow','category') {
  909: 	$ENV{"form.$field"}=~s/[^\w\/\s\(\)\=\-\"\']//g;
  910:     }
  911:     foreach ('mode','form','element') {
  912: 	# is this required?  Hmmm.
  913: 	next unless (exists($ENV{"form.$_"}));
  914: 	$ENV{"form.$_"}=&Apache::lonnet::unescape($ENV{"form.$_"});
  915: 	$ENV{"form.$_"}=~s/[^\w\/\s\(\)\=\-\"\']//g;
  916:     }
  917:     # Preprocess the category form element.
  918:     if ($ENV{'form.category'} ne 'any') {
  919:         my @extensions = &Apache::loncommon::filecategorytypes
  920:             ($ENV{'form.category'});
  921:         $ENV{'form.mime'} = join ' OR ',@extensions;
  922:     }
  923:     # Check to see if enough information was filled in
  924:     for my $field ('title','author','subject','keywords','url','version',
  925: 		   'notes','abstract','mime','language','owner',
  926: 		   'custommetadata') {
  927: 	if (&filled($ENV{"form.$field"})) {
  928: 	    $fillflag++;
  929: 	}
  930:     }
  931:     unless ($fillflag) {
  932: 	&output_blank_field_error($r);
  933: 	return ;
  934:     }
  935:     # Turn the form input into a SQL-based query
  936:     my $query='';
  937:     my @queries;
  938:     my $font = '<font color="#800000" face="helvetica">';
  939:     # Evaluate logical expression AND/OR/NOT phrase fields.
  940:     foreach my $field ('title','author','subject','notes','abstract','url',
  941: 		       'keywords','version','owner','mime') {
  942: 	if ($ENV{'form.'.$field}) {
  943:             my $searchphrase = $ENV{'form.'.$field};
  944:             $pretty_search_string .= $font."$field</font> contains <b>".
  945:                 $searchphrase."</b>";
  946:             if ($ENV{'form.'.$field.'_related'}) {
  947:                 my @New_Words;
  948:                 ($searchphrase,@New_Words) = &related_version($searchphrase);
  949:                 if (@New_Words) {
  950:                     $pretty_search_string .= " with related words: ".
  951:                         "<b>@New_Words</b>.";
  952:                 } else {
  953:                     $pretty_search_string .= " with no related words.";
  954:                 }
  955:             }
  956:             $pretty_search_string .= "<br />\n";
  957: 	    push @queries,&build_SQL_query($field,$searchphrase);
  958:         }
  959:     }
  960:     # I dislike the hack below.
  961:     if ($ENV{'form.category'}) {
  962:         $ENV{'form.mime'}='';
  963:     }
  964:     # Evaluate option lists
  965:     if ($ENV{'form.language'} and $ENV{'form.language'} ne 'any') {
  966: 	push @queries,"(language like \"$ENV{'form.language'}\")";
  967:         $pretty_search_string.=$font."language</font>= ".
  968:             &Apache::loncommon::languagedescription($ENV{'form.language'}).
  969:                 "<br />\n";
  970:     }
  971:     if ($ENV{'form.copyright'} and $ENV{'form.copyright'} ne 'any') {
  972: 	push @queries,"(copyright like \"$ENV{'form.copyright'}\")";
  973:         $pretty_search_string.=$font."copyright</font> = ".
  974:             &Apache::loncommon::copyrightdescription($ENV{'form.copyright'}).
  975:                 "<br \>\n";
  976:     }
  977:     #
  978:     # Evaluate date windows
  979:     my $datequery=&build_date_queries(
  980: 			$ENV{'form.creationdatestart_month'},
  981: 			$ENV{'form.creationdatestart_day'},
  982: 			$ENV{'form.creationdatestart_year'},
  983: 			$ENV{'form.creationdateend_month'},
  984: 			$ENV{'form.creationdateend_day'},
  985: 			$ENV{'form.creationdateend_year'},
  986: 			$ENV{'form.lastrevisiondatestart_month'},
  987: 			$ENV{'form.lastrevisiondatestart_day'},
  988: 			$ENV{'form.lastrevisiondatestart_year'},
  989: 			$ENV{'form.lastrevisiondateend_month'},
  990: 			$ENV{'form.lastrevisiondateend_day'},
  991: 			$ENV{'form.lastrevisiondateend_year'},
  992: 			);
  993:     # Test to see if date windows are legitimate
  994:     if ($datequery=~/^Incorrect/) {
  995: 	&output_date_error($r,$datequery);
  996: 	return ;
  997:     } elsif ($datequery) {
  998:         # Here is where you would set up pretty_search_string to output
  999:         # date query information.
 1000: 	push @queries,$datequery;
 1001:     }
 1002:     # Process form information for custom metadata querying
 1003:     my $customquery=undef;
 1004:     if ($ENV{'form.custommetadata'}) {
 1005:         $pretty_search_string .=$font."Custom Metadata Search</font>: <b>".
 1006:             $ENV{'form.custommetadata'}."</b><br />\n";
 1007: 	$customquery=&build_custommetadata_query('custommetadata',
 1008: 				      $ENV{'form.custommetadata'});
 1009:     }
 1010:     my $customshow=undef;
 1011:     if ($ENV{'form.customshow'}) {
 1012:         $pretty_search_string .=$font."Custom Metadata Display</font>: <b>".
 1013:             $ENV{'form.customshow'}."</b><br />\n";
 1014: 	$customshow=$ENV{'form.customshow'};
 1015: 	$customshow=~s/[^\w\s]//g;
 1016: 	my @fields=split(/\s+/,$customshow);
 1017: 	$customshow=join(" ",@fields);
 1018:     }
 1019:     ## ---------------------------------------------------------------
 1020:     ## Deal with restrictions to given domains
 1021:     ## 
 1022:     my $libraries_to_query = undef;
 1023:     # $ENV{'form.domains'} can be either a scalar or an array reference.
 1024:     # We need an array.
 1025:     my @allowed_domains = (ref($ENV{'form.domains'}) ? @{$ENV{'form.domains'}} 
 1026:                            :  ($ENV{'form.domains'}) );
 1027:     my %domain_hash = ();
 1028:     my $pretty_domains_string;
 1029:     foreach (@allowed_domains) {
 1030:         $domain_hash{$_}++;
 1031:     }
 1032:     if ($domain_hash{'any'}) {
 1033:         $pretty_domains_string = "Searching all domains.";
 1034:     } else {
 1035:         if (@allowed_domains > 1) {
 1036:             $pretty_domains_string = "Searching domains:";
 1037:         } else {
 1038:             $pretty_domains_string = "Searching domain ";
 1039:         }
 1040:         foreach (sort @allowed_domains) {
 1041:             $pretty_domains_string .= "<b>$_</b> ";
 1042:         }
 1043:         foreach (keys(%Apache::lonnet::libserv)) {
 1044:             if (exists($domain_hash{$Apache::lonnet::hostdom{$_}})) {
 1045:                 push @$libraries_to_query,$_;
 1046:             }
 1047:         }
 1048:     }
 1049:     $pretty_search_string .= $pretty_domains_string."<br />\n";
 1050:     #
 1051:     if (@queries) {
 1052: 	$query=join(" AND ",@queries);
 1053: 	$query="select * from metadata where $query";
 1054:     } elsif ($customquery) {
 1055:         $query = '';
 1056:     }
 1057:     return ($query,$customquery,$customshow,$libraries_to_query,
 1058:             $pretty_search_string);
 1059: }
 1060: 
 1061: ######################################################################
 1062: ######################################################################
 1063: 
 1064: =pod 
 1065: 
 1066: =item &parse_basic_search() 
 1067: 
 1068: Parse the basic search form and return a scalar containing an sql query.
 1069: 
 1070: =cut
 1071: 
 1072: ######################################################################
 1073: ######################################################################
 1074: sub parse_basic_search {
 1075:     my ($r)=@_;
 1076:     # Clean up fields for safety
 1077:     for my $field ('basicexp') {
 1078: 	$ENV{"form.$field"}=~s/[^\w\s\(\)\-]//g;
 1079:     }
 1080:     foreach ('mode','form','element') {
 1081: 	# is this required?  Hmmm.
 1082: 	next unless (exists($ENV{"form.$_"}));
 1083: 	$ENV{"form.$_"}=&Apache::lonnet::unescape($ENV{"form.$_"});
 1084: 	$ENV{"form.$_"}=~s/[^\w\/\s\(\)\=\-\"\']//g;
 1085:     }
 1086: 
 1087:     # Check to see if enough is filled in
 1088:     unless (&filled($ENV{'form.basicexp'})) {
 1089: 	&output_blank_field_error($r);
 1090: 	return OK;
 1091:     }
 1092:     my $pretty_search_string = '<b>'.$ENV{'form.basicexp'}.'</b>';
 1093:     my $search_string = $ENV{'form.basicexp'};
 1094:     if ($ENV{'form.related'}) {
 1095:         my @New_Words;
 1096:         ($search_string,@New_Words) = &related_version($ENV{'form.basicexp'});
 1097:         if (@New_Words) {
 1098:             $pretty_search_string .= " with related words: <b>@New_Words</b>.";
 1099:         } else {
 1100:             $pretty_search_string .= " with no related words.";
 1101:         }
 1102:     }
 1103:     &Apache::lonnet::logthis("Search String: $search_string");
 1104:     # Build SQL query string based on form page
 1105:     my $query='';
 1106:     my $concatarg=join(',"    ",',
 1107: 		       ('title', 'author', 'subject', 'notes', 'abstract',
 1108:                         'keywords'));
 1109:     $concatarg='title' if $ENV{'form.titleonly'};
 1110:     $query=&build_SQL_query('concat('.$concatarg.')',$search_string);
 1111:     $pretty_search_string .= "<br />\n";
 1112:     return 'select * from metadata where '.$query,$pretty_search_string;
 1113: }
 1114: 
 1115: 
 1116: ######################################################################
 1117: ######################################################################
 1118: 
 1119: =pod 
 1120: 
 1121: =item &related_version
 1122: 
 1123: Modifies an input string to include related words.  Words in the string
 1124: are replaced with parenthesized lists of 'OR'd words.  For example
 1125: "torque" is replaced with "(torque OR word1 OR word2 OR ...)".  
 1126: 
 1127: Note: Using this twice on a string is probably silly.
 1128: 
 1129: =cut
 1130: 
 1131: ######################################################################
 1132: ######################################################################
 1133: sub related_version {
 1134:     my $search_string = shift;
 1135:     my $result = $search_string;
 1136:     my %New_Words = ();
 1137:     while ($search_string =~ /(\w+)/cg) {
 1138:         my $word = $1;
 1139:         next if (lc($word) =~ /\b(or|and|not)\b/);
 1140:         my @Words = &Apache::loncommon::get_related_words($word);
 1141:         @Words = ($#Words>4? @Words[0..4] : @Words);
 1142:         foreach (@Words) { $New_Words{$_}++;}
 1143:         my $replacement = join " OR ", ($word,@Words);
 1144:         $result =~ s/(\b)$word(\b)/$1($replacement)$2/g;
 1145:     }
 1146:     return $result,sort(keys(%New_Words));
 1147: }
 1148: 
 1149: ######################################################################
 1150: ######################################################################
 1151: 
 1152: =pod 
 1153: 
 1154: =item &build_SQL_query() 
 1155: 
 1156: Builds a SQL query string from a logical expression with AND/OR keywords
 1157: using Text::Query and &recursive_SQL_query_builder()
 1158: 
 1159: =cut
 1160: 
 1161: ######################################################################
 1162: ######################################################################
 1163: sub build_SQL_query {
 1164:     my ($field_name,$logic_statement)=@_;
 1165:     my $q=new Text::Query('abc',
 1166: 			  -parse => 'Text::Query::ParseAdvanced',
 1167: 			  -build => 'Text::Query::Build');
 1168:     $q->prepare($logic_statement);
 1169:     my $matchexp=${$q}{'matchexp'}; chomp $matchexp;
 1170:     my $sql_query=&recursive_SQL_query_build($field_name,$matchexp);
 1171:     return $sql_query;
 1172: }
 1173: 
 1174: ######################################################################
 1175: ######################################################################
 1176: 
 1177: =pod 
 1178: 
 1179: =item &build_custommetadata_query() 
 1180: 
 1181: Constructs a custom metadata query using a rather heinous regular
 1182: expression.
 1183: 
 1184: =cut
 1185: 
 1186: ######################################################################
 1187: ######################################################################
 1188: sub build_custommetadata_query {
 1189:     my ($field_name,$logic_statement)=@_;
 1190:     my $q=new Text::Query('abc',
 1191: 			  -parse => 'Text::Query::ParseAdvanced',
 1192: 			  -build => 'Text::Query::BuildAdvancedString');
 1193:     $q->prepare($logic_statement);
 1194:     my $matchexp=${$q}{'-parse'}{'-build'}{'matchstring'};
 1195:     # quick fix to change literal into xml tag-matching
 1196:     # will eventually have to write a separate builder module
 1197:     # wordone=wordtwo becomes\<wordone\>[^\<] *wordtwo[^\<]*\<\/wordone\>
 1198:     $matchexp =~ s/(\w+)\\=([\w\\\+]+)?# wordone=wordtwo is changed to 
 1199:                  /\\<$1\\>?#           \<wordone\>
 1200:                    \[\^\\<\]?#        [^\<]         
 1201:                    \*$2\[\^\\<\]?#           *wordtwo[^\<]
 1202:                    \*\\<\\\/$1\\>?#                        *\<\/wordone\>
 1203:                    /g;
 1204:     return $matchexp;
 1205: }
 1206: 
 1207: ######################################################################
 1208: ######################################################################
 1209: 
 1210: =pod 
 1211: 
 1212: =item &recursive_SQL_query_build() 
 1213: 
 1214: Recursively constructs an SQL query.  Takes as input $dkey and $pattern.
 1215: 
 1216: =cut
 1217: 
 1218: ######################################################################
 1219: ######################################################################
 1220: sub recursive_SQL_query_build {
 1221:     my ($dkey,$pattern)=@_;
 1222:     my @matches=($pattern=~/(\[[^\]|\[]*\])/g);
 1223:     return $pattern unless @matches;
 1224:     foreach my $match (@matches) {
 1225: 	$match=~/\[ (\w+)\s(.*) \]/;
 1226: 	my ($key,$value)=($1,$2);
 1227: 	my $replacement='';
 1228: 	if ($key eq 'literal') {
 1229: 	    $replacement="($dkey like \"\%$value\%\")";
 1230: 	}
 1231: 	elsif ($key eq 'not') {
 1232: 	    $value=~s/like/not like/;
 1233: #	    $replacement="($dkey not like $value)";
 1234: 	    $replacement="$value";
 1235: 	}
 1236: 	elsif ($key eq 'and') {
 1237: 	    $value=~/(.*[\"|\)]) ([|\(|\^].*)/;
 1238: 	    $replacement="($1 AND $2)";
 1239: 	}
 1240: 	elsif ($key eq 'or') {
 1241: 	    $value=~/(.*[\"|\)]) ([|\(|\^].*)/;
 1242: 	    $replacement="($1 OR $2)";
 1243: 	}
 1244: 	substr($pattern,
 1245: 	       index($pattern,$match),
 1246: 	       length($match),
 1247: 	       $replacement
 1248: 	       );
 1249:     }
 1250:     &recursive_SQL_query_build($dkey,$pattern);
 1251: }
 1252: 
 1253: ######################################################################
 1254: ######################################################################
 1255: 
 1256: =pod 
 1257: 
 1258: =item &build_date_queries() 
 1259: 
 1260: Builds a SQL logic query to check time/date entries.
 1261: Also reports errors (check for /^Incorrect/).
 1262: 
 1263: =cut
 1264: 
 1265: ######################################################################
 1266: ######################################################################
 1267: sub build_date_queries {
 1268:     my ($cmonth1,$cday1,$cyear1,$cmonth2,$cday2,$cyear2,
 1269: 	$lmonth1,$lday1,$lyear1,$lmonth2,$lday2,$lyear2)=@_;
 1270:     my @queries;
 1271:     if ($cmonth1 or $cday1 or $cyear1 or $cmonth2 or $cday2 or $cyear2) {
 1272: 	unless ($cmonth1 and $cday1 and $cyear1 and
 1273: 		$cmonth2 and $cday2 and $cyear2) {
 1274: 	    return "Incorrect entry for the creation date.  You must specify ".
 1275: 		   "a starting month, day, and year and an ending month, ".
 1276: 		   "day, and year.";
 1277: 	}
 1278: 	my $cnumeric1=sprintf("%d%2d%2d",$cyear1,$cmonth1,$cday1);
 1279: 	$cnumeric1+=0;
 1280: 	my $cnumeric2=sprintf("%d%2d%2d",$cyear2,$cmonth2,$cday2);
 1281: 	$cnumeric2+=0;
 1282: 	if ($cnumeric1>$cnumeric2) {
 1283: 	    return "Incorrect entry for the creation date.  The starting ".
 1284: 		   "date must occur before the ending date.";
 1285: 	}
 1286: 	my $cquery="(creationdate BETWEEN '$cyear1-$cmonth1-$cday1' AND '".
 1287: 	           "$cyear2-$cmonth2-$cday2 23:59:59')";
 1288: 	push @queries,$cquery;
 1289:     }
 1290:     if ($lmonth1 or $lday1 or $lyear1 or $lmonth2 or $lday2 or $lyear2) {
 1291: 	unless ($lmonth1 and $lday1 and $lyear1 and
 1292: 		$lmonth2 and $lday2 and $lyear2) {
 1293: 	    return "Incorrect entry for the last revision date.  You must ".
 1294: 		   "specify a starting month, day, and year and an ending ".
 1295: 		   "month, day, and year.";
 1296: 	}
 1297: 	my $lnumeric1=sprintf("%d%2d%2d",$lyear1,$lmonth1,$lday1);
 1298: 	$lnumeric1+=0;
 1299: 	my $lnumeric2=sprintf("%d%2d%2d",$lyear2,$lmonth2,$lday2);
 1300: 	$lnumeric2+=0;
 1301: 	if ($lnumeric1>$lnumeric2) {
 1302: 	    return "Incorrect entry for the last revision date.  The ".
 1303: 		   "starting date must occur before the ending date.";
 1304: 	}
 1305: 	my $lquery="(lastrevisiondate BETWEEN '$lyear1-$lmonth1-$lday1' AND '".
 1306: 	           "$lyear2-$lmonth2-$lday2 23:59:59')";
 1307: 	push @queries,$lquery;
 1308:     }
 1309:     if (@queries) {
 1310: 	return join(" AND ",@queries);
 1311:     }
 1312:     return '';
 1313: }
 1314: 
 1315: ######################################################################
 1316: ######################################################################
 1317: 
 1318: =pod 
 1319: 
 1320: =item &output_results() 
 1321: 
 1322: Format and output results based on a reply list.
 1323: There are two windows that this function writes to.  The main search
 1324: window ("srch") has a listing of the results.  A secondary window ("popwin")
 1325: gives the status of the network search (time elapsed, number of machines
 1326: contacted, etc.)
 1327: 
 1328: =cut
 1329: 
 1330: ######################################################################
 1331: ######################################################################
 1332: sub output_results {
 1333: #    &Apache::lonnet::logthis("output_results:".time);
 1334:     my $fnum; # search result counter
 1335:     my ($mode,$r,$replyref,$hidden)=@_;
 1336:     my %rhash=%{$replyref};
 1337:     my $compiledresult='';
 1338:     my $timeremain=300; # (seconds)
 1339:     my $elapsetime=0;
 1340:     my $resultflag=0;
 1341:     my $tflag=1;
 1342:     ##
 1343:     ## Set viewing function
 1344:     ##
 1345:     my $viewfunction = $Views{$ENV{'form.viewselect'}};
 1346:     if (!defined($viewfunction)) {
 1347:         $r->print("Internal Error - Bad view selected.\n");
 1348:         $r->rflush();
 1349:         return;
 1350:     }
 1351:     #
 1352:     # make query information persistent to allow for subsequent revision
 1353:     my $persistent=&make_persistent(\%ENV);
 1354:     #
 1355:     # Begin producing output
 1356:     $r->rflush();
 1357:     #
 1358:     # begin showing the cataloged results
 1359:     my $action = "/adm/searchcat";
 1360:     if ($mode eq 'Basic') { 
 1361:         $action .= "?reqinterface=basic";
 1362:     } elsif ($mode eq 'Advanced') {
 1363:         $action .= "?reqinterface=advanced";
 1364:     }
 1365:     $r->print(<<CATALOGCONTROLS);
 1366: <form name='results' method="post" action="$action">
 1367: $hidden
 1368: <input type='hidden' name='acts' value='' />
 1369: <input type='button' value='Revise search request'
 1370: onClick='this.form.submit();' />
 1371: $importbutton
 1372: $closebutton
 1373: $persistent
 1374: <hr />
 1375: CATALOGCONTROLS
 1376:     #
 1377:     # make the pop-up window for status
 1378:     $r->print(&make_popwin(%rhash));
 1379:     $r->rflush();
 1380:     ##
 1381:     ## Prepare for the main loop below
 1382:     ##
 1383:     my $servercount=0;
 1384:     my $hitcountsum=0;
 1385:     my $servernum=(keys %rhash);
 1386:     my $serversleft=$servernum;
 1387:     ##
 1388:     ## Run until we run out of time or we run out of servers
 1389:     ##
 1390:     while($serversleft && $timeremain) {
 1391:       ##
 1392:       ## %rhash has servers deleted from it as results come in 
 1393:       ## (within the foreach loop below).
 1394:       ##
 1395:       foreach my $rkey (sort keys %rhash) {
 1396: #        &Apache::lonnet::logthis("Server $rkey:".time);
 1397: 	$servercount++;
 1398: 	$compiledresult='';
 1399: 	my $reply=$rhash{$rkey};
 1400: 	my @results;
 1401: 	if ($reply eq 'con_lost') {
 1402: 	    &popwin_imgupdate($r,$rkey,"srvbad.gif");
 1403: 	    $serversleft--;
 1404:             delete $rhash{$rkey};
 1405: 	} else {
 1406:             # must do since 'use strict' checks for tainting
 1407: 	    $reply=~/^([\.\w]+)$/; 
 1408: 	    my $replyfile=$r->dir_config('lonDaemons').'/tmp/'.$1;
 1409: 	    $reply=~/(.*?)\_/;
 1410:             for (my $counter=0;$counter<2;$counter++) {
 1411:                 if (-e $replyfile && ! -e "$replyfile.end") {
 1412:                     &popwin_imgupdate($r,$rkey,"srvhalf.gif");
 1413:                     &popwin_js($r,'popwin.hc["'.$rkey.'"]='.
 1414:                                '"still transferring..."'.';');
 1415:                 }
 1416:                 # Are we finished transferring data?
 1417:                 if (-e "$replyfile.end") {
 1418:                     $serversleft--;
 1419:                     delete $rhash{$rkey};
 1420:                     if (-s $replyfile) {
 1421:                         &popwin_imgupdate($r,$rkey,"srvgood.gif");
 1422:                         my $fh;
 1423:                         unless ($fh=Apache::File->new($replyfile)){ 
 1424:                             # Is it really appropriate to die on this error?
 1425:                             $r->print('ERROR: file '.
 1426:                                       $replyfile.' cannot be opened');
 1427:                             return OK;
 1428:                         }
 1429:                         @results=<$fh> if $fh;
 1430:                         my $hits =@results;
 1431:                         &popwin_js($r,'popwin.hc["'.$rkey.'"]='.
 1432:                                    $hits.';');
 1433:                         $hitcountsum+=$hits;
 1434:                         &popwin_js($r,'popwin.document.forms.popremain.'.
 1435:                                    'numhits.value='.$hitcountsum.';');
 1436:                     } else {
 1437:                         &popwin_imgupdate($r,$rkey,"srvempty.gif");
 1438:                         &popwin_js($r,'popwin.hc["'.$rkey.'"]=0;');
 1439:                     }
 1440:                     last;
 1441:                 } # end of if ( -e "$replyfile.end")
 1442:                 last unless $timeremain;
 1443:                 sleep 1;    # wait for daemons to write files?
 1444:                 $timeremain--;
 1445:                 $elapsetime++;
 1446:                 &popwin_js($r,"popwin.document.popremain.".
 1447:                            "elapsetime.value=$elapsetime;");
 1448: 	    }
 1449: 	    &popwin_js($r,'popwin.document.whirly.'.
 1450: 		       'src="/adm/lonIcons/lonanimend.gif";');
 1451: 	} # end of if ($reply eq 'con_lost') else statement
 1452:         my %Fields = undef;     # Holds the data to be sent to the various 
 1453:                                 # *_view routines.
 1454:         my ($extrashow,$customfields,$customhash) = 
 1455:                                     &handle_custom_fields(\@results);
 1456:         my @customfields = @$customfields;
 1457:         my %customhash   = %$customhash;
 1458: 	untie %groupsearch_db if (tied %groupsearch_db);
 1459:         #
 1460: 	if (! tie(%groupsearch_db,'GDBM_File',$diropendb,&GDBM_WRCREAT,0640)) {
 1461: 	    $r->print('<html><head></head><body>Unable to tie hash to db '.
 1462:                       'file</body></html>');
 1463:         } else {
 1464: 	    if ($ENV{'form.launch'} eq '1') {
 1465: 		&start_fresh_session();
 1466: 	    }
 1467: 	    foreach my $result (@results) {
 1468: 		next if $result=~/^custom\=/;
 1469: 		chomp $result;
 1470: 		next unless $result;
 1471:                 %Fields = &parse_raw_result($result,$rkey);
 1472:                 #
 1473:                 # Check copyright tags and skip results the user cannot use
 1474:                 my (undef,undef,$resdom,$resname) = split('/',$Fields{'url'});
 1475:                 # Check for priv
 1476:                 if (($Fields{'copyright'} eq 'priv') && 
 1477:                     (($ENV{'user.name'} ne $resname) &&
 1478:                      ($ENV{'user.domain'} ne $resdom))) {
 1479:                     next;
 1480:                 }
 1481:                 # Check for domain
 1482:                 if (($Fields{'copyright'} eq 'domain') &&
 1483:                     ($ENV{'user.domain'} ne $resdom)) {
 1484:                     next;
 1485:                 }
 1486:                 #
 1487: 		$Fields{'extrashow'}=$extrashow;
 1488: 		if ($extrashow) {
 1489: 		    foreach my $field (@customfields) {
 1490: 			my $value='';
 1491: 			$value = $1 if ($customhash{$Fields{'url'}}=~/\<{$field}[^\>]*\>(.*?)\<\/{$field}[^\>]*\>/s);
 1492:                         $Fields{'extrashow'}=~s/\<\!\-\- $field \-\-\>/ $value/g;
 1493:                     }
 1494:                 }
 1495:                 $compiledresult.="\n<p>\n";
 1496:                 if ($ENV{'form.catalogmode'} eq 'interactive') {
 1497:                     my $titleesc=$Fields{'title'};
 1498:                     $titleesc=~s/\'/\\'/; # '
 1499:                     $compiledresult.=<<END if ($ENV{'form.catalogmode'} eq 'interactive');
 1500: <font size='-1'><INPUT TYPE="button" NAME="returnvalues" VALUE="SELECT"
 1501: onClick="javascript:select_data('$titleesc','$Fields{'url'}')">
 1502: </font>
 1503: <br />
 1504: END
 1505:                 }
 1506:                 if ($ENV{'form.catalogmode'} eq 'groupsearch') {
 1507: 		    $fnum+=0;
 1508: 		    $groupsearch_db{"pre_${fnum}_link"}=$Fields{'url'};
 1509: 		    $groupsearch_db{"pre_${fnum}_title"}=$Fields{'title'};
 1510: 		    $compiledresult.=<<END;
 1511: <font size='-1'>
 1512: <input type="checkbox" name="returnvalues" value="SELECT"
 1513: onClick="javascript:queue($fnum)" />
 1514: </font>
 1515: <br />
 1516: END
 1517: # <input type="hidden" name="title$fnum" value="$title" />
 1518: # <input type="hidden" name="url$fnum" value="$url" />
 1519:                     $fnum++;
 1520: 		}
 1521:                 # Render the result into html
 1522:                 $compiledresult.= &$viewfunction(%Fields, hostname => $rkey );
 1523:                 if ($compiledresult or $servercount!=$servernum) {
 1524:                     $compiledresult.="<hr align='left' width='200' noshade />";
 1525:                 }
 1526:             }
 1527:             untie %groupsearch_db;
 1528:         }
 1529: 	if ($compiledresult) {
 1530: 	    $resultflag=1;
 1531:             $r->print($compiledresult);
 1532: 	}
 1533:       } # End of foreach loop over servers remaining
 1534:     }   # End of big loop - while($serversleft && $timeremain)
 1535:     unless ($resultflag) {
 1536:         $r->print("\nThere were no results that matched your query\n");
 1537:     }
 1538:     $r->print('<script type="text/javascript">'.'popwin.close()</script>'.
 1539:               "\n"); 
 1540:     $r->print("</body>\n</html>\n");
 1541:     $r->rflush(); 
 1542:     return;
 1543: }
 1544: 
 1545: ###########################################################
 1546: ###########################################################
 1547: 
 1548: =pod
 1549: 
 1550: =item &parse_raw_result()
 1551: 
 1552: Takes a line from the file of results and parse it.  Returns a hash 
 1553: with keys for the following fields:
 1554: 'title', 'author', 'subject', 'url', 'keywords', 'version', 'notes', 
 1555: 'abstract', 'mime', 'lang', 'owner', 'copyright', 'creationdate', 
 1556: 'lastrevisiondate'.
 1557: 
 1558: In addition, the following tags are set by calling the appropriate 
 1559: lonnet function: 'language', 'cprtag', 'mimetag'.
 1560: 
 1561: The 'title' field is set to "Untitled" if the title field is blank.
 1562: 
 1563: 'abstract' and 'keywords' are truncated to 200 characters.
 1564: 
 1565: =cut
 1566: 
 1567: ###########################################################
 1568: ###########################################################
 1569: sub parse_raw_result {
 1570:     my ($result,$hostname) = @_;
 1571:     # Check for a comma - if it is there then we do not need to unescape the
 1572:     # string.  There seems to be some kind of problem with some items in
 1573:     # the database - the entire string gets sent out unescaped...?
 1574:     unless ($result =~ /,/) {
 1575:         $result = &Apache::lonnet::unescape($result);
 1576:     }
 1577:     my @fields=map {
 1578:         &Apache::lonnet::unescape($_);
 1579:     } (split(/\,/,$result));
 1580:     my ($title,$author,$subject,$url,$keywords,$version,
 1581:         $notes,$abstract,$mime,$lang,
 1582:         $creationdate,$lastrevisiondate,$owner,$copyright)=@fields;
 1583:     my %Fields = 
 1584:         ( title     => &Apache::lonnet::unescape($title),
 1585:           author    => &Apache::lonnet::unescape($author),
 1586:           subject   => &Apache::lonnet::unescape($subject),
 1587:           url       => &Apache::lonnet::unescape($url),
 1588:           keywords  => &Apache::lonnet::unescape($keywords),
 1589:           version   => &Apache::lonnet::unescape($version),
 1590:           notes     => &Apache::lonnet::unescape($notes),
 1591:           abstract  => &Apache::lonnet::unescape($abstract),
 1592:           mime      => &Apache::lonnet::unescape($mime),
 1593:           lang      => &Apache::lonnet::unescape($lang),
 1594:           owner     => &Apache::lonnet::unescape($owner),
 1595:           copyright => &Apache::lonnet::unescape($copyright),
 1596:           creationdate     => &Apache::lonnet::unescape($creationdate),
 1597:           lastrevisiondate => &Apache::lonnet::unescape($lastrevisiondate)
 1598:         );
 1599:     $Fields{'language'} = 
 1600:         &Apache::loncommon::languagedescription($Fields{'lang'});
 1601:     $Fields{'copyrighttag'} =
 1602:         &Apache::loncommon::copyrightdescription($Fields{'copyright'});
 1603:     $Fields{'mimetag'} =
 1604:         &Apache::loncommon::filedescription($Fields{'mime'});
 1605:     if ($Fields{'author'}=~/^(\s*|error)$/) {
 1606:         $Fields{'author'}="Unknown Author";
 1607:     }
 1608:     # Put spaces in the keyword list, if needed.
 1609:     $Fields{'keywords'}=~ s/,([A-z])/, $1/g; 
 1610:     if ($Fields{'title'}=~ /^\s*$/ ) { 
 1611:         $Fields{'title'}='Untitled'; 
 1612:     }
 1613:     unless ($ENV{'user.adv'}) {
 1614:         $Fields{'keywords'} = '- not displayed -';
 1615:         $Fields{'notes'}    = '- not displayed -';
 1616:         $Fields{'abstract'} = '- not displayed -';
 1617:         $Fields{'subject'}  = '- not displayed -';
 1618:     }
 1619:     if (length($Fields{'abstract'})>200) {
 1620:         $Fields{'abstract'} = 
 1621:             substr($Fields{'abstract'},0,200).'...';
 1622:     }
 1623:     if (length($Fields{'keywords'})>200) {
 1624:         $Fields{'keywords'} =
 1625:             substr($Fields{'keywords'},0,200).'...';
 1626:     }
 1627:     return %Fields;
 1628: }
 1629: 
 1630: ###########################################################
 1631: ###########################################################
 1632: 
 1633: =pod
 1634: 
 1635: =item &handle_custom_fields()
 1636: 
 1637: =cut
 1638: 
 1639: ###########################################################
 1640: ###########################################################
 1641: sub handle_custom_fields {
 1642:     my @results = @{shift()};
 1643:     my $customshow='';
 1644:     my $extrashow='';
 1645:     my @customfields;
 1646:     if ($ENV{'form.customshow'}) {
 1647:         $customshow=$ENV{'form.customshow'};
 1648:         $customshow=~s/[^\w\s]//g;
 1649:         my @fields=map {
 1650:             "<font color=\"#008000\">$_:</font><!-- $_ -->";
 1651:         } split(/\s+/,$customshow);
 1652:         @customfields=split(/\s+/,$customshow);
 1653:         if ($customshow) {
 1654:             $extrashow="<ul><li>".join("</li><li>",@fields)."</li></ul>\n";
 1655:         }
 1656:     }
 1657:     my $customdata='';
 1658:     my %customhash;
 1659:     foreach my $result (@results) {
 1660:         if ($result=~/^(custom\=.*)$/) { # grab all custom metadata
 1661:             my $tmp=$result;
 1662:             $tmp=~s/^custom\=//;
 1663:             my ($k,$v)=map {&Apache::lonnet::unescape($_);
 1664:                         } split(/\,/,$tmp);
 1665:             $customhash{$k}=$v;
 1666:         }
 1667:     }
 1668:     return ($extrashow,\@customfields,\%customhash);
 1669: }
 1670: 
 1671: ######################################################################
 1672: ######################################################################
 1673: 
 1674: =pod
 1675: 
 1676: =item &search_results_header
 1677: 
 1678: Output the proper html headers and javascript code to deal with different 
 1679: calling modes.
 1680: 
 1681: Takes most inputs directly from %ENV, except $mode.  
 1682: 
 1683: =over 4
 1684: 
 1685: =item $mode is either (at this writing) 'Basic' or 'Advanced'
 1686: 
 1687: =back
 1688: 
 1689: The following environment variables are checked:
 1690: 
 1691: =over 4
 1692: 
 1693: =item 'form.catalogmode' 
 1694: 
 1695: Checked for 'interactive' and 'groupsearch'.
 1696: 
 1697: =item 'form.mode'
 1698: 
 1699: Checked for existance & 'edit' mode.
 1700: 
 1701: =item 'form.form'
 1702: 
 1703: =item 'form.element'
 1704: 
 1705: =back
 1706: 
 1707: =cut
 1708: 
 1709: ######################################################################
 1710: ######################################################################
 1711: sub search_results_header {
 1712:     my ($mode,$pretty_query) = @_;
 1713:     $mode = lc($mode);
 1714:     my $title;
 1715:     if ($mode eq 'advanced') {
 1716:         $title = "Advanced Search Results";
 1717:     } elsif ($mode eq 'basic') {
 1718:         $title = "Basic Search Results";
 1719:     }
 1720:     my $result = '';
 1721:     # output beginning of search page
 1722:     $result.=<<BEGINNING;
 1723: <html>
 1724: <head>
 1725: <title>$title</title>
 1726: BEGINNING
 1727:     # conditional output of script functions dependent on the mode in
 1728:     # which the search was invoked
 1729:     if ($ENV{'form.catalogmode'} eq 'interactive'){
 1730: 	if (! exists($ENV{'form.mode'}) || $ENV{'form.mode'} ne 'edit') {
 1731:             $result.=<<SCRIPT;
 1732: <script type="text/javascript">
 1733:     function select_data(title,url) {
 1734: 	changeTitle(title);
 1735: 	changeURL(url);
 1736: 	self.close();
 1737:     }
 1738:     function changeTitle(val) {
 1739: 	if (opener.inf.document.forms.resinfo.elements.t) {
 1740: 	    opener.inf.document.forms.resinfo.elements.t.value=val;
 1741: 	}
 1742:     }
 1743:     function changeURL(val) {
 1744: 	if (opener.inf.document.forms.resinfo.elements.u) {
 1745: 	    opener.inf.document.forms.resinfo.elements.u.value=val;
 1746: 	}
 1747:     }
 1748: </script>
 1749: SCRIPT
 1750:         } elsif ($ENV{'form.mode'} eq 'edit') {
 1751:             my $form = $ENV{'form.form'};
 1752:             my $element = $ENV{'form.element'};
 1753:             $result.=<<SCRIPT;
 1754: <script type="text/javascript">
 1755: function select_data(title,url) {
 1756:     changeURL(url);
 1757:     self.close();
 1758: }
 1759: function changeTitle(val) {
 1760: }
 1761: function changeURL(val) {
 1762:     if (window.opener.document) {
 1763:         window.opener.document.forms["$form"].elements["$element"].value=val;
 1764:     } else {
 1765: 	var url = 'forms[\"$form\"].elements[\"$element\"].value';
 1766:         alert("Unable to transfer data to "+url);
 1767:     }
 1768: }
 1769: </script>
 1770: SCRIPT
 1771:         }
 1772:     }
 1773:     $result.=<<SCRIPT if $ENV{'form.catalogmode'} eq 'groupsearch';
 1774: <script type="text/javascript">
 1775:     function select_data(title,url) {
 1776: //	alert('DEBUG: Should be storing '+title+' and '+url);
 1777:     }
 1778:     function queue(val) {
 1779: 	if (eval("document.forms.results.returnvalues["+val+"].checked")) {
 1780: 	    document.forms.results.acts.value+='1a'+val+'b';
 1781: 	}
 1782: 	else {
 1783: 	    document.forms.results.acts.value+='0a'+val+'b';
 1784: 	}
 1785:     }
 1786:     function select_group() {
 1787: 	window.location=
 1788:     "/adm/groupsort?mode=$ENV{'form.mode'}&catalogmode=groupsearch&acts="+
 1789: 	    document.forms.results.acts.value;
 1790:     }
 1791: </script>
 1792: SCRIPT
 1793:     $result.=<<SCRIPT;
 1794: <script type="text/javascript">
 1795:     function displayinfo(val) {
 1796: 	popwin.document.forms.popremain.sdetails.value=val;
 1797:     }
 1798:     function openhelp(val) {
 1799: 	openhelpwin=open('/adm/help/searchcat.html','helpscreen',
 1800: 	     'scrollbars=1,width=400,height=300');
 1801: 	openhelpwin.focus();
 1802:     }
 1803:     function abortsearch(val) {
 1804: 	popwin.close();
 1805:     }
 1806: </script>
 1807: SCRIPT
 1808:     $result.=<<END;
 1809: </head>
 1810: <body bgcolor="#ffffff">
 1811: <img align=right src=/adm/lonIcons/lonlogos.gif>
 1812: <h1>$title</h1>
 1813: END
 1814:     if ($pretty_query) {
 1815:         $result .= "<p>Search query: $pretty_query</p>";
 1816:     }
 1817:     return $result;
 1818: }
 1819: 
 1820: ######################################################################
 1821: ######################################################################
 1822: 
 1823: =pod
 1824: 
 1825: =item &make_popwin()
 1826: 
 1827: Returns html with javascript in it to open up the status window.
 1828: 
 1829: =cut
 1830: 
 1831: ######################################################################
 1832: ######################################################################
 1833: sub make_popwin {
 1834:     my %rhash = @_;
 1835:     my $servernum=(keys %rhash);
 1836:     my $hcinit;
 1837:     my $grid="'<br />'+\n";
 1838:     # $sn is the server number, used ONLY to make sure we have
 1839:     # rows of 10 each.  No longer used to index images.
 1840:     my $sn=1;
 1841:     foreach my $sk (sort keys %rhash) {
 1842: 	$grid.="'<a href=\"";
 1843: 	$grid.="javascript:opener.displayinfo('+";
 1844: 	$grid.="\"'\"+'";
 1845: 	$grid.=$sk;
 1846: 	my $hc;
 1847: 	if ($rhash{$sk} eq 'con_lost') {
 1848: 	    $hc="BAD CONNECTION ";
 1849: 	}
 1850: 	else {
 1851: 	    $hc="'+\"'\"+\"+hc['$sk']+\"+\"'\"+'";
 1852: 	    $hcinit.="hc[\"$sk\"]=\"not yet connected...\";";
 1853: 	}
 1854: 	$grid.=" hitcount=".$hc;
 1855: 	$grid.=" domain=".$Apache::lonnet::hostdom{$sk};
 1856: 	$grid.=" IP=".$Apache::lonnet::hostip{$sk};
 1857: 	# '+"'"+'">'+
 1858: 	$grid.="'+\"'\"+')\">'+";
 1859: 	$grid.="\n";
 1860: 	$grid.="'<img border=\"0\" name=\"img_".$Apache::lonnet::hostdom{$sk}.
 1861:             '_'.$sk."\" src=\"/adm/lonIcons/srvnull.gif\" alt=\"".$sk.
 1862:                 "\" /></a>'+\n";
 1863: 	$grid.="'<br />'+\n" unless $sn%10;
 1864:         $sn++;
 1865:     }
 1866:     my $result.=<<ENDPOP;
 1867: <script type="text/javascript">
 1868:     popwin=open('','popwin','scrollbars=1,width=400,height=220');
 1869:     popwin.focus();
 1870:     popwin.document.writeln('<'+'html>');
 1871:     popwin.document.writeln('<'+'head>');
 1872:     popwin.document.writeln('<'+'script>');
 1873:     popwin.document.writeln('hc=new Array();$hcinit');
 1874:     popwin.document.writeln('<'+'/script>');
 1875:     popwin.document.writeln('<'+'/head>'+
 1876:         '<'+'body bgcolor="#FFFFFF">'+
 1877: 	'<'+'image name="whirly" align="right" src="/adm/lonIcons/'+
 1878: 	'lonanim.gif" '+
 1879: 	'alt="animated logo" />'+
 1880: 	'<'+'h3>Search Results Progress<'+'/h3>'+
 1881:         '<'+'form name="popremain">'+
 1882:         '<'+'tt>'+
 1883: 	'<'+'br clear="all"/><i>PLEASE BE PATIENT</i>'+
 1884: 	'<'+'br />SCANNING $servernum SERVERS'+
 1885: 	'<'+'br clear="all" />Number of record hits found '+
 1886: 	'<'+'input type="text" size="10" name="numhits"'+
 1887: 	' value="0" />'+
 1888: 	'<'+'br clear="all" />Time elapsed '+
 1889: 	'<'+'input type="text" size="10" name="elapsetime"'+
 1890: 	' value="0" />'+
 1891: 	'<'+'br />'+
 1892: 	'SERVER GRID (click on any cell for details)'+
 1893:         $grid
 1894:         '<'+'br />'+
 1895: 	'Server details '+
 1896: 	'<'+'input type="text" size="35" name="sdetails"'+
 1897: 	' value="" />'+
 1898: 	'<'+'br />'+
 1899: 	' <'+'input type="button" name="button"'+
 1900: 	' value="close this window" '+
 1901: 	' onClick="javascript:opener.abortsearch()" />'+
 1902: 	' <'+'input type="button" name="button"'+
 1903: 	' value="help" onClick="javascript:opener.openhelp()" />'+
 1904: 	'<'+'/tt>'+
 1905:         '<'+'/form>'+
 1906:         '<'+'/body><'+'/html>');
 1907:     popwin.document.close();
 1908: </script>
 1909: ENDPOP
 1910:     return $result;
 1911: }
 1912: 
 1913: ######################################################################
 1914: ######################################################################
 1915: 
 1916: =pod 
 1917: 
 1918: =item Metadata Viewing Functions
 1919: 
 1920: Output is a HTML-ified string.
 1921: Input arguments are title, author, subject, url, keywords, version,
 1922: notes, short abstract, mime, language, creation date,
 1923: last revision date, owner, copyright, hostname, and
 1924: extra custom metadata to show.
 1925: 
 1926: =over 4
 1927: 
 1928: =item &detailed_citation_view() 
 1929: 
 1930: =cut
 1931: 
 1932: ######################################################################
 1933: ######################################################################
 1934: sub detailed_citation_view {
 1935:     my %values = @_;
 1936:     my $result=<<END;
 1937: <h3><a href="http://$ENV{'HTTP_HOST'}$values{'url'}" 
 1938:     target='search_preview'>$values{'title'}</a></h3>
 1939: <p>
 1940: <b>$values{'author'}</b>, <i>$values{'owner'}</i><br />
 1941: 
 1942: <b>Subject:       </b> $values{'subject'}<br />
 1943: <b>Keyword(s):    </b> $values{'keywords'}<br />
 1944: <b>Notes:         </b> $values{'notes'}<br />
 1945: <b>MIME Type:     </b> $values{'mimetag'}<br />
 1946: <b>Language:      </b> $values{'language'}<br />
 1947: <b>Copyright/Distribution:</b> $values{'cprtag'}<br />
 1948: </p>
 1949: $values{'extrashow'}
 1950: <p>
 1951: $values{'shortabstract'}
 1952: </p>
 1953: END
 1954:     return $result;
 1955: }
 1956: 
 1957: ######################################################################
 1958: ######################################################################
 1959: 
 1960: =pod 
 1961: 
 1962: =item &summary_view() 
 1963: 
 1964: =cut
 1965: 
 1966: ######################################################################
 1967: ######################################################################
 1968: sub summary_view {
 1969:     my %values = @_;
 1970:     my $result=<<END;
 1971: <a href="http://$ENV{'HTTP_HOST'}$values{'url'}" 
 1972:    target='search_preview'>$values{'author'}</a><br />
 1973: $values{'title'}<br />
 1974: $values{'owner'} -- $values{'lastrevisiondate'}<br />
 1975: $values{'copyrighttag'}<br />
 1976: $values{'extrashow'}
 1977: </p>
 1978: END
 1979:     return $result;
 1980: }
 1981: 
 1982: ######################################################################
 1983: ######################################################################
 1984: 
 1985: =pod 
 1986: 
 1987: =item &fielded_format_view() 
 1988: 
 1989: =cut
 1990: 
 1991: ######################################################################
 1992: ######################################################################
 1993: sub fielded_format_view {
 1994:     my %values = @_;
 1995:     my $result=<<END;
 1996: <b>URL: </b> <a href="http://$ENV{'HTTP_HOST'}$values{'url'}" 
 1997:               target='search_preview'>$values{'url'}</a>
 1998: <br />
 1999: <b>Title:</b> $values{'title'}<br />
 2000: <b>Author(s):</b> $values{'author'}<br />
 2001: <b>Subject:</b> $values{'subject'}<br />
 2002: <b>Keyword(s):</b> $values{'keywords'}<br />
 2003: <b>Notes:</b> $values{'notes'}<br />
 2004: <b>MIME Type:</b> $values{'mimetag'}<br />
 2005: <b>Language:</b> $values{'language'}<br />
 2006: <b>Creation Date:</b> $values{'creationdate'}<br />
 2007: <b>Last Revision Date:</b> $values{'lastrevisiondate'}<br />
 2008: <b>Publisher/Owner:</b> $values{'owner'}<br />
 2009: <b>Copyright/Distribution:</b> $values{'copyrighttag'}<br />
 2010: <b>Repository Location:</b> $values{'hostname'}<br />
 2011: <b>Abstract:</b> $values{'shortabstract'}<br />
 2012: $values{'extrashow'}
 2013: </p>
 2014: END
 2015:     return $result;
 2016: }
 2017: 
 2018: ######################################################################
 2019: ######################################################################
 2020: 
 2021: =pod 
 2022: 
 2023: =item &xml_sgml_view() 
 2024: 
 2025: =back 
 2026: 
 2027: =cut
 2028: 
 2029: ######################################################################
 2030: ######################################################################
 2031: sub xml_sgml_view {
 2032:     my %values = @_;
 2033:     my $result=<<END;
 2034: <pre>
 2035: &lt;LonCapaResource&gt;
 2036: &lt;url&gt;$values{'url'}&lt;/url&gt;
 2037: &lt;title&gt;$values{'title'}&lt;/title&gt;
 2038: &lt;author&gt;$values{'author'}&lt;/author&gt;
 2039: &lt;subject&gt;$values{'subject'}&lt;/subject&gt;
 2040: &lt;keywords&gt;$values{'keywords'}&lt;/keywords&gt;
 2041: &lt;notes&gt;$values{'notes'}&lt;/notes&gt;
 2042: &lt;mimeInfo&gt;
 2043: &lt;mime&gt;$values{'mime'}&lt;/mime&gt;
 2044: &lt;mimetag&gt;$values{'mimetag'}&lt;/mimetag&gt;
 2045: &lt;/mimeInfo&gt;
 2046: &lt;languageInfo&gt;
 2047: &lt;language&gt;$values{'lang'}&lt;/language&gt;
 2048: &lt;languagetag&gt;$values{'language'}&lt;/languagetag&gt;
 2049: &lt;/languageInfo&gt;
 2050: &lt;creationdate&gt;$values{'creationdate'}&lt;/creationdate&gt;
 2051: &lt;lastrevisiondate&gt;$values{'lastrevisiondate'}&lt;/lastrevisiondate&gt;
 2052: &lt;owner&gt;$values{'owner'}&lt;/owner&gt;
 2053: &lt;copyrightInfo&gt;
 2054: &lt;copyright&gt;$values{'copyright'}&lt;/copyright&gt;
 2055: &lt;copyrighttag&gt;$values{'copyrighttag'}&lt;/copyrighttag&gt;
 2056: &lt;/copyrightInfo&gt;
 2057: &lt;repositoryLocation&gt;$values{'hostname'}&lt;/repositoryLocation&gt;
 2058: &lt;shortabstract&gt;$values{'shortabstract'}&lt;/shortabstract&gt;
 2059: &lt;/LonCapaResource&gt;
 2060: </pre>
 2061: $values{'extrashow'}
 2062: END
 2063:     return $result;
 2064: }
 2065: 
 2066: ######################################################################
 2067: ######################################################################
 2068: 
 2069: =pod 
 2070: 
 2071: =item &filled() see if field is filled.
 2072: 
 2073: =cut
 2074: 
 2075: ######################################################################
 2076: ######################################################################
 2077: sub filled {
 2078:     my ($field)=@_;
 2079:     if ($field=~/\S/ && $field ne 'any') {
 2080: 	return 1;
 2081:     }
 2082:     else {
 2083: 	return 0;
 2084:     }
 2085: }
 2086: 
 2087: ######################################################################
 2088: ######################################################################
 2089: 
 2090: =pod 
 2091: 
 2092: =item &output_blank_field_error()
 2093: 
 2094: =cut
 2095: 
 2096: ######################################################################
 2097: ######################################################################
 2098: sub output_blank_field_error {
 2099:     my ($r)=@_;
 2100:     # make query information persistent to allow for subsequent revision
 2101:     my $persistent=&make_persistent(\%ENV);
 2102: 
 2103:     $r->print(<<BEGINNING);
 2104: <html>
 2105: <head>
 2106: <title>The LearningOnline Network with CAPA</title>
 2107: BEGINNING
 2108:     $r->print(<<RESULTS);
 2109: </head>
 2110: <body bgcolor="#ffffff">
 2111: <img align='right' src='/adm/lonIcons/lonlogos.gif' />
 2112: <h1>Search Catalog</h1>
 2113: <form method="post" action="/adm/searchcat">
 2114: $persistent
 2115: <input type='button' value='Revise search request'
 2116: onClick='this.form.submit();' />
 2117: $closebutton
 2118: <hr />
 2119: <h3>Helpful Message</h3>
 2120: <p>
 2121: Incorrect search query due to blank entry fields.
 2122: You need to fill in the relevant
 2123: fields on the search page in order for a query to be
 2124: processed.
 2125: </p>
 2126: </body>
 2127: </html>
 2128: RESULTS
 2129: }
 2130: 
 2131: ######################################################################
 2132: ######################################################################
 2133: 
 2134: =pod 
 2135: 
 2136: =item &output_date_error()
 2137: 
 2138: Output a full html page with an error message.
 2139: 
 2140: =cut
 2141: 
 2142: ######################################################################
 2143: ######################################################################
 2144: sub output_date_error {
 2145:     my ($r,$message)=@_;
 2146:     # make query information persistent to allow for subsequent revision
 2147:     my $persistent=&make_persistent(\%ENV);
 2148: 
 2149:     $r->print(<<RESULTS);
 2150: <html>
 2151: <head>
 2152: <title>The LearningOnline Network with CAPA</title>
 2153: </head>
 2154: <body bgcolor="#ffffff">
 2155: <img align='right' src='/adm/lonIcons/lonlogos.gif' />
 2156: <h1>Search Catalog</h1>
 2157: <form method="post" action="/adm/searchcat">
 2158: $persistent
 2159: <input type='button' value='Revise search request'
 2160: onClick='this.form.submit();' />
 2161: $closebutton
 2162: <hr />
 2163: <h3>Helpful Message</h3>
 2164: <p>
 2165: $message
 2166: </p>
 2167: </body>
 2168: </html>
 2169: RESULTS
 2170: }
 2171: 
 2172: ######################################################################
 2173: ######################################################################
 2174: 
 2175: =pod 
 2176: 
 2177: =item &start_fresh_session()
 2178: 
 2179: Cleans the global %groupsearch_db by removing all fields which begin with
 2180: 'pre_' or 'store'.
 2181: 
 2182: =cut
 2183: 
 2184: ######################################################################
 2185: ######################################################################
 2186: sub start_fresh_session {
 2187:     delete $groupsearch_db{'mode_catalog'};
 2188:     foreach (keys %groupsearch_db) {
 2189:         if ($_ =~ /^pre_/) {
 2190:             delete $groupsearch_db{$_};
 2191:         }
 2192:         if ($_ =~ /^store/) {
 2193: 	    delete $groupsearch_db{$_};
 2194: 	}
 2195:     }
 2196: }
 2197: 
 2198: ######################################################################
 2199: ######################################################################
 2200: 
 2201: =pod 
 2202: 
 2203: =item &popwin_js() send javascript to popwin
 2204: 
 2205: =cut
 2206: 
 2207: ######################################################################
 2208: ######################################################################
 2209: sub popwin_js {
 2210:     # Print javascript out to popwin, but make sure we dont generate
 2211:     # any javascript errors in doing so.
 2212:     my ($r,$text) = @_;
 2213:     $r->print(<<"END");
 2214: <script type="text/javascript">
 2215:     if (! popwin.closed) {
 2216: 	$text
 2217:     }
 2218: </script>
 2219: END
 2220:     $r->rflush();
 2221: }
 2222: 
 2223: ######################################################################
 2224: ######################################################################
 2225: 
 2226: =pod 
 2227: 
 2228: =item &popwin_imgupdate()
 2229: 
 2230: Send a given image (and its location) out to the browser.  Takes as 
 2231: input $r, loncapa server id, and an icon URL.
 2232: 
 2233: =cut
 2234: 
 2235: ######################################################################
 2236: ######################################################################
 2237: sub popwin_imgupdate {
 2238:     my ($r,$server,$icon) = @_;
 2239:     &popwin_js($r,'popwin.document.img_'.$Apache::lonnet::hostdom{$server}.
 2240:                '_'.$server.'.'.'src="/adm/lonIcons/'.$icon.'";');
 2241: }    
 2242: 
 2243: 1;
 2244: 
 2245: __END__
 2246: 
 2247: =pod
 2248: 
 2249: =back 
 2250: 
 2251: =cut

FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>