File:  [LON-CAPA] / loncom / interface / lonsearchcat.pm
Revision 1.180: download - view: text, annotated - select for diffs
Mon Jun 16 20:54:39 2003 UTC (20 years, 11 months ago) by matthew
Branches: MAIN
CVS tags: HEAD
Default to only searching current domain on basic search.

    1: # The LearningOnline Network with CAPA
    2: # Search Catalog
    3: #
    4: # $Id: lonsearchcat.pm,v 1.180 2003/06/16 20:54:39 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: ###############################################################################
   29: ###############################################################################
   30: 
   31: =pod 
   32: 
   33: =head1 NAME
   34: 
   35: lonsearchcat - LONCAPA Search Interface
   36: 
   37: =head1 SYNOPSIS
   38: 
   39: Search interface to LON-CAPAs digital library
   40: 
   41: =head1 DESCRIPTION
   42: 
   43: This module enables searching for a distributed browseable catalog.
   44: 
   45: This is part of the LearningOnline Network with CAPA project
   46: described at http://www.lon-capa.org.
   47: 
   48: lonsearchcat presents the user with an interface to search the LON-CAPA
   49: digital library.  lonsearchcat also initiates the execution of a search
   50: by sending the search parameters to LON-CAPA servers.  The progress of 
   51: search (on a server basis) is displayed to the user in a seperate window.
   52: 
   53: =head1 Internals
   54: 
   55: =over 4
   56: 
   57: =cut
   58: 
   59: ###############################################################################
   60: ###############################################################################
   61: 
   62: ###############################################################################
   63: ##                                                                           ##
   64: ## ORGANIZATION OF THIS PERL MODULE                                          ##
   65: ##                                                                           ##
   66: ## 1. Modules used by this module                                            ##
   67: ## 2. Variables used throughout the module                                   ##
   68: ## 3. handler subroutine called via Apache and mod_perl                      ##
   69: ## 4. Other subroutines                                                      ##
   70: ##                                                                           ##
   71: ###############################################################################
   72: 
   73: package Apache::lonsearchcat;
   74: 
   75: # ------------------------------------------------- modules used by this module
   76: use strict;
   77: use Apache::Constants qw(:common :http);
   78: use Apache::lonnet();
   79: use Apache::File();
   80: use CGI qw(:standard);
   81: use Text::Query;
   82: use GDBM_File;
   83: use Apache::loncommon();
   84: use Apache::lonmysql();
   85: 
   86: # ---------------------------------------- variables used throughout the module
   87: 
   88: ######################################################################
   89: ######################################################################
   90: 
   91: =pod 
   92: 
   93: =item Global variables
   94: 
   95: =over 4
   96: 
   97: =item $importbutton
   98: 
   99: button to take the select results and go to group sorting
  100: 
  101: =item %groupsearch_db   
  102: 
  103: Database hash used to save values for the groupsearch RAT interface.
  104: 
  105: =item $diropendb 
  106: 
  107: The full path to the (temporary) search database file.  This is set and
  108: used in &handler() and is also used in &output_results().
  109: 
  110: =item %Views
  111: 
  112: Hash which associates an output view description with the function
  113: that produces it.  Adding a new view type should be as easy as
  114: adding a line to the definition of this hash and making sure the function
  115: takes the proper parameters.
  116: 
  117: =item $bodytag
  118: 
  119: LON-CAPA standard body tag, gotten from &Apache::lonnet::bodytag.
  120: No title, no table, just a <body> tag.
  121: 
  122: =back 
  123: 
  124: =cut
  125: 
  126: ######################################################################
  127: ######################################################################
  128: 
  129: # -- dynamically rendered interface components
  130: my $importbutton; # button to take the selected results and go to group sorting
  131: 
  132: # -- miscellaneous variables
  133: my %groupsearch_db;     # database hash
  134: my $diropendb = "";    # db file
  135: #             View Description           Function Pointer
  136: my %Views = ("Detailed Citation View" => \&detailed_citation_view,
  137:              "Summary View"           => \&summary_view,
  138:              "Fielded Format"         => \&fielded_format_view,
  139:              "XML/SGML"               => \&xml_sgml_view,
  140:              "Compact View"           => \&compact_view);
  141: my %persistent_db;
  142: my $hidden_fields;
  143: my $bodytag;
  144: 
  145: #
  146: # For course search
  147: #
  148: my %alreadyseen;
  149: my $hashtied;
  150: my %hash;
  151: my $totalfound;
  152:  
  153: ######################################################################
  154: ######################################################################
  155: 
  156: =pod 
  157: 
  158: =item &handler() - main handler invoked by httpd child
  159: 
  160: =item Variables
  161: 
  162: =over 4
  163: 
  164: =item $hidden
  165: 
  166: holds 'hidden' html forms
  167: 
  168: =item $scrout
  169: 
  170: string that holds portions of the screen output
  171: 
  172: =back 
  173: 
  174: =cut
  175: 
  176: ######################################################################
  177: ######################################################################
  178: sub handler {
  179:     my $r = shift;
  180:     #
  181: 
  182:     my $loaderror=&Apache::lonnet::overloaderror($r);
  183:     if ($loaderror) { return $loaderror; }
  184: 
  185:     my $closebutton;  # button that closes the search window 
  186:                       # This button is different for the RAT compared to
  187:                       # normal invocation.
  188:     #
  189:     $r->content_type('text/html');
  190:     $r->send_http_header;
  191:     return OK if $r->header_only;
  192:     ##
  193:     ## Prevent caching of the search interface window.  Hopefully this means
  194:     ## we will get the launch=1 passed in a little more.
  195:     &Apache::loncommon::no_cache($r);
  196:     ## 
  197:     ## Pick up form fields passed in the links.
  198:     ##
  199:     &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
  200:              ['catalogmode','launch','acts','mode','form','element','pause',
  201:               'phase','persistent_db_id','table','start','show',
  202:               'cleargroupsort']);
  203:     ##
  204:     ## The following is a trick - we wait a few seconds if asked to so
  205:     ##     the daemon running the search can get ahead of the daemon
  206:     ##     printing the results.  We only need (theoretically) to do
  207:     ##     this once, so the pause indicator is deleted
  208:     ##
  209:     if (exists($ENV{'form.pause'})) {
  210:         sleep(3);
  211:         delete($ENV{'form.pause'});
  212:     }
  213:     ##
  214:     ## Initialize global variables
  215:     ##
  216:     my $domain  = $r->dir_config('lonDefDomain');
  217:     $diropendb= "/home/httpd/perl/tmp/$ENV{'user.domain'}_$ENV{'user.name'}_searchcat.db";
  218:     #
  219:     # set the name of the persistent database
  220:     #          $ENV{'form.persistent_db_id'} can only have digits in it.
  221:     if (! exists($ENV{'form.persistent_db_id'}) ||
  222:         ($ENV{'form.persistent_db_id'} =~ /\D/) ||
  223:         ($ENV{'form.launch'} eq '1')) {
  224:         $ENV{'form.persistent_db_id'} = time;
  225:     }
  226:     $bodytag=&Apache::loncommon::bodytag(undef,undef,undef,1);
  227:     my $persistent_db_file = "/home/httpd/perl/tmp/".
  228:         &Apache::lonnet::escape($domain).
  229:             '_'.&Apache::lonnet::escape($ENV{'user.name'}).
  230:                 '_'.$ENV{'form.persistent_db_id'}.'_persistent_search.db';
  231:     ##
  232:     if (! &get_persistent_form_data($persistent_db_file)) {
  233:         if ($ENV{'form.phase'} =~ /(run_search|results)/) {
  234:             &Apache::lonnet::logthis("lonsearchcat:Unable to recover data ".
  235:                                      "from $persistent_db_file");
  236:             $r->print(<<END);
  237: <html>
  238: <head><title>LON-CAPA Search Error</title></head>
  239: $bodytag
  240: We were unable to retrieve data describing your search.  This is a serious
  241: error and has been logged.  Please alert your LON-CAPA administrator.
  242: </body>
  243: </html>
  244: END
  245:             return OK;
  246:         }
  247:     }
  248:     ##
  249:     ## Clear out old values from groupsearch database
  250:     ##
  251:     untie %groupsearch_db if (tied(%groupsearch_db));
  252:     if (($ENV{'form.cleargroupsort'} eq '1') || 
  253:         (($ENV{'form.launch'} eq '1') && 
  254:          ($ENV{'form.catalogmode'} eq 'groupsearch'))) {
  255: 	if (tie(%groupsearch_db,'GDBM_File',$diropendb,&GDBM_WRCREAT(),0640)) {
  256: 	    &start_fresh_session();
  257: 	    untie %groupsearch_db;
  258:             delete($ENV{'form.cleargroupsort'});
  259: 	} else {
  260:             # This is a stupid error to give to the user.  
  261:             # It really tells them nothing.
  262: 	    $r->print('<html><head></head>'.$bodytag.
  263:                       'Unable to tie hash to db file</body></html>');
  264: 	    return OK;
  265: 	}
  266:     }
  267:     ##
  268:     ## Configure hidden fields
  269:     ##
  270:     $hidden_fields = '<input type="hidden" name="persistent_db_id" value="'.
  271:         $ENV{'form.persistent_db_id'}.'" />'."\n";
  272:     if (exists($ENV{'form.catalogmode'})) {
  273:         $hidden_fields .= '<input type="hidden" name="catalogmode" value="'.
  274:                 $ENV{'form.catalogmode'}.'" />'."\n";
  275:     }
  276:     if (exists($ENV{'form.form'})) {
  277:         $hidden_fields .= '<input type="hidden" name="form" value="'.
  278:                 $ENV{'form.form'}.'" />'."\n";
  279:     }
  280:     if (exists($ENV{'form.element'})) {
  281:         $hidden_fields .= '<input type="hidden" name="element" value="'.
  282:                 $ENV{'form.element'}.'" />'."\n";
  283:     }
  284:     if (exists($ENV{'form.mode'})) {
  285:         $hidden_fields .= '<input type="hidden" name="mode" value="'.
  286:                 $ENV{'form.mode'}.'" />'."\n";
  287:     }
  288:     ##
  289:     ## Configure dynamic components of interface
  290:     ##
  291:     if ($ENV{'form.catalogmode'} eq 'interactive') {
  292:         $closebutton="<input type='button' name='close' value='CLOSE' ";
  293:         if ($ENV{'form.phase'} =~ /(results|run_search)/) {
  294: 	    $closebutton .="onClick='parent.close()'";
  295:         } else {
  296:             $closebutton .="onClick='self.close()'";
  297:         }
  298:         $closebutton .=">\n";
  299:     } elsif ($ENV{'form.catalogmode'} eq 'groupsearch') {
  300:         $closebutton="<input type='button' name='close' value='CLOSE' ";
  301:         if ($ENV{'form.phase'} =~ /(results|run_search)/) {
  302: 	    $closebutton .="onClick='parent.close()'";
  303:         } else {
  304:             $closebutton .="onClick='self.close()'";
  305:         }
  306:         $closebutton .= ">";
  307:         $importbutton=<<END;
  308: <input type='button' name='import' value='IMPORT'
  309: onClick='javascript:select_group()'>
  310: END
  311:     } else {
  312:         $closebutton = '';
  313:         $importbutton = '';
  314:     }
  315:     ##
  316:     ## Sanity checks on form elements
  317:     ##
  318:     if (!defined($ENV{'form.viewselect'})) {
  319:         if (($ENV{'form.catalogmode'} eq 'groupsearch') ||
  320:             ($ENV{'form.catalogmode'} eq 'interactive')) {
  321:             $ENV{'form.viewselect'} ="Compact View";
  322:         } else {
  323:             $ENV{'form.viewselect'} ="Detailed Citation View";
  324:         }
  325:     }
  326:     $ENV{'form.phase'} = 'disp_basic' if (! exists($ENV{'form.phase'}));
  327:     $ENV{'form.show'} = 20 if (! exists($ENV{'form.show'}));
  328:     ##
  329:     ## Switch on the phase
  330:     ##
  331:     if ($ENV{'form.phase'} eq 'disp_basic') {
  332:         &print_basic_search_form($r,$closebutton);
  333:     } elsif ($ENV{'form.phase'} eq 'disp_adv') {
  334:         &print_advanced_search_form($r,$closebutton);
  335:     } elsif ($ENV{'form.phase'} eq 'results') {
  336:         &display_results($r,$importbutton,$closebutton);
  337:     } elsif ($ENV{'form.phase'} =~ /^(sort|run_search)$/) {
  338:         my ($query,$customquery,$customshow,$libraries,$pretty_string) =
  339:             &get_persistent_data($persistent_db_file,
  340:                  ['query','customquery','customshow',
  341:                   'libraries','pretty_string']);
  342:         if ($ENV{'form.phase'} eq 'sort') {
  343:             &print_sort_form($r,$pretty_string);
  344:         } elsif ($ENV{'form.phase'} eq 'run_search') {
  345:             &run_search($r,$query,$customquery,$customshow,
  346:                         $libraries,$pretty_string);
  347:         }
  348:     } elsif ($ENV{'form.phase'} eq 'course_search') {
  349:         &course_search($r);
  350:     } elsif(($ENV{'form.phase'} eq 'basic_search') ||
  351:             ($ENV{'form.phase'} eq 'adv_search')) {
  352:         $ENV{'form.searchmode'} = 'basic';
  353:         if ($ENV{'form.phase'} eq 'adv_search') {
  354:             $ENV{'form.searchmode'} = 'advanced';
  355:         }
  356:         # Set up table
  357:         if (! defined(&create_results_table())) {
  358:             $r->print(<<END);
  359: <html><head><title>Search Error</title></head>
  360: $bodytag
  361: Unable to create table in which to store search results.  
  362: The search has been aborted.
  363: </body>
  364: </html>
  365: END
  366:             return OK;
  367:         }
  368:         delete($ENV{'form.launch'});
  369:         if (! &make_form_data_persistent($r,$persistent_db_file)) {
  370:             $r->print(<<END);
  371: <html><head><title>Search Error</title></head>
  372: $bodytag
  373: Unable to properly store search information.  The search has been aborted.
  374: </body>
  375: </html>
  376: END
  377:             return OK;
  378:         }
  379:         #
  380:         # We are running a search
  381:         my ($query,$customquery,$customshow,$libraries) = 
  382:             (undef,undef,undef,undef);
  383:         my $pretty_string;
  384:         if ($ENV{'form.phase'} eq 'basic_search') {
  385:             ($query,$pretty_string,$libraries) = 
  386:                 &parse_basic_search($r,$closebutton);
  387:         } else {                      # Advanced search
  388:             ($query,$customquery,$customshow,$libraries,$pretty_string) 
  389:                 = &parse_advanced_search($r,$closebutton);
  390:             return OK if (! defined($query));
  391:         }
  392:         &make_persistent({ query => $query,
  393:                            customquery => $customquery,
  394:                            customshow => $customshow,
  395:                            libraries => $libraries,
  396:                            pretty_string => $pretty_string },
  397:                          $persistent_db_file);
  398:         ##
  399:         ## Print out the frames interface
  400:         ##
  401:         &print_frames_interface($r);
  402:     }
  403:     return OK;
  404: } 
  405: 
  406: ######################################################################
  407: ######################################################################
  408: 
  409: sub course_search {
  410:     my $r=shift;
  411:     my $bodytag=&Apache::loncommon::bodytag('Course Search');
  412:     my $pretty_search_string = '<b>'.$ENV{'form.courseexp'}.'</b>';
  413:     my $search_string = $ENV{'form.courseexp'};
  414:     my @New_Words;
  415:     if ($ENV{'form.crsrelated'}) {
  416:         ($search_string,@New_Words) = &related_version($ENV{'form.courseexp'});
  417:         if (@New_Words) {
  418:             $pretty_search_string .= " with related words: <b>@New_Words</b>.";
  419:         } else {
  420:             $pretty_search_string .= " with no related words.";
  421:         }
  422:     }
  423:     my $fulltext=$ENV{'form.crsfulltext'};
  424:     my @allwords=($search_string,@New_Words);
  425:     $totalfound=0;
  426:     $r->print('<html><head><title>LON-CAPA Course Search</title></head>'.
  427: 	      $bodytag.$pretty_search_string);
  428:     $r->rflush();
  429: # ======================================================= Go through the course
  430:    $hashtied=0;
  431:    undef %alreadyseen;
  432:    %alreadyseen=();
  433:     my $c=$r->connection;
  434:    &tiehash();
  435:    foreach (keys %hash) {
  436:        if ($c->aborted()) { last; }
  437:        if (($_=~/^src\_(.+)$/) && (!$alreadyseen{$hash{$_}})) {
  438:            &checkonthis($r,$hash{$_},0,$hash{'title_'.$1},$fulltext,@allwords);
  439:        }
  440:    }
  441:    &untiehash();
  442:     unless ($totalfound) {
  443: 	$r->print('<p>No resources found.</p>');
  444:     }
  445: # =================================================== Done going through course
  446:     $r->print('</body></html>');
  447: }
  448: 
  449: # ---------------------------------------------------------------- tie the hash
  450: 
  451: sub tiehash {
  452:     $hashtied=0;
  453:     if ($ENV{'request.course.fn'}) {
  454:         if (tie(%hash,'GDBM_File',$ENV{'request.course.fn'}.".db",
  455:             &GDBM_READER(),0640)) {
  456:                 $hashtied=1;
  457:         }
  458:     }    
  459: }
  460: 
  461: sub untiehash {
  462:     if ($hashtied) { untie %hash; }
  463:     $hashtied=0;
  464: }
  465: 
  466: # =============================== This pulls up a resource and its dependencies
  467: 
  468: sub checkonthis {
  469:     my ($r,$url,$level,$title,$fulltext,@allwords)=@_;
  470:     $alreadyseen{$url}=1;
  471:     $r->rflush();
  472:     my $result=&Apache::lonnet::metadata($url,'title').' '.
  473:                &Apache::lonnet::metadata($url,'subject').' '.
  474:                &Apache::lonnet::metadata($url,'abstract').' '.
  475:                &Apache::lonnet::metadata($url,'keywords');
  476:     if (($url) && ($fulltext)) {
  477: 	$result.=&Apache::lonnet::ssi_body($url);
  478:     }
  479:     $result=~s/\s+/ /gs;
  480:     my $applies=0;
  481:     foreach (@allwords) {
  482:         if ($_=~/\w/) {
  483: 	   if ($result=~/$_/si) {
  484: 	      $applies++;
  485:            }
  486:        }
  487:     }
  488: # Does this resource apply?
  489:     if ($applies) {
  490:        $r->print('<br />');
  491:        for (my $i=0;$i<=$level*5;$i++) {
  492:            $r->print('&nbsp;');
  493:        }
  494:        $r->print('<a href="'.$url.'" target="cat">'.
  495: 		 ($title?$title:$url).'</a><br />');
  496:        $totalfound++;
  497:     } elsif ($fulltext) {
  498:        $r->print(' .');
  499:     }
  500:     $r->rflush();
  501: # Check also the dependencies of this one
  502:     my $dependencies=
  503:                 &Apache::lonnet::metadata($url,'dependencies');
  504:     foreach (split(/\,/,$dependencies)) {
  505:        if (($_=~/^\/res\//) && (!$alreadyseen{$_})) {
  506:           &checkonthis($r,$_,$level+1,'',$fulltext,@allwords);
  507:        }
  508:     }
  509: }
  510: 
  511: ######################################################################
  512: ######################################################################
  513: 
  514: =pod 
  515: 
  516: =item &print_basic_search_form() 
  517: 
  518: Returns a scalar which holds html for the basic search form.
  519: 
  520: =cut
  521: 
  522: ######################################################################
  523: ######################################################################
  524: 
  525: sub print_basic_search_form{
  526:     my ($r,$closebutton) = @_;
  527:     my $bodytag=&Apache::loncommon::bodytag('Search');
  528:     my $scrout=<<"ENDDOCUMENT";
  529: <html>
  530: <head>
  531: <title>The LearningOnline Network with CAPA</title>
  532: <script type="text/javascript">
  533:     function openhelp(val) {
  534: 	openhelpwin=open('/adm/help/searchcat.html','helpscreen',
  535: 	     'scrollbars=1,width=600,height=300');
  536: 	openhelpwin.focus();
  537:     }
  538: </script>
  539: </head>
  540: $bodytag
  541: ENDDOCUMENT
  542: if (&Apache::lonnet::allowed('bre',$ENV{'request.role.domain'})) {
  543:     $scrout.=(<<ENDDOCUMENT);
  544: <h1>Catalog Search</h1>
  545: <form method="post" action="/adm/searchcat">
  546: <input type="hidden" name="phase" value="basic_search" />
  547: $hidden_fields
  548: <p>
  549: Enter terms or phrases separated by AND, OR, or NOT 
  550: then press SEARCH below.
  551: </p>
  552: <p>
  553: <table>
  554: <tr><td>
  555: ENDDOCUMENT
  556:     $scrout.='&nbsp;'.&simpletextfield('basicexp',$ENV{'form.basicexp'},40).
  557:         '&nbsp;';
  558:     my $relatedcheckbox = &simplecheckbox('related',$ENV{'form.related'});
  559:     my $domain = $r->dir_config('lonDefDomain');
  560:     my $domaincheckbox = &simplecheckbox('domains',$domain,'checked');
  561:     $scrout.=<<END;
  562: </td><td><a
  563: href="/adm/searchcat?phase=disp_adv&catalogmode=$ENV{'form.catalogmode'}&launch=$ENV{'form.launch'}"
  564: >Advanced Search</a></td></tr>
  565: <tr><td>$relatedcheckbox use related words</td>
  566:     <td>$domaincheckbox only search domain <b>$domain</b></td></tr>
  567: </table>
  568: </p>
  569: <p>
  570: &nbsp;<input type="submit" name="basicsubmit" value='SEARCH' />&nbsp;
  571: $closebutton
  572: END
  573:     $scrout.=&selectbox(undef,'viewselect',
  574: 			$ENV{'form.viewselect'},
  575: 			undef,undef,undef,
  576: 			sort(keys(%Views)));
  577:     $scrout.=&selectbox(undef,'show',
  578: 			$ENV{'form.show'},
  579: 			undef,undef,undef,
  580: 			(10,20,50,100));
  581:     $scrout.=<<ENDDOCUMENT;
  582: per page.
  583: </p>
  584: </form>
  585: ENDDOCUMENT
  586:     }
  587:     if ($ENV{'request.course.id'}) {
  588:         $scrout.=(<<ENDCOURSESEARCH);
  589: <hr />
  590: <h1>Course Search</h1>    
  591: <form method="post" action="/adm/searchcat">
  592: <input type="hidden" name="phase" value="course_search" />
  593: $hidden_fields
  594: <p>
  595: Enter terms or phrases, then press SEARCH below.
  596: </p>
  597: <p>
  598: <table>
  599: <tr><td>
  600: ENDCOURSESEARCH
  601:         $scrout.='&nbsp;'.
  602:             &simpletextfield('courseexp',$ENV{'form.courseexp'},40);
  603:         my $crscheckbox = 
  604:             &simplecheckbox('crsfulltext',$ENV{'form.crsfulltext'});
  605:         my $relcheckbox = 
  606:             &simplecheckbox('crsrelated',$ENV{'form.crsrelated'});
  607:         $scrout.=(<<ENDENDCOURSE);
  608: </td></tr>
  609: <tr><td>$relcheckbox use related words</td><td></td></tr>
  610: <tr><td>$crscheckbox fulltext search (time consuming)</td><td></td></tr>
  611: </table><p>
  612: &nbsp;<input type="submit" name="coursesubmit" value='SEARCH' />
  613: </p>
  614: ENDENDCOURSE
  615:     }
  616:     $scrout.=(<<ENDDOCUMENT);
  617: </body>
  618: </html>
  619: ENDDOCUMENT
  620:     $r->print($scrout);
  621:     return;
  622: }
  623: ######################################################################
  624: ######################################################################
  625: 
  626: =pod 
  627: 
  628: =item &advanced_search_form() 
  629: 
  630: Returns a scalar which holds html for the advanced search form.
  631: 
  632: =cut
  633: 
  634: ######################################################################
  635: ######################################################################
  636: 
  637: sub print_advanced_search_form{
  638:     my ($r,$closebutton) = @_;
  639:     my $advanced_buttons = <<"END";
  640: <p>
  641: <input type="submit" name="advancedsubmit" value='SEARCH' />
  642: <input type="reset" name="reset" value='RESET' />
  643: $closebutton
  644: <input type="button" value="HELP" onClick="openhelp()" />
  645: </p>
  646: END
  647:     if (!defined($ENV{'form.viewselect'})) {
  648:         $ENV{'form.viewselect'} ="Detailed Citation View";
  649:     }
  650:     my $bodytag=&Apache::loncommon::bodytag('Advanced Catalog Search');
  651:     my $scrout=<<"ENDHEADER";
  652: <html>
  653: <head>
  654: <title>The LearningOnline Network with CAPA</title>
  655: <script type="text/javascript">
  656:     function openhelp(val) {
  657: 	openhelpwin=open('/adm/help/searchcat.html','helpscreen',
  658: 	     'scrollbars=1,width=600,height=300');
  659: 	openhelpwin.focus();
  660:     }
  661: </script>
  662: </head>
  663: $bodytag
  664: Enter terms or phrases separated by search operators 
  665: such as AND, OR, or NOT.<br />
  666: <form method="post" action="/adm/searchcat">
  667: $advanced_buttons
  668: $hidden_fields
  669: <input type="hidden" name="phase" value="adv_search" />
  670: <table>
  671: <tr><td><font color="#800000" face="helvetica"><b>VIEW:</b></font></td>
  672: <td>
  673: ENDHEADER
  674:     $scrout.=&selectbox(undef,'viewselect',
  675: 			$ENV{'form.viewselect'},
  676: 			undef,undef,undef,
  677: 			sort(keys(%Views)));
  678:     $scrout.='&nbsp;';
  679:     $scrout.=&selectbox(undef,'show',
  680: 			$ENV{'form.show'},
  681: 			undef,undef,undef,
  682: 			(10,20,50,100));
  683:     $scrout.='&nbsp;'.
  684:         '<font color="#800000" face="helvetica">Per Page</font>';
  685:     $scrout.="</td><td>Related<br />Words</td></tr>\n";
  686:     $scrout.=&searchphrasefield_with_related('title',   'title'   ,
  687:                                              $ENV{'form.title'});
  688:     $scrout.=&searchphrasefield('author',  'author'  ,$ENV{'form.author'});
  689:     $scrout.=&searchphrasefield_with_related('subject', 'subject' ,
  690:                                              $ENV{'form.subject'});
  691:     $scrout.=&searchphrasefield_with_related('keywords','keywords',
  692:                                              $ENV{'form.keywords'});
  693:     $scrout.=&searchphrasefield('URL',     'url'     ,$ENV{'form.url'});
  694:     $scrout.=&searchphrasefield_with_related('notes',   'notes'   ,
  695:                                              $ENV{'form.notes'});
  696:     $scrout.=&searchphrasefield_with_related('abstract','abstract',
  697:                                              $ENV{'form.abstract'});
  698:     # Hack - an empty table row.
  699:     $scrout.="<tr><td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td></tr>\n";
  700:     $scrout.=&searchphrasefield('file<br />extension','extension',
  701:                         $ENV{'form.extension'});
  702:     $scrout.="<tr><td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td></tr>\n";
  703:     $scrout.=&searchphrasefield('publisher<br />owner','owner',
  704: 				$ENV{'form.owner'});
  705:     $scrout.="</table>\n";
  706:     $ENV{'form.category'}='any' if (! defined($ENV{'form.category'}));
  707:     $scrout.=&selectbox('File Category','category',
  708: 			$ENV{'form.category'},
  709: 			'any','Any category',
  710: 			undef,
  711: 			(&Apache::loncommon::filecategories()));
  712:     $ENV{'form.language'}='any' unless length($ENV{'form.language'});
  713:     #----------------------------------------------------------------
  714:     # Allow restriction to multiple domains.
  715:     #   I make the crazy assumption that there will never be a domain 'any'.
  716:     #
  717:     $ENV{'form.domains'} = 'any' if (! exists($ENV{'form.domains'}));
  718:     my @allowed_domains = (ref($ENV{'form.domains'}) ? @{$ENV{'form.domains'}} 
  719:                            :  ($ENV{'form.domains'}) );
  720:     my %domain_hash = ();
  721:     foreach (@allowed_domains) {
  722:         $domain_hash{$_}++;
  723:     }
  724:     my @domains =&Apache::loncommon::get_domains();
  725:     # adjust the size of the select box
  726:     my $size = 4;
  727:     $size = (scalar @domains < ($size - 1) ? scalar @domains + 1 : $size);
  728:     $scrout.="\n".'<font color="#800000" face="helvetica"><b>'.
  729:         'DOMAINS TO BE SEARCHED</b></font><br />'.
  730:             '<select name="domains" size="'.$size.'" multiple>'."\n".
  731:                 '<option name="any" value="any" '.
  732:                     ($domain_hash{'any'}? 'selected ' :'').
  733:                         '>all domains</option>'."\n";
  734:     foreach my $dom (sort @domains) {
  735:         $scrout.="<option name=\"$dom\" ".
  736:             ($domain_hash{$dom} ? 'selected ' :'').">$dom</option>\n";
  737:     }
  738:     $scrout.="</select>\n";
  739:     #----------------------------------------------------------------
  740:     $scrout.=&selectbox('Limit by language','language',
  741: 			$ENV{'form.language'},'any','Any Language',
  742: 			\&Apache::loncommon::languagedescription,
  743: 			(&Apache::loncommon::languageids),
  744: 			);
  745: # ------------------------------------------------ Compute date selection boxes
  746:     $scrout.=<<CREATIONDATESTART;
  747: <p>
  748: <font color="#800000" face="helvetica"><b>LIMIT BY CREATION DATE RANGE:</b>
  749: </font>
  750: <br />
  751: between:
  752: CREATIONDATESTART
  753:     $scrout.=&dateboxes('creationdatestart',1,1,1976,
  754: 			$ENV{'form.creationdatestart_month'},
  755: 			$ENV{'form.creationdatestart_day'},
  756: 			$ENV{'form.creationdatestart_year'},
  757: 			);
  758:     $scrout.="and:\n";
  759:     $scrout.=&dateboxes('creationdateend',12,31,2051,
  760: 			$ENV{'form.creationdateend_month'},
  761: 			$ENV{'form.creationdateend_day'},
  762: 			$ENV{'form.creationdateend_year'},
  763: 			);
  764:     $scrout.="</p>";
  765:     $scrout.=<<LASTREVISIONDATESTART;
  766: <p>
  767: <font color="#800000" face="helvetica"><b>LIMIT BY LAST REVISION DATE RANGE:
  768: </b></font>
  769: <br />between:
  770: LASTREVISIONDATESTART
  771:     $scrout.=&dateboxes('lastrevisiondatestart',1,1,1976,
  772: 			$ENV{'form.lastrevisiondatestart_month'},
  773: 			$ENV{'form.lastrevisiondatestart_day'},
  774: 			$ENV{'form.lastrevisiondatestart_year'},
  775: 			);
  776:     $scrout.=<<LASTREVISIONDATEEND;
  777: and:
  778: LASTREVISIONDATEEND
  779:     $scrout.=&dateboxes('lastrevisiondateend',12,31,2051,
  780: 			$ENV{'form.lastrevisiondateend_month'},
  781: 			$ENV{'form.lastrevisiondateend_day'},
  782: 			$ENV{'form.lastrevisiondateend_year'},
  783: 			);
  784:     $scrout.='</p>';
  785:     $ENV{'form.copyright'}='any' unless length($ENV{'form.copyright'});
  786:     $scrout.=&selectbox('Limit by copyright/distribution','copyright',
  787: 			 $ENV{'form.copyright'},
  788: 			 'any','Any copyright/distribution',
  789: 			 \&Apache::loncommon::copyrightdescription,
  790: 			 (&Apache::loncommon::copyrightids),
  791: 			 );
  792: # ------------------------------------------- Compute customized metadata field
  793: #    $scrout.=<<CUSTOMMETADATA;
  794: #<p>
  795: #<font color="#800000" face="helvetica"><b>LIMIT BY SPECIAL METADATA FIELDS:</b>
  796: #</font>
  797: #For resource-specific metadata, enter in an expression in the form of 
  798: #<i>key</i>=<i>value</i> separated by operators such as AND, OR or NOT.<br />
  799: #<b>Example:</b> grandmother=75 OR grandfather=85
  800: #<br />
  801: #CUSTOMMETADATA
  802: #    $scrout.=&simpletextfield('custommetadata',$ENV{'form.custommetadata'});
  803: #    $scrout.=<<CUSTOMSHOW;
  804: #<p>
  805: #<font color="#800000" face="helvetica"><b>SHOW SPECIAL METADATA FIELDS:</b>
  806: #</font>
  807: #Enter in a space-separated list of special metadata fields to show
  808: #in a fielded listing for each record result.
  809: #<br />
  810: #CUSTOMSHOW
  811: #    $scrout.=&simpletextfield('customshow',$ENV{'form.customshow'});
  812:     $scrout.=<<ENDDOCUMENT;
  813: $advanced_buttons
  814: </form>
  815: </body>
  816: </html>
  817: ENDDOCUMENT
  818:     $r->print($scrout);
  819:     return;
  820: }
  821: 
  822: ######################################################################
  823: ######################################################################
  824: 
  825: =pod 
  826: 
  827: =item &get_persistent_form_data
  828: 
  829: Inputs: filename of database
  830: 
  831: Outputs: returns undef on database errors.
  832: 
  833: This function is the reverse of &make_persistent() for form data.
  834: Retrieve persistent data from %persistent_db.  Retrieved items will have their
  835: values unescaped.  If a form value already exists in $ENV, it will not be
  836: overwritten.  Form values that are array references may have values appended
  837: to them.
  838: 
  839: =cut
  840: 
  841: ######################################################################
  842: ######################################################################
  843: sub get_persistent_form_data {
  844:     my $filename = shift;
  845:     return 0 if (! -e $filename);
  846:     return undef if (! tie(%persistent_db,'GDBM_File',$filename,
  847:                            &GDBM_READER(),0640));
  848:     #
  849:     # These make sure we do not get array references printed out as 'values'.
  850:     my %arrays_allowed = ('form.domains'=>1);
  851:     #
  852:     # Loop through the keys, looking for 'form.'
  853:     foreach my $name (keys(%persistent_db)) {
  854:         next if ($name !~ /^form./);
  855:         next if (exists($ENV{$name}));
  856:         my @values = map { 
  857:             &Apache::lonnet::unescape($_);
  858:         } split(',',$persistent_db{$name});
  859:         next if (@values <1);
  860:         if ($arrays_allowed{$name}) {
  861:             $ENV{$name} = [@values];
  862:         } else {
  863:             $ENV{$name} = $values[0] if ($values[0]);
  864:         }
  865:     }
  866:     untie (%persistent_db);
  867:     return 1;
  868: }
  869: ######################################################################
  870: ######################################################################
  871: 
  872: =pod 
  873: 
  874: =item &get_persistent_data
  875: 
  876: Inputs: filename of database, ref to array of values to recover.
  877: 
  878: Outputs: array of values.  Returns undef on error.
  879: 
  880: This function is the reverse of &make_persistent();
  881: Retrieve persistent data from %persistent_db.  Retrieved items will have their
  882: values unescaped.  If the item contains commas (before unescaping), the
  883: returned value will be an array pointer. 
  884: 
  885: =cut
  886: 
  887: ######################################################################
  888: ######################################################################
  889: sub get_persistent_data {
  890:     my $filename = shift;
  891:     my @Vars = @{shift()};
  892:     my @Values;   # Return array
  893:     return undef if (! -e $filename);
  894:     return undef if (! tie(%persistent_db,'GDBM_File',$filename,
  895:                            &GDBM_READER(),0640));
  896:     foreach my $name (@Vars) {
  897:         if (! exists($persistent_db{$name})) {
  898:             push @Values, undef;
  899:             next;
  900:         }
  901:         my @values = map { 
  902:             &Apache::lonnet::unescape($_);
  903:         } split(',',$persistent_db{$name});
  904:         if (@values <= 1) {
  905:             push @Values,$values[0];
  906:         } else {
  907:             push @Values,\@values;
  908:         }
  909:     }
  910:     untie (%persistent_db);
  911:     return @Values;
  912: }
  913: 
  914: ######################################################################
  915: ######################################################################
  916: 
  917: =pod 
  918: 
  919: =item &make_persistent() 
  920: 
  921: Inputs: Hash of values to save, filename of persistent database.
  922: 
  923: Store variables away to the %persistent_db.
  924: Values will be escaped.  Values that are array pointers will have their
  925: elements escaped and concatenated in a comma seperated string.  
  926: 
  927: =cut
  928: 
  929: ######################################################################
  930: ######################################################################
  931: sub make_persistent {
  932:     my %save = %{shift()};
  933:     my $filename = shift;
  934:     return undef if (! tie(%persistent_db,'GDBM_File',
  935:                            $filename,&GDBM_WRCREAT(),0640));
  936:     foreach my $name (keys(%save)) {
  937:         my @values = (ref($save{$name}) ? @{$save{$name}} : ($save{$name}));
  938:         # We handle array references, but not recursively.
  939:         my $store = join(',', map { &Apache::lonnet::escape($_); } @values );
  940:         $persistent_db{$name} = $store;
  941:     }
  942:     untie(%persistent_db);
  943:     return 1;
  944: }
  945: 
  946: ######################################################################
  947: ######################################################################
  948: 
  949: =pod 
  950: 
  951: =item &make_form_data_persistent() 
  952: 
  953: Inputs: filename of persistent database.
  954: 
  955: Store most form variables away to the %persistent_db.
  956: Values will be escaped.  Values that are array pointers will have their
  957: elements escaped and concatenated in a comma seperated string.  
  958: 
  959: =cut
  960: 
  961: ######################################################################
  962: ######################################################################
  963: sub make_form_data_persistent {
  964:     my $r = shift;
  965:     my $filename = shift;
  966:     my %save;
  967:     foreach (keys(%ENV)) {
  968:         next if (!/^form/ || /submit/);
  969:         $save{$_} = $ENV{$_};
  970:     }
  971:     return &make_persistent(\%save,$filename);
  972: }
  973: 
  974: ######################################################################
  975: #                HTML form building functions                        #  
  976: ######################################################################
  977: 
  978: =pod 
  979: 
  980: =item HTML form building functions
  981: 
  982: =over 4
  983: 
  984: =cut
  985: 
  986: ###############################################
  987: ###############################################
  988: 
  989: =pod
  990: 
  991: =item &simpletextfield() 
  992: 
  993: Inputs: $name,$value,$size
  994: 
  995: Returns a text input field with the given name, value, and size.  
  996: If size is not specified, a value of 20 is used.
  997: 
  998: =cut
  999: 
 1000: ###############################################
 1001: ###############################################
 1002: 
 1003: sub simpletextfield {
 1004:     my ($name,$value,$size)=@_;
 1005:     $size = 20 if (! defined($size));
 1006:     return '<input type="text" name="'.$name.
 1007:         '" size="'.$size.'" value="'.$value.'" />';
 1008: }
 1009: 
 1010: ###############################################
 1011: ###############################################
 1012: 
 1013: =pod
 1014: 
 1015: =item &simplecheckbox()
 1016: 
 1017: Inputs: $name,$value
 1018: 
 1019: Returns a simple check box with the given $name.
 1020: If $value eq 'on' the box is checked.
 1021: 
 1022: =cut
 1023: 
 1024: ###############################################
 1025: ###############################################
 1026: 
 1027: sub simplecheckbox{
 1028:     my ($name,$value,$checked)=@_;
 1029:     $checked="checked" if ($value eq 'on');
 1030:     return '<input type="checkbox" name="'.$name.'" value="'.$value.'" '.
 1031:         $checked.' />';
 1032: }
 1033: 
 1034: ###############################################
 1035: ###############################################
 1036: 
 1037: =pod
 1038: 
 1039: =item &fieldtitle()
 1040: 
 1041: Input: $title
 1042: 
 1043: Returns a scalar with html which will display $title as a search
 1044: field heading.
 1045: 
 1046: =cut
 1047: 
 1048: ###############################################
 1049: ###############################################
 1050: 
 1051: sub fieldtitle {
 1052:     my $title = uc(shift());
 1053:     return '<font color="#800000" face="helvetica"><b>'.$title.
 1054:         ':&nbsp;</b></font>';
 1055: }
 1056: 
 1057: ###############################################
 1058: ###############################################
 1059: 
 1060: =pod
 1061: 
 1062: =item &searchphrasefield()
 1063: 
 1064: Inputs: $title,$name,$value
 1065: 
 1066: Returns html for a title line and an input field for entering search terms.
 1067: The entry field (which is where the $name and $value are used) is a 50 column 
 1068: simpletextfield.  The html returned is for a row in a three column table.
 1069: 
 1070: =cut
 1071: 
 1072: ###############################################
 1073: ###############################################
 1074:     
 1075: sub searchphrasefield {
 1076:     my ($title,$name,$value)=@_;
 1077:     return '<tr><td>'.&fieldtitle($title).'</td><td>'.
 1078:         &simpletextfield($name,$value,50)."</td><td>&nbsp;</td></tr>\n";
 1079: }
 1080: 
 1081: ###############################################
 1082: ###############################################
 1083: 
 1084: =pod
 1085: 
 1086: =item &searchphrasefield_with_related()
 1087: 
 1088: Inputs: $title,$name,$value
 1089: 
 1090: Returns html for a title line and an input field for entering search terms
 1091: and a check box for 'related words'.  The entry field (which is where the 
 1092: $name and $value are used) is a 50 column simpletextfield.  The name of
 1093: the related words checkbox is "$name_related".
 1094: 
 1095: =cut
 1096: 
 1097: ###############################################
 1098: ###############################################
 1099:     
 1100: sub searchphrasefield_with_related {
 1101:     my ($title,$name,$value)=@_;
 1102:     return '<tr><td>'.&fieldtitle($title).'</td><td>'.
 1103:         &simpletextfield($name,$value,50).'</td><td align="center">&nbsp;'.
 1104:             &simplecheckbox($name.'_related',$ENV{'form.'.$name.'_related'}).
 1105:                 "&nbsp;</td></tr>\n";
 1106: }
 1107: 
 1108: ###############################################
 1109: ###############################################
 1110: 
 1111: =pod
 1112: 
 1113: =item &dateboxes()
 1114: 
 1115: Returns html selection form elements for the specification of 
 1116: the day, month, and year.
 1117: 
 1118: =cut
 1119: 
 1120: ###############################################
 1121: ###############################################
 1122: 
 1123: sub dateboxes {
 1124:     my ($name,$defaultmonth,$defaultday,$defaultyear,
 1125: 	$currentmonth,$currentday,$currentyear)=@_;
 1126:     ($defaultmonth,$defaultday,$defaultyear)=('','','');
 1127:     #
 1128:     # Day
 1129:     my $day=<<END;
 1130: <select name="${name}_day">
 1131: <option value='$defaultday'> </option>
 1132: END
 1133:     for (my $i = 1; $i<=31; $i++) {
 1134: 	$day.="<option value=\"$i\">$i</option>\n";
 1135:     }
 1136:     $day.="</select>\n";
 1137:     $day=~s/(\"$currentday\")/$1 SELECTED/ if length($currentday);
 1138:     #
 1139:     # Month
 1140:     my $month=<<END;
 1141: <select name="${name}_month">
 1142: <option value='$defaultmonth'> </option>
 1143: END
 1144:     my $i = 1;
 1145:     foreach (qw/January February March April May June 
 1146: 	     July August September October November December /){
 1147: 	$month .="<option value=\"$i\">$_</option>\n";
 1148: 	$i++;
 1149:     }
 1150:     $month.="</select>\n";
 1151:     $month=~s/(\"$currentmonth\")/$1 SELECTED/ if length($currentmonth);
 1152:     #
 1153:     # Year (obviously)
 1154:     my $year=<<END;
 1155: <select name="${name}_year">
 1156: <option value='$defaultyear'> </option>
 1157: END
 1158:     my $maxyear = 2051; 
 1159:     for (my $i = 1976; $i<=$maxyear; $i++) {
 1160: 	$year.="<option value=\"$i\">$i</option>\n";
 1161:     }
 1162:     $year.="</select>\n";
 1163:     $year=~s/(\"$currentyear\")/$1 SELECTED/ if length($currentyear);
 1164:     return "$month$day$year";
 1165: }
 1166: 
 1167: ###############################################
 1168: ###############################################
 1169: 
 1170: =pod
 1171: 
 1172: =item &selectbox()
 1173: 
 1174: Returns a scalar containing an html <select> form.  
 1175: 
 1176: Inputs: 
 1177: 
 1178: =over 4
 1179: 
 1180: =item $title 
 1181: 
 1182: Printed above the select box, in uppercase.  If undefined, only a select
 1183: box will be returned, with no additional html.
 1184: 
 1185: =item $name 
 1186: 
 1187: The name element of the <select> tag.
 1188: 
 1189: =item $default 
 1190: 
 1191: The default value of the form.  Can be $anyvalue, or in @idlist.
 1192: 
 1193: =item $anyvalue 
 1194: 
 1195: The <option value="..."> used to indicate a default of 
 1196: none of the values.  Can be undef.
 1197: 
 1198: =item $anytag 
 1199: 
 1200: The text associate with $anyvalue above.
 1201: 
 1202: =item $functionref 
 1203: 
 1204: Each element in @idlist will be passed as a parameter 
 1205: to the function referenced here.  The return value of the function should
 1206: be a scalar description of the items.  If this value is undefined the 
 1207: description of each item in @idlist will be the item name.
 1208: 
 1209: =item @idlist 
 1210: 
 1211: The items to be selected from.  One of these or $anyvalue will be the 
 1212: value returned by the form element, $ENV{form.$name}.
 1213: 
 1214: =back
 1215: 
 1216: =cut
 1217: 
 1218: ###############################################
 1219: 
 1220: sub selectbox {
 1221:     my ($title,$name,$default,$anyvalue,$anytag,$functionref,@idlist)=@_;
 1222:     if (! defined($functionref)) { $functionref = sub { $_[0]}; }
 1223:     my $selout='';
 1224:     if (defined($title)) {
 1225:         my $uctitle=uc($title);
 1226:         $selout="\n".'<p><font color="#800000" face="helvetica">'.
 1227:             '<b>'.$uctitle.': </b></font>';
 1228:     }
 1229:     $selout .= '<select name="'.$name.'">';
 1230:     unshift @idlist,$anyvalue if (defined($anyvalue));
 1231:     foreach (@idlist) {
 1232:         $selout.='<option value="'.$_.'"';
 1233:         if ($_ eq $default and !/^any$/) {
 1234: 	    $selout.=' selected >'.&{$functionref}($_).'</option>';
 1235: 	}
 1236: 	elsif ($_ eq $default and /^$anyvalue$/) {
 1237: 	    $selout.=' selected >'.$anytag.'</option>';
 1238: 	}
 1239:         else {$selout.='>'.&{$functionref}($_).'</option>';}
 1240:     }
 1241:     return $selout.'</select>'.(defined($title)?'</p>':' ');
 1242: }
 1243: 
 1244: ######################################################################
 1245: #                End of HTML form building functions                 #  
 1246: ######################################################################
 1247: 
 1248: =pod
 1249: 
 1250: =back 
 1251: 
 1252: =cut
 1253: 
 1254: 
 1255: ######################################################################
 1256: ######################################################################
 1257: 
 1258: =pod 
 1259: 
 1260: =item &parse_advanced_search()
 1261: 
 1262: Parse advanced search form and return the following:
 1263: 
 1264: =over 4
 1265: 
 1266: =item $query Scalar containing an SQL query.
 1267: 
 1268: =item $customquery Scalar containing a custom query.
 1269: 
 1270: =item $customshow Scalar containing commands to show custom metadata.
 1271: 
 1272: =item $libraries_to_query Reference to array of domains to search.
 1273: 
 1274: =back
 1275: 
 1276: =cut
 1277: 
 1278: ######################################################################
 1279: ######################################################################
 1280: sub parse_advanced_search {
 1281:     my ($r,$closebutton)=@_;
 1282:     my $fillflag=0;
 1283:     my $pretty_search_string = "<br />\n";
 1284:     # Clean up fields for safety
 1285:     for my $field ('title','author','subject','keywords','url','version',
 1286: 		   'creationdatestart_month','creationdatestart_day',
 1287: 		   'creationdatestart_year','creationdateend_month',
 1288: 		   'creationdateend_day','creationdateend_year',
 1289: 		   'lastrevisiondatestart_month','lastrevisiondatestart_day',
 1290: 		   'lastrevisiondatestart_year','lastrevisiondateend_month',
 1291: 		   'lastrevisiondateend_day','lastrevisiondateend_year',
 1292: 		   'notes','abstract','extension','language','owner',
 1293: 		   'custommetadata','customshow','category') {
 1294: 	$ENV{"form.$field"}=~s/[^\w\/\s\(\)\=\-\"\']//g;
 1295:     }
 1296:     foreach ('mode','form','element') {
 1297: 	# is this required?  Hmmm.
 1298: 	next unless (exists($ENV{"form.$_"}));
 1299: 	$ENV{"form.$_"}=&Apache::lonnet::unescape($ENV{"form.$_"});
 1300: 	$ENV{"form.$_"}=~s/[^\w\/\s\(\)\=\-\"\']//g;
 1301:     }
 1302:     # Preprocess the category form element.
 1303:     $ENV{'form.category'} = 'any' if (! defined($ENV{'form.category'}) ||
 1304:                                       ref($ENV{'form.category'}));
 1305:     #
 1306:     # Check to see if enough information was filled in
 1307:     for my $field ('title','author','subject','keywords','url','version',
 1308: 		   'notes','abstract','category','extension','language',
 1309:                    'owner','custommetadata') {
 1310: 	if (&filled($ENV{"form.$field"})) {
 1311: 	    $fillflag++;
 1312: 	}
 1313:     }
 1314:     unless ($fillflag) {
 1315: 	&output_blank_field_error($r,$closebutton,'phase=disp_adv');
 1316: 	return ;
 1317:     }
 1318:     # Turn the form input into a SQL-based query
 1319:     my $query='';
 1320:     my @queries;
 1321:     my $font = '<font color="#800000" face="helvetica">';
 1322:     # Evaluate logical expression AND/OR/NOT phrase fields.
 1323:     foreach my $field ('title','author','subject','notes','abstract','url',
 1324: 		       'keywords','version','owner') {
 1325: 	if ($ENV{'form.'.$field}) {
 1326:             my $searchphrase = $ENV{'form.'.$field};
 1327:             $pretty_search_string .= $font."$field</font> contains <b>".
 1328:                 $searchphrase."</b>";
 1329:             if ($ENV{'form.'.$field.'_related'}) {
 1330:                 my @New_Words;
 1331:                 ($searchphrase,@New_Words) = &related_version($searchphrase);
 1332:                 if (@New_Words) {
 1333:                     $pretty_search_string .= " with related words: ".
 1334:                         "<b>@New_Words</b>.";
 1335:                 } else {
 1336:                     $pretty_search_string .= " with no related words.";
 1337:                 }
 1338:             }
 1339:             $pretty_search_string .= "<br />\n";
 1340: 	    push @queries,&build_SQL_query($field,$searchphrase);
 1341:         }
 1342:     }
 1343:     #
 1344:     # Make the 'mime' from 'form.category' and 'form.extension'
 1345:     #
 1346:     my $searchphrase;
 1347:     if (exists($ENV{'form.category'})    && 
 1348:         $ENV{'form.category'} !~ /^\s*$/ &&
 1349:         $ENV{'form.category'} ne 'any')     {
 1350:         my @extensions = &Apache::loncommon::filecategorytypes
 1351:                                                    ($ENV{'form.category'});
 1352:         if (scalar(@extensions) > 0) {
 1353:             $searchphrase = join(' OR ',@extensions);
 1354:         }
 1355:     }
 1356:     if (exists($ENV{'form.extension'}) && $ENV{'form.extension'} !~ /^\s*$/) {
 1357:         $searchphrase .= ' OR ' if (defined($searchphrase));
 1358:         my @extensions = split(/,/,$ENV{'form.extension'});
 1359:         $searchphrase .= join(' OR ',@extensions);
 1360:     }
 1361:     if (defined($searchphrase)) {
 1362:         push @queries,&build_SQL_query('mime',$searchphrase);
 1363:         $pretty_search_string .=$font.'mime</font> contains <b>'.
 1364:             $searchphrase.'</b><br />';
 1365:     }
 1366:     #####
 1367:     # Evaluate option lists
 1368:     if ($ENV{'form.language'} and $ENV{'form.language'} ne 'any') {
 1369: 	push @queries,"(language like \"$ENV{'form.language'}\")";
 1370:         $pretty_search_string.=$font."language</font>= ".
 1371:             &Apache::loncommon::languagedescription($ENV{'form.language'}).
 1372:                 "<br />\n";
 1373:     }
 1374:     if ($ENV{'form.copyright'} and $ENV{'form.copyright'} ne 'any') {
 1375: 	push @queries,"(copyright like \"$ENV{'form.copyright'}\")";
 1376:         $pretty_search_string.=$font."copyright</font> = ".
 1377:             &Apache::loncommon::copyrightdescription($ENV{'form.copyright'}).
 1378:                 "<br \>\n";
 1379:     }
 1380:     #
 1381:     # Evaluate date windows
 1382:     my $datequery=&build_date_queries(
 1383: 			$ENV{'form.creationdatestart_month'},
 1384: 			$ENV{'form.creationdatestart_day'},
 1385: 			$ENV{'form.creationdatestart_year'},
 1386: 			$ENV{'form.creationdateend_month'},
 1387: 			$ENV{'form.creationdateend_day'},
 1388: 			$ENV{'form.creationdateend_year'},
 1389: 			$ENV{'form.lastrevisiondatestart_month'},
 1390: 			$ENV{'form.lastrevisiondatestart_day'},
 1391: 			$ENV{'form.lastrevisiondatestart_year'},
 1392: 			$ENV{'form.lastrevisiondateend_month'},
 1393: 			$ENV{'form.lastrevisiondateend_day'},
 1394: 			$ENV{'form.lastrevisiondateend_year'},
 1395: 			);
 1396:     # Test to see if date windows are legitimate
 1397:     if ($datequery=~/^Incorrect/) {
 1398: 	&output_date_error($r,$datequery,$closebutton);
 1399: 	return ;
 1400:     } elsif ($datequery) {
 1401:         # Here is where you would set up pretty_search_string to output
 1402:         # date query information.
 1403: 	push @queries,$datequery;
 1404:     }
 1405:     # Process form information for custom metadata querying
 1406:     my $customquery=undef;
 1407: #    if ($ENV{'form.custommetadata'}) {
 1408: #        $pretty_search_string .=$font."Custom Metadata Search</font>: <b>".
 1409: #            $ENV{'form.custommetadata'}."</b><br />\n";
 1410: #	$customquery=&build_custommetadata_query('custommetadata',
 1411: #				      $ENV{'form.custommetadata'});
 1412: #    }
 1413:     my $customshow=undef;
 1414: #    if ($ENV{'form.customshow'}) {
 1415: #        $pretty_search_string .=$font."Custom Metadata Display</font>: <b>".
 1416: #            $ENV{'form.customshow'}."</b><br />\n";
 1417: #	$customshow=$ENV{'form.customshow'};
 1418: #	$customshow=~s/[^\w\s]//g;
 1419: #	my @fields=split(/\s+/,$customshow);
 1420: #	$customshow=join(" ",@fields);
 1421: #    }
 1422:     ## ---------------------------------------------------------------
 1423:     ## Deal with restrictions to given domains
 1424:     ## 
 1425:     my ($libraries_to_query,$pretty_domains_string) = 
 1426:         &parse_domain_restrictions();
 1427:     $pretty_search_string .= $pretty_domains_string."<br />\n";
 1428:     #
 1429:     if (@queries) {
 1430: 	$query=join(" AND ",@queries);
 1431: 	$query="select * from metadata where $query";
 1432:     } elsif ($customquery) {
 1433:         $query = '';
 1434:     }
 1435:     return ($query,$customquery,$customshow,$libraries_to_query,
 1436:             $pretty_search_string);
 1437: }
 1438: 
 1439: sub parse_domain_restrictions {
 1440:     my $libraries_to_query = undef;
 1441:     # $ENV{'form.domains'} can be either a scalar or an array reference.
 1442:     # We need an array.
 1443:     if (! exists($ENV{'form.domains'})) {
 1444:         return (undef,'');
 1445:     }
 1446:     my @allowed_domains;
 1447:     if (ref($ENV{'form.domains'})) {
 1448:         @allowed_domains =  @{$ENV{'form.domains'}};
 1449:     } else {
 1450:         @allowed_domains = ($ENV{'form.domains'});
 1451:     }
 1452:     my %domain_hash = ();
 1453:     my $pretty_domains_string;
 1454:     foreach (@allowed_domains) {
 1455:         $domain_hash{$_}++;
 1456:     }
 1457:     if ($domain_hash{'any'}) {
 1458:         $pretty_domains_string = "In all LON-CAPA domains.";
 1459:     } else {
 1460:         if (@allowed_domains > 1) {
 1461:             $pretty_domains_string = "In LON-CAPA domains:";
 1462:         } else {
 1463:             $pretty_domains_string = "In LON-CAPA domain ";
 1464:         }
 1465:         foreach (sort @allowed_domains) {
 1466:             $pretty_domains_string .= "<b>".$_."</b> ";
 1467:         }
 1468:         foreach (keys(%Apache::lonnet::libserv)) {
 1469:             if (exists($domain_hash{$Apache::lonnet::hostdom{$_}})) {
 1470:                 push @$libraries_to_query,$_;
 1471:             }
 1472:         }
 1473:     }
 1474:     return ($libraries_to_query,$pretty_domains_string);
 1475: }
 1476: 
 1477: ######################################################################
 1478: ######################################################################
 1479: 
 1480: =pod 
 1481: 
 1482: =item &parse_basic_search() 
 1483: 
 1484: Parse the basic search form and return a scalar containing an sql query.
 1485: 
 1486: =cut
 1487: 
 1488: ######################################################################
 1489: ######################################################################
 1490: sub parse_basic_search {
 1491:     my ($r,$closebutton)=@_;
 1492:     # Clean up fields for safety
 1493:     for my $field ('basicexp') {
 1494: 	$ENV{"form.$field"}=~s/[^\w\s\(\)\-]//g;
 1495:     }
 1496:     foreach ('mode','form','element') {
 1497: 	# is this required?  Hmmm.
 1498: 	next unless (exists($ENV{"form.$_"}));
 1499: 	$ENV{"form.$_"}=&Apache::lonnet::unescape($ENV{"form.$_"});
 1500: 	$ENV{"form.$_"}=~s/[^\w\/\s\(\)\=\-\"\']//g;
 1501:     }
 1502:     my ($libraries_to_query,$pretty_domains_string) = 
 1503:         &parse_domain_restrictions();
 1504:     # Check to see if enough is filled in
 1505:     unless (&filled($ENV{'form.basicexp'})) {
 1506: 	&output_blank_field_error($r,$closebutton,'phase=disp_basic');
 1507: 	return OK;
 1508:     }
 1509:     my $pretty_search_string = '<b>'.$ENV{'form.basicexp'}.'</b>';
 1510:     my $search_string = $ENV{'form.basicexp'};
 1511:     if ($ENV{'form.related'}) {
 1512:         my @New_Words;
 1513:         ($search_string,@New_Words) = &related_version($ENV{'form.basicexp'});
 1514:         if (@New_Words) {
 1515:             $pretty_search_string .= " with related words: <b>@New_Words</b>.";
 1516:         } else {
 1517:             $pretty_search_string .= " with no related words.";
 1518:         }
 1519:     }
 1520:     # Build SQL query string based on form page
 1521:     my $query='';
 1522:     my $concatarg=join(',',
 1523: 		       ('title', 'author', 'subject', 'notes', 'abstract',
 1524:                         'keywords'));
 1525:     $concatarg='title' if $ENV{'form.titleonly'};
 1526:     $query=&build_SQL_query('concat_ws(" ",'.$concatarg.')',$search_string);
 1527:     if (defined($pretty_domains_string) && $pretty_domains_string ne '') {
 1528:         $pretty_search_string .= ' '.$pretty_domains_string;
 1529:     }
 1530:     $pretty_search_string .= "<br />\n";
 1531:     return ('SELECT * FROM metadata WHERE '.$query,$pretty_search_string,
 1532:             $libraries_to_query);
 1533: }
 1534: 
 1535: 
 1536: ######################################################################
 1537: ######################################################################
 1538: 
 1539: =pod 
 1540: 
 1541: =item &related_version
 1542: 
 1543: Modifies an input string to include related words.  Words in the string
 1544: are replaced with parenthesized lists of 'OR'd words.  For example
 1545: "torque" is replaced with "(torque OR word1 OR word2 OR ...)".  
 1546: 
 1547: Note: Using this twice on a string is probably silly.
 1548: 
 1549: =cut
 1550: 
 1551: ######################################################################
 1552: ######################################################################
 1553: sub related_version {
 1554:     my $search_string = shift;
 1555:     my $result = $search_string;
 1556:     my %New_Words = ();
 1557:     while ($search_string =~ /(\w+)/cg) {
 1558:         my $word = $1;
 1559:         next if (lc($word) =~ /\b(or|and|not)\b/);
 1560:         my @Words = &Apache::loncommon::get_related_words($word);
 1561:         @Words = ($#Words>4? @Words[0..4] : @Words);
 1562:         foreach (@Words) { $New_Words{$_}++;}
 1563:         my $replacement = join " OR ", ($word,@Words);
 1564:         $result =~ s/(\b)$word(\b)/$1($replacement)$2/g;
 1565:     }
 1566:     return $result,sort(keys(%New_Words));
 1567: }
 1568: 
 1569: ######################################################################
 1570: ######################################################################
 1571: 
 1572: =pod 
 1573: 
 1574: =item &build_SQL_query() 
 1575: 
 1576: Builds a SQL query string from a logical expression with AND/OR keywords
 1577: using Text::Query and &recursive_SQL_query_builder()
 1578: 
 1579: =cut
 1580: 
 1581: ######################################################################
 1582: ######################################################################
 1583: sub build_SQL_query {
 1584:     my ($field_name,$logic_statement)=@_;
 1585:     my $q=new Text::Query('abc',
 1586: 			  -parse => 'Text::Query::ParseAdvanced',
 1587: 			  -build => 'Text::Query::Build');
 1588:     $q->prepare($logic_statement);
 1589:     my $matchexp=${$q}{'matchexp'}; chomp $matchexp;
 1590:     my $sql_query=&recursive_SQL_query_build($field_name,$matchexp);
 1591:     return $sql_query;
 1592: }
 1593: 
 1594: ######################################################################
 1595: ######################################################################
 1596: 
 1597: =pod 
 1598: 
 1599: =item &build_custommetadata_query() 
 1600: 
 1601: Constructs a custom metadata query using a rather heinous regular
 1602: expression.
 1603: 
 1604: =cut
 1605: 
 1606: ######################################################################
 1607: ######################################################################
 1608: sub build_custommetadata_query {
 1609:     my ($field_name,$logic_statement)=@_;
 1610:     my $q=new Text::Query('abc',
 1611: 			  -parse => 'Text::Query::ParseAdvanced',
 1612: 			  -build => 'Text::Query::BuildAdvancedString');
 1613:     $q->prepare($logic_statement);
 1614:     my $matchexp=${$q}{'-parse'}{'-build'}{'matchstring'};
 1615:     # quick fix to change literal into xml tag-matching
 1616:     # will eventually have to write a separate builder module
 1617:     # wordone=wordtwo becomes\<wordone\>[^\<] *wordtwo[^\<]*\<\/wordone\>
 1618:     $matchexp =~ s/(\w+)\\=([\w\\\+]+)?# wordone=wordtwo is changed to 
 1619:                  /\\<$1\\>?#           \<wordone\>
 1620:                    \[\^\\<\]?#        [^\<]         
 1621:                    \*$2\[\^\\<\]?#           *wordtwo[^\<]
 1622:                    \*\\<\\\/$1\\>?#                        *\<\/wordone\>
 1623:                    /g;
 1624:     return $matchexp;
 1625: }
 1626: 
 1627: ######################################################################
 1628: ######################################################################
 1629: 
 1630: =pod 
 1631: 
 1632: =item &recursive_SQL_query_build() 
 1633: 
 1634: Recursively constructs an SQL query.  Takes as input $dkey and $pattern.
 1635: 
 1636: =cut
 1637: 
 1638: ######################################################################
 1639: ######################################################################
 1640: sub recursive_SQL_query_build {
 1641:     my ($dkey,$pattern)=@_;
 1642:     my @matches=($pattern=~/(\[[^\]|\[]*\])/g);
 1643:     return $pattern unless @matches;
 1644:     foreach my $match (@matches) {
 1645:         $match=~/\[ (\w+)\s(.*) \]/;
 1646:         my ($key,$value)=($1,$2);
 1647:         my $replacement='';
 1648:         if ($key eq 'literal') {
 1649:             $replacement="($dkey LIKE \"\%$value\%\")";
 1650:         } elsif (lc($key) eq 'not') {
 1651:             $value=~s/LIKE/NOT LIKE/;
 1652: #          $replacement="($dkey not like $value)";
 1653:             $replacement="$value";
 1654:         } elsif ($key eq 'and') {
 1655:             $value=~/(.*[\"|\)]) ([|\(|\^].*)/;
 1656:             $replacement="($1 AND $2)";
 1657: 	} elsif ($key eq 'or') {
 1658:             $value=~/(.*[\"|\)]) ([|\(|\^].*)/;
 1659:             $replacement="($1 OR $2)";
 1660: 	}
 1661: 	substr($pattern,
 1662:                index($pattern,$match),
 1663:                length($match),
 1664:                $replacement);
 1665:     }
 1666:     &recursive_SQL_query_build($dkey,$pattern);
 1667: }
 1668: 
 1669: ######################################################################
 1670: ######################################################################
 1671: 
 1672: =pod 
 1673: 
 1674: =item &build_date_queries() 
 1675: 
 1676: Builds a SQL logic query to check time/date entries.
 1677: Also reports errors (check for /^Incorrect/).
 1678: 
 1679: =cut
 1680: 
 1681: ######################################################################
 1682: ######################################################################
 1683: sub build_date_queries {
 1684:     my ($cmonth1,$cday1,$cyear1,$cmonth2,$cday2,$cyear2,
 1685: 	$lmonth1,$lday1,$lyear1,$lmonth2,$lday2,$lyear2)=@_;
 1686:     my @queries;
 1687:     if ($cmonth1 or $cday1 or $cyear1 or $cmonth2 or $cday2 or $cyear2) {
 1688: 	unless ($cmonth1 and $cday1 and $cyear1 and
 1689: 		$cmonth2 and $cday2 and $cyear2) {
 1690: 	    return "Incorrect entry for the creation date.  You must specify ".
 1691: 		   "a starting month, day, and year and an ending month, ".
 1692: 		   "day, and year.";
 1693: 	}
 1694: 	my $cnumeric1=sprintf("%d%2d%2d",$cyear1,$cmonth1,$cday1);
 1695: 	$cnumeric1+=0;
 1696: 	my $cnumeric2=sprintf("%d%2d%2d",$cyear2,$cmonth2,$cday2);
 1697: 	$cnumeric2+=0;
 1698: 	if ($cnumeric1>$cnumeric2) {
 1699: 	    return "Incorrect entry for the creation date.  The starting ".
 1700: 		   "date must occur before the ending date.";
 1701: 	}
 1702: 	my $cquery="(creationdate BETWEEN '$cyear1-$cmonth1-$cday1' AND '".
 1703: 	           "$cyear2-$cmonth2-$cday2 23:59:59')";
 1704: 	push @queries,$cquery;
 1705:     }
 1706:     if ($lmonth1 or $lday1 or $lyear1 or $lmonth2 or $lday2 or $lyear2) {
 1707: 	unless ($lmonth1 and $lday1 and $lyear1 and
 1708: 		$lmonth2 and $lday2 and $lyear2) {
 1709: 	    return "Incorrect entry for the last revision date.  You must ".
 1710: 		   "specify a starting month, day, and year and an ending ".
 1711: 		   "month, day, and year.";
 1712: 	}
 1713: 	my $lnumeric1=sprintf("%d%2d%2d",$lyear1,$lmonth1,$lday1);
 1714: 	$lnumeric1+=0;
 1715: 	my $lnumeric2=sprintf("%d%2d%2d",$lyear2,$lmonth2,$lday2);
 1716: 	$lnumeric2+=0;
 1717: 	if ($lnumeric1>$lnumeric2) {
 1718: 	    return "Incorrect entry for the last revision date.  The ".
 1719: 		   "starting date must occur before the ending date.";
 1720: 	}
 1721: 	my $lquery="(lastrevisiondate BETWEEN '$lyear1-$lmonth1-$lday1' AND '".
 1722: 	           "$lyear2-$lmonth2-$lday2 23:59:59')";
 1723: 	push @queries,$lquery;
 1724:     }
 1725:     if (@queries) {
 1726: 	return join(" AND ",@queries);
 1727:     }
 1728:     return '';
 1729: }
 1730: 
 1731: ######################################################################
 1732: ######################################################################
 1733: 
 1734: =pod
 1735: 
 1736: =item &copyright_check()
 1737: 
 1738: =cut
 1739: 
 1740: ######################################################################
 1741: ######################################################################
 1742: sub copyright_check {
 1743:     my $Metadata = shift;
 1744:     # Check copyright tags and skip results the user cannot use
 1745:     my (undef,undef,$resdom,$resname) = split('/',
 1746:                                               $Metadata->{'url'});
 1747:     # Check for priv
 1748:     if (($Metadata->{'copyright'} eq 'priv') && 
 1749:         (($ENV{'user.name'} ne $resname) &&
 1750:          ($ENV{'user.domain'} ne $resdom))) {
 1751:         return 0;
 1752:     }
 1753:     # Check for domain
 1754:     if (($Metadata->{'copyright'} eq 'domain') &&
 1755:         ($ENV{'user.domain'} ne $resdom)) {
 1756:         return 0;
 1757:     }
 1758:     return 1;
 1759: }
 1760: 
 1761: 
 1762: ######################################################################
 1763: ######################################################################
 1764: 
 1765: =pod
 1766: 
 1767: =item &ensure_db_and_table
 1768: 
 1769: Ensure we can get lonmysql to connect to the database and the table we
 1770: need exists.
 1771: 
 1772: Inputs: $r, table id
 1773: 
 1774: Returns: undef on error, 1 if the table exists.
 1775: 
 1776: =cut
 1777: 
 1778: ######################################################################
 1779: ######################################################################
 1780: sub ensure_db_and_table {
 1781:     my ($r,$table) = @_;
 1782:     ##
 1783:     ## Sanity check the table id.
 1784:     ##
 1785:     if (! defined($table) || $table eq '' || $table =~ /\D/ ) {
 1786:         $r->print("Unable to retrieve search results.  ".
 1787:                   "Unable to determine the table results were stored in.  ".
 1788:                   "</body></html>");
 1789:         return undef;
 1790:     }
 1791:     ##
 1792:     ## Make sure we can connect and the table exists.
 1793:     ##
 1794:     my $connection_result = &Apache::lonmysql::connect_to_db();
 1795:     if (!defined($connection_result)) {
 1796:         $r->print("Unable to connect to the MySQL database where your results".
 1797:                   " are stored. </body></html>");
 1798:         &Apache::lonnet::logthis("lonsearchcat: unable to get lonmysql to".
 1799:                                  " connect to database.");
 1800:         &Apache::lonnet::logthis(&Apache::lonmysql::get_error());
 1801:         return undef;
 1802:     }
 1803:     my $table_check = &Apache::lonmysql::check_table($table);
 1804:     if (! defined($table_check)) {
 1805:         $r->print("A MySQL error has occurred.</form></body></html>");
 1806:         &Apache::lonnet::logthis("lonmysql was unable to determine the status".
 1807:                                  " of table ".$table);
 1808:         return undef;
 1809:     } elsif (! $table_check) {
 1810:         $r->print("The table of results could not be found.");
 1811:         &Apache::lonnet::logthis("The user requested a table, ".$table.
 1812:                                  ", that could not be found.");
 1813:         return undef;
 1814:     }
 1815:     return 1;
 1816: }
 1817: 
 1818: ######################################################################
 1819: ######################################################################
 1820: 
 1821: =pod
 1822: 
 1823: =item &print_sort_form
 1824: 
 1825: =cut
 1826: 
 1827: ######################################################################
 1828: ######################################################################
 1829: sub print_sort_form {
 1830:     my ($r,$pretty_query_string) = @_;
 1831:     ##
 1832:     my %SortableFields = 
 1833:         (id        => 'Default',
 1834:          title     => 'Title',
 1835:          author    => 'Author',
 1836:          subject   => 'Subject',
 1837:          url       => 'URL',
 1838:          version   => 'Version Number',
 1839:          mime      => 'Mime type',
 1840:          lang      => 'Language',
 1841:          owner     => 'Owner/Publisher',
 1842:          copyright => 'Copyright',
 1843:          hostname  => 'Host',
 1844:          creationdate     => 'Creation Date',
 1845:          lastrevisiondate => 'Revision Date',
 1846:      );
 1847:     ##
 1848:     my $table = $ENV{'form.table'};
 1849:     return if (! &ensure_db_and_table($r,$table));
 1850:     ##
 1851:     ## Get the number of results 
 1852:     ##
 1853:     my $total_results = &Apache::lonmysql::number_of_rows($table);
 1854:     if (! defined($total_results)) {
 1855:         $r->print("A MySQL error has occurred.</form></body></html>");
 1856:         &Apache::lonnet::logthis("lonmysql was unable to determine the number".
 1857:                                  " of rows in table ".$table);
 1858:         &Apache::lonnet::logthis(&Apache::lonmysql::get_error());
 1859:         return;
 1860:     }
 1861:     my $result;
 1862:     $result.=<<END;
 1863: <html>
 1864: <head>
 1865: <script>
 1866:     function change_sort() {
 1867:         var newloc = "/adm/searchcat?phase=results";
 1868:         newloc += "&persistent_db_id=$ENV{'form.persistent_db_id'}";
 1869:         newloc += "&sortby=";
 1870:         newloc += document.forms.statusform.elements.sortby.value;
 1871:         parent.resultsframe.location= newloc;
 1872:     }
 1873: </script>
 1874: <title>Results</title>
 1875: </head>
 1876: $bodytag
 1877: <form name="statusform" action="" method="post">
 1878: <input type="hidden" name="Queue" value="" />
 1879: END
 1880: 
 1881: #<h2>Sort Results</h2>
 1882: #Sort by: <select size="1" name="sortby" onchange="javascript:change_sort();">
 1883: #    $ENV{'form.sortby'} = 'id' if (! defined($ENV{'form.sortby'}));
 1884: #    foreach (keys(%SortableFields)) {
 1885: #        $result.="<option name=\"$_\"";
 1886: #        if ($_ eq $ENV{'form.sortby'}) {
 1887: #            $result.=" selected ";
 1888: #        }
 1889: #        $result.=" >$SortableFields{$_}</option>\n";
 1890: #    }
 1891: #    $result.="</select>\n";
 1892:     my $revise = &revise_button();
 1893:     $result.=<<END;
 1894: <p>
 1895: There are $total_results matches to your query. $revise
 1896: </p><p>
 1897: Search:$pretty_query_string
 1898: </p>
 1899: </form>
 1900: </body>
 1901: </html>
 1902: END
 1903:     $r->print($result);
 1904:     return;
 1905: }
 1906: 
 1907: #####################################################################
 1908: #####################################################################
 1909: 
 1910: =pod
 1911: 
 1912: =item MySQL Table Description
 1913: 
 1914: MySQL table creation requires a precise description of the data to be
 1915: stored.  The use of the correct types to hold data is vital to efficient
 1916: storage and quick retrieval of records.  The columns must be described in
 1917: the following format:
 1918: 
 1919: =cut
 1920: 
 1921: #####################################################################
 1922: #####################################################################
 1923: 
 1924: my @Datatypes = 
 1925:     ( { name => 'id', 
 1926:         type => 'MEDIUMINT',
 1927:         restrictions => 'UNSIGNED NOT NULL',
 1928:         primary_key  => 'yes',
 1929:         auto_inc     => 'yes' },
 1930:       { name => 'title',     type=>'TEXT'},
 1931:       { name => 'author',    type=>'TEXT'},
 1932:       { name => 'subject',   type=>'TEXT'},
 1933:       { name => 'url',       type=>'TEXT', restrictions => 'NOT NULL' },
 1934:       { name => 'keywords',  type=>'TEXT'},
 1935:       { name => 'version',   type=>'TEXT'},
 1936:       { name => 'notes',     type=>'TEXT'},
 1937:       { name => 'abstract',  type=>'TEXT'},
 1938:       { name => 'mime',      type=>'TEXT'},
 1939:       { name => 'lang',      type=>'TEXT'},
 1940:       { name => 'owner',     type=>'TEXT'},
 1941:       { name => 'copyright', type=>'TEXT'},
 1942:       { name => 'hostname',  type=>'TEXT'},
 1943:       #--------------------------------------------------
 1944:       { name => 'creationdate',     type=>'DATETIME'},
 1945:       { name => 'lastrevisiondate', type=>'DATETIME'},
 1946:       #--------------------------------------------------
 1947:       );
 1948: 
 1949: my @Fullindicies = 
 1950:     qw/title/;
 1951: #    qw/title author subject abstract mime language owner copyright/;
 1952:     
 1953: ######################################################################
 1954: ######################################################################
 1955: 
 1956: =pod
 1957: 
 1958: =item &create_results_table()
 1959: 
 1960: Creates the table of search results by calling lonmysql.  Stores the
 1961: table id in $ENV{'form.table'}
 1962: 
 1963: Inputs: none.
 1964: 
 1965: Returns: the identifier of the table on success, undef on error.
 1966: 
 1967: =cut
 1968: 
 1969: ######################################################################
 1970: ######################################################################
 1971: sub create_results_table {
 1972:     my $table = &Apache::lonmysql::create_table
 1973:         ( { columns => \@Datatypes,
 1974:             FULLTEXT => [{'columns' => \@Fullindicies},],
 1975:         } );
 1976:     if (defined($table)) {
 1977:         $ENV{'form.table'} = $table;
 1978:         return $table;
 1979:     } 
 1980:     return undef; # Error...
 1981: }
 1982: 
 1983: ######################################################################
 1984: ######################################################################
 1985: 
 1986: =pod
 1987: 
 1988: =item Search Status update functions
 1989: 
 1990: Each of the following functions changes the values of one of the
 1991: input fields used to display the search status to the user.  The names
 1992: should be explanatory.
 1993: 
 1994: Inputs: Apache request handler ($r), text to display.
 1995: 
 1996: Returns: Nothing.
 1997: 
 1998: =over 4
 1999: 
 2000: =item &update_count_status()
 2001: 
 2002: =item &update_status()
 2003: 
 2004: =item &update_seconds()
 2005: 
 2006: =back
 2007: 
 2008: =cut
 2009: 
 2010: ######################################################################
 2011: ######################################################################
 2012: sub update_count_status {
 2013:     my ($r,$text) = @_;
 2014:     $text =~ s/\'/\\\'/g;
 2015:     $r->print
 2016:         ("<script>document.statusform.count.value = ' $text'</script>\n");
 2017:     $r->rflush();
 2018: }
 2019: 
 2020: sub update_status {
 2021:     my ($r,$text) = @_;
 2022:     $text =~ s/\'/\\\'/g;
 2023:     $r->print
 2024:         ("<script>document.statusform.status.value = ' $text'</script>\n");
 2025:     $r->rflush();
 2026: }
 2027: 
 2028: sub update_seconds {
 2029:     my ($r,$text) = @_;
 2030:     $text =~ s/\'/\\\'/g;
 2031:     $r->print
 2032:         ("<script>document.statusform.seconds.value = ' $text'</script>\n");
 2033:     $r->rflush();
 2034: }
 2035: 
 2036: ######################################################################
 2037: ######################################################################
 2038: 
 2039: =pod
 2040: 
 2041: =item &revise_button
 2042: 
 2043: Inputs: None
 2044: 
 2045: Returns: html string for a 'revise search' button.
 2046: 
 2047: =cut
 2048: 
 2049: ######################################################################
 2050: ######################################################################
 2051: sub revise_button {
 2052:     my $revise_phase = 'disp_basic';
 2053:     $revise_phase = 'disp_adv' if ($ENV{'form.searchmode'} eq 'advanced');
 2054:     my $newloc = '/adm/searchcat'.
 2055:         '?persistent_db_id='.$ENV{'form.persistent_db_id'}.
 2056:             '&cleargroupsort=1'.
 2057:             '&phase='.$revise_phase;
 2058:     my $result = qq{<input type="button" value="Revise search" name="revise"} .
 2059:         qq{ onClick="parent.location='$newloc';" /> };
 2060:     return $result;
 2061: }
 2062: 
 2063: ######################################################################
 2064: ######################################################################
 2065: 
 2066: =pod
 2067: 
 2068: =item &run_search 
 2069: 
 2070: =cut
 2071: 
 2072: ######################################################################
 2073: ######################################################################
 2074: sub run_search {
 2075:     my ($r,$query,$customquery,$customshow,$serverlist,$pretty_string) = @_;
 2076:     my $connection = $r->connection;
 2077:     #
 2078:     # Timing variables
 2079:     #
 2080:     my $starttime = time;
 2081:     my $max_time  = 30;  # seconds for the search to complete
 2082:     #
 2083:     # Print run_search header
 2084:     #
 2085:     $r->print(<<END);
 2086: <html>
 2087: <head><title>Search Status</title></head>
 2088: $bodytag
 2089: <form name="statusform" action="" method="post">
 2090: <input type="hidden" name="Queue" value="" />
 2091: END
 2092:     # Check to see if $pretty_string has more than one carriage return.
 2093:     # Assume \n s are following <br /> s and truncate the value.
 2094:     # (there is probably a better way)...
 2095:     my @Lines = split /<br \/>/,$pretty_string;
 2096:     if (@Lines > 2) {
 2097:         $pretty_string = join '<br \>',(@Lines[0..2],'....<br />');
 2098:     }
 2099:     $r->print("Search: ".$pretty_string);
 2100:     $r->rflush();
 2101:     #
 2102:     # Determine the servers we need to contact.
 2103:     #
 2104:     my @Servers_to_contact;
 2105:     if (defined($serverlist)) {
 2106:         if (ref($serverlist) eq 'ARRAY') {
 2107:             @Servers_to_contact = @$serverlist;
 2108:         } else {
 2109:             @Servers_to_contact = ($serverlist);
 2110:         }
 2111:     } else {
 2112:         @Servers_to_contact = sort(keys(%Apache::lonnet::libserv));
 2113:     }
 2114:     my %Server_status;
 2115:     my $table =$ENV{'form.table'};
 2116:     if (! defined($table) || $table eq '' || $table =~ /\D/ ) {
 2117:         $r->print("Unable to determine table id to store search results in.".
 2118:                   "The search has been aborted.</body></html>");
 2119:         return;
 2120:     }
 2121:     my $table_status = &Apache::lonmysql::check_table($table);
 2122:     if (! defined($table_status)) {
 2123:         $r->print("Unable to determine status of table.</body></html>");
 2124:         &Apache::lonnet::logthis("Bogus table id of $table for ".
 2125:                                  "$ENV{'user.name'} @ $ENV{'user.domain'}");
 2126:         &Apache::lonnet::logthis("lonmysql error = ".
 2127:                                  &Apache::lonmysql::get_error());
 2128:         return;
 2129:     }
 2130:     if (! $table_status) {
 2131:         $r->print("The table id,$table, we tried to use is invalid.".
 2132:                   "The search has been aborted.</body></html>");
 2133:         return;
 2134:     }
 2135:     ##
 2136:     ## Prepare for the big loop.
 2137:     ##
 2138:     my $hitcountsum;
 2139:     my $server; 
 2140:     my $status;
 2141:     my $revise = &revise_button();
 2142:     $r->print(<<END);
 2143: <table>
 2144: <tr><th>Status</th><th>Total Matches</th><th>Time Remaining</th><th></th></tr>
 2145: <tr>
 2146: <td><input type="text" name="status"  value="" size="30" /></td>
 2147: <td><input type="text" name="count"   value="" size="10" /></td>
 2148: <td><input type="text" name="seconds" value="" size="8" /></td>
 2149: <td>$revise</td>
 2150: </tr>
 2151: </table>
 2152: </form>
 2153: END
 2154:     $r->rflush();
 2155:     my $time_remaining = $max_time - (time - $starttime) ;
 2156:     my $last_time = $time_remaining;
 2157:     &update_seconds($r,$time_remaining);
 2158:     &update_status($r,'contacting '.$Servers_to_contact[0]);
 2159:     while (($time_remaining > 0) &&
 2160:            ((@Servers_to_contact) || keys(%Server_status))) {
 2161:         # Send out a search request if it needs to be done.
 2162:         if (@Servers_to_contact) {
 2163:             # Contact one server
 2164:             my $server = shift(@Servers_to_contact);
 2165:             my $reply=&Apache::lonnet::metadata_query($query,$customquery,
 2166:                                                       $customshow,[$server]);
 2167:             ($server) = keys(%$reply);
 2168:             $Server_status{$server} = $reply->{$server};
 2169:             &update_status($r,'contacting '.$server);
 2170:         } else {
 2171:             # wait a sec. to give time for files to be written
 2172:             # This sleep statement is here instead of outside the else 
 2173:             # block because we do not want to pause if we have servers
 2174:             # left to contact.  
 2175:             sleep(1); 
 2176:         }
 2177:         #
 2178:         if (scalar (keys(%Server_status))) {
 2179:             &update_status($r,'waiting on '.(join(' ',keys(%Server_status))));
 2180:         }
 2181:         #
 2182:         # Loop through the servers we have contacted but do not
 2183:         # have results from yet, looking for results.
 2184:         while (my ($server,$status) = each(%Server_status)) {
 2185:             last if ($connection->aborted());
 2186:             if ($status eq 'con_lost') {
 2187:                 delete ($Server_status{$server});
 2188:                 next;
 2189:             }
 2190:             $status=~/^([\.\w]+)$/; 
 2191:        	    my $datafile=$r->dir_config('lonDaemons').'/tmp/'.$1;
 2192:             if (-e $datafile && ! -e "$datafile.end") {
 2193:                 &update_status($r,'Receiving results from '.$server);
 2194:                 next;
 2195:             }
 2196:             last if ($connection->aborted());
 2197:             if (-e "$datafile.end") {
 2198:                 &update_status($r,'Reading results from '.$server);
 2199:                 if (-z "$datafile") {
 2200:                     delete($Server_status{$server});
 2201:                     next;
 2202:                 }
 2203:                 my $fh;
 2204:                 if (!($fh=Apache::File->new($datafile))) { 
 2205:                     $r->print("Unable to open search results file for ".
 2206:                                   "server $server.  Omitting from search");
 2207:                     delete($Server_status{$server}); 
 2208:                    next;
 2209:                 }
 2210:                 # Read in the whole file.
 2211:                 while (my $result = <$fh>) {
 2212:                     last if ($connection->aborted());
 2213:                     # handle custom fields?  Someday we will!
 2214:                     chomp($result);
 2215:                     next unless $result;
 2216:                     # Parse the result.
 2217:                     my %Fields = &parse_raw_result($result,$server);
 2218:                     $Fields{'hostname'} = $server;
 2219:                     next if (! &copyright_check(\%Fields));
 2220:                     # Store the result in the mysql database
 2221:                     my $result = &Apache::lonmysql::store_row($table,\%Fields);
 2222:                     if (! defined($result)) {
 2223:                         $r->print(&Apache::lonmysql::get_error());
 2224:                     }
 2225:                     # $r->print(&Apache::lonmysql::get_debug());
 2226:                     $hitcountsum ++;
 2227:                     $time_remaining = $max_time - (time - $starttime) ;
 2228:                     if ($last_time - $time_remaining > 0) {
 2229:                         &update_seconds($r,$time_remaining);
 2230:                         $last_time = $time_remaining;
 2231:                     }
 2232:                     if ($hitcountsum % 50 == 0) {
 2233:                         &update_count_status($r,$hitcountsum);
 2234:                     }
 2235:                 } # End of foreach (@results)
 2236:                 $fh->close();
 2237:                 # $server is only deleted if the results file has been 
 2238:                 # found and (successfully) opened.  This may be a bad idea.
 2239:                 delete($Server_status{$server});
 2240:             }
 2241:             last if ($connection->aborted());
 2242:             &update_count_status($r,$hitcountsum);
 2243:         }
 2244:         last if ($connection->aborted());
 2245:         # Finished looping through the servers
 2246:         $starttime = time if (@Servers_to_contact);
 2247:         $time_remaining = $max_time - (time - $starttime) ;
 2248:         if ($last_time - $time_remaining > 0) {
 2249:             $last_time = $time_remaining;
 2250:             &update_seconds($r,$time_remaining);
 2251:         }
 2252:     }
 2253:     &update_status($r,'Search Complete'.$server);
 2254:     &update_seconds($r,0);
 2255:     &Apache::lonmysql::disconnect_from_db();
 2256:     # We have run out of time or run out of servers to talk to and
 2257:     # results to get.  
 2258:     $r->print("</body></html>");
 2259:     if ($ENV{'form.catalogmode'} ne 'groupsearch') {
 2260:         $r->print("<script>".
 2261:                       "window.location='/adm/searchcat?".
 2262:                       "phase=sort&".
 2263:                       "persistent_db_id=$ENV{'form.persistent_db_id'}';".
 2264:                   "</script>");
 2265:     }
 2266:     return;
 2267: }
 2268: 
 2269: ######################################################################
 2270: ######################################################################
 2271: =pod
 2272: 
 2273: =item &prev_next_buttons
 2274: 
 2275: =cut
 2276: 
 2277: ######################################################################
 2278: ######################################################################
 2279: sub prev_next_buttons {
 2280:     my ($current_min,$show,$total,$parms) = @_;
 2281:     return '' if ($show eq 'all'); # No links if you get them all at once.
 2282:     my $links;
 2283:     ##
 2284:     ## Prev
 2285:     my $prev_min = $current_min - $show;
 2286:     $prev_min = 1 if $prev_min < 1;
 2287:     if ($prev_min < $current_min) {
 2288:         $links .= qq{
 2289: <a href="/adm/searchcat?$parms&start=$prev_min&show=$show">prev</a>
 2290: };    
 2291:     } else {
 2292:         $links .= 'prev';
 2293:     }
 2294:     ##
 2295:     ## Pages.... Someday.
 2296:     ##
 2297:     $links .= qq{ &nbsp;
 2298: <a href="/adm/searchcat?$parms&start=$current_min&$show=$show">reload</a>
 2299: };
 2300:     ##
 2301:     ## Next
 2302:     my $next_min = $current_min + $show;
 2303:     $next_min = $current_min if ($next_min > $total);
 2304:     if ($next_min != $current_min) {
 2305:         $links .= qq{ &nbsp;
 2306: <a href="/adm/searchcat?$parms&start=$next_min&show=$show">next</a>
 2307: };    
 2308:     } else {
 2309:         $links .= '&nbsp;next';
 2310:     }
 2311:     return $links;
 2312: }
 2313: ######################################################################
 2314: ######################################################################
 2315: 
 2316: =pod
 2317: 
 2318: =item &display_results
 2319: 
 2320: =cut
 2321: 
 2322: ######################################################################
 2323: ######################################################################
 2324: sub display_results {
 2325:     my ($r,$importbutton,$closebutton) = @_;
 2326:     my $connection = $r->connection;
 2327:     $r->print(&search_results_header($importbutton,$closebutton));
 2328:     ##
 2329:     ## Set viewing function
 2330:     ##
 2331:     my $viewfunction = $Views{$ENV{'form.viewselect'}};
 2332:     if (!defined($viewfunction)) {
 2333:         $r->print("Internal Error - Bad view selected.\n");
 2334:         $r->rflush();
 2335:         return;
 2336:     }
 2337:     ##
 2338:     ## $checkbox_num is a count of the number of checkboxes output on the 
 2339:     ## page this is used only during catalogmode=groupsearch.
 2340:     my $checkbox_num = 0;
 2341:     ##
 2342:     ## Get the catalog controls setup
 2343:     ##
 2344:     my $action = "/adm/searchcat?phase=results";
 2345:     ##
 2346:     ## Deal with groupsearch
 2347:     ##
 2348:     if ($ENV{'form.catalogmode'} eq 'groupsearch') {
 2349:         if (! tie(%groupsearch_db,'GDBM_File',$diropendb,
 2350:                   &GDBM_WRCREAT(),0640)) {
 2351:             $r->print('Unable to store import results.</form></body></html>');
 2352:             $r->rflush();
 2353:             return;
 2354:         } 
 2355:     }
 2356:     ##
 2357:     ## Prepare the table for querying
 2358:     ##
 2359:     my $table = $ENV{'form.table'};
 2360:     return if (! &ensure_db_and_table($r,$table));
 2361:     ##
 2362:     ## Get the number of results 
 2363:     ##
 2364:     my $total_results = &Apache::lonmysql::number_of_rows($table);
 2365:     if (! defined($total_results)) {
 2366:         $r->print("A MySQL error has occurred.</form></body></html>");
 2367:         &Apache::lonnet::logthis("lonmysql was unable to determine the number".
 2368:                                  " of rows in table ".$table);
 2369:         &Apache::lonnet::logthis(&Apache::lonmysql::get_error());
 2370:         return;
 2371:     }
 2372:     ##
 2373:     ## Determine how many results we need to get
 2374:     ##
 2375:     $ENV{'form.start'} = 1      if (! exists($ENV{'form.start'}));
 2376:     $ENV{'form.show'}  = 'all'  if (! exists($ENV{'form.show'}));
 2377:     my $min = $ENV{'form.start'};
 2378:     my $max;
 2379:     if ($ENV{'form.show'} eq 'all') {
 2380:         $max = $total_results ;
 2381:     } else {
 2382:         $max = $min + $ENV{'form.show'} - 1;
 2383:         $max = $total_results if ($max > $total_results);
 2384:     }
 2385:     ##
 2386:     ## Output links (if necessary) for 'prev' and 'next' pages.
 2387:     ##
 2388:     $r->print
 2389:         ('<center>'.
 2390:          &prev_next_buttons($min,$ENV{'form.show'},$total_results,
 2391:                             "table=".$ENV{'form.table'}.
 2392:                             "&phase=results".
 2393:                             "&persistent_db_id=".$ENV{'form.persistent_db_id'})
 2394:          ."</center>\n"
 2395:          );
 2396:     if ($total_results == 0) {
 2397:         $r->print("<h3>There are currently no results.</h3>Please try to reload this page, which will update the display.\n".
 2398:                   "</form></body></html>");
 2399:         return;
 2400:     } else {
 2401:         $r->print
 2402:             ("<center>Results $min to $max out of $total_results</center>\n");
 2403:     }
 2404:     ##
 2405:     ## Get results from MySQL table
 2406:     ##
 2407:     my @Results = &Apache::lonmysql::get_rows($table,
 2408:                                               'id>='.$min.' AND id<='.$max);
 2409:     ##
 2410:     ## Loop through the results and output them.
 2411:     ##
 2412:     foreach my $row (@Results) {
 2413:         if ($connection->aborted()) {
 2414:             &cleanup();
 2415:             return;
 2416:         }
 2417:         my %Fields = %{&parse_row(@$row)};
 2418:         my $output="<p>\n";
 2419:         my $prefix=&catalogmode_output($Fields{'title'},$Fields{'url'},
 2420:                                        $Fields{'id'},$checkbox_num++);
 2421:         # Render the result into html
 2422:         $output.= &$viewfunction($prefix,%Fields);
 2423:         # Print them out as they come in.
 2424:         $r->print($output);
 2425:         $r->rflush();
 2426:     }
 2427:     if (@Results < 1) {
 2428:         $r->print("There were no results matching your query");
 2429:     } else {
 2430:         $r->print
 2431:             ('<center>'.
 2432:              &prev_next_buttons($min,$ENV{'form.show'},$total_results,
 2433:                                 "table=".$ENV{'form.table'}.
 2434:                                 "&phase=results".
 2435:                                 "&persistent_db_id=".
 2436:                                 $ENV{'form.persistent_db_id'})
 2437:              ."</center>\n"
 2438:              );
 2439:     }
 2440:     $r->print("</form></body></html>");
 2441:     $r->rflush();
 2442:     untie %groupsearch_db if (tied(%groupsearch_db));
 2443:     return;
 2444: }
 2445: 
 2446: ######################################################################
 2447: ######################################################################
 2448: 
 2449: =pod
 2450: 
 2451: =item &catalogmode_output($title,$url,$fnum,$checkbox_num)
 2452: 
 2453: Returns html needed for the various catalog modes.  Gets inputs from
 2454: $ENV{'form.catalogmode'}.  Stores data in %groupsearch_db.
 2455: 
 2456: =cut
 2457: 
 2458: ######################################################################
 2459: ######################################################################
 2460: sub catalogmode_output {
 2461:     my $output = '';
 2462:     my ($title,$url,$fnum,$checkbox_num) = @_;
 2463:     if ($ENV{'form.catalogmode'} eq 'interactive') {
 2464:         $title=~ s/\'/\\\'/g;
 2465:         if ($ENV{'form.catalogmode'} eq 'interactive') {
 2466:             $output.=<<END 
 2467: <font size='-1'><INPUT TYPE="button" NAME="returnvalues" VALUE="SELECT"
 2468: onClick="javascript:select_data('$title','$url')">
 2469: </font>
 2470: END
 2471:         }
 2472:     } elsif ($ENV{'form.catalogmode'} eq 'groupsearch') {
 2473:         $groupsearch_db{"pre_${fnum}_link"}=$url;
 2474:         $groupsearch_db{"pre_${fnum}_title"}=$title;
 2475:         $output.=<<END;
 2476: <font size='-1'>
 2477: <input type="checkbox" name="returnvalues" value="SELECT"
 2478: onClick="javascript:queue($checkbox_num,$fnum)" />
 2479: </font>
 2480: END
 2481:     }
 2482:     return $output;
 2483: }
 2484: ######################################################################
 2485: ######################################################################
 2486: 
 2487: =pod
 2488: 
 2489: =item &parse_row
 2490: 
 2491: Parse a row returned from the database.
 2492: 
 2493: =cut
 2494: 
 2495: ######################################################################
 2496: ######################################################################
 2497: sub parse_row {
 2498:     my @Row = @_;
 2499:     my %Fields;
 2500:     for (my $i=0;$i<=$#Row;$i++) {
 2501:         $Fields{$Datatypes[$i]->{'name'}}=&Apache::lonnet::unescape($Row[$i]);
 2502:     }
 2503:     $Fields{'language'} = 
 2504:         &Apache::loncommon::languagedescription($Fields{'lang'});
 2505:     $Fields{'copyrighttag'} =
 2506:         &Apache::loncommon::copyrightdescription($Fields{'copyright'});
 2507:     $Fields{'mimetag'} =
 2508:         &Apache::loncommon::filedescription($Fields{'mime'});
 2509:     return \%Fields;
 2510: }
 2511: 
 2512: ###########################################################
 2513: ###########################################################
 2514: 
 2515: =pod
 2516: 
 2517: =item &parse_raw_result()
 2518: 
 2519: Takes a line from the file of results and parse it.  Returns a hash 
 2520: with keys for the following fields:
 2521: 'title', 'author', 'subject', 'url', 'keywords', 'version', 'notes', 
 2522: 'abstract', 'mime', 'lang', 'owner', 'copyright', 'creationdate', 
 2523: 'lastrevisiondate'.
 2524: 
 2525: In addition, the following tags are set by calling the appropriate 
 2526: lonnet function: 'language', 'cprtag', 'mimetag'.
 2527: 
 2528: The 'title' field is set to "Untitled" if the title field is blank.
 2529: 
 2530: 'abstract' and 'keywords' are truncated to 200 characters.
 2531: 
 2532: =cut
 2533: 
 2534: ###########################################################
 2535: ###########################################################
 2536: sub parse_raw_result {
 2537:     my ($result,$hostname) = @_;
 2538:     # Check for a comma - if it is there then we do not need to unescape the
 2539:     # string.  There seems to be some kind of problem with some items in
 2540:     # the database - the entire string gets sent out unescaped...?
 2541:     unless ($result =~ /,/) {
 2542:         $result = &Apache::lonnet::unescape($result);
 2543:     }
 2544:     my @fields=map {
 2545:         &Apache::lonnet::unescape($_);
 2546:     } (split(/\,/,$result));
 2547:     my ($title,$author,$subject,$url,$keywords,$version,
 2548:         $notes,$abstract,$mime,$lang,
 2549:         $creationdate,$lastrevisiondate,$owner,$copyright)=@fields;
 2550:     my %Fields = 
 2551:         ( title     => &Apache::lonnet::unescape($title),
 2552:           author    => &Apache::lonnet::unescape($author),
 2553:           subject   => &Apache::lonnet::unescape($subject),
 2554:           url       => &Apache::lonnet::unescape($url),
 2555:           keywords  => &Apache::lonnet::unescape($keywords),
 2556:           version   => &Apache::lonnet::unescape($version),
 2557:           notes     => &Apache::lonnet::unescape($notes),
 2558:           abstract  => &Apache::lonnet::unescape($abstract),
 2559:           mime      => &Apache::lonnet::unescape($mime),
 2560:           lang      => &Apache::lonnet::unescape($lang),
 2561:           owner     => &Apache::lonnet::unescape($owner),
 2562:           copyright => &Apache::lonnet::unescape($copyright),
 2563:           creationdate     => &Apache::lonnet::unescape($creationdate),
 2564:           lastrevisiondate => &Apache::lonnet::unescape($lastrevisiondate)
 2565:         );
 2566:     $Fields{'language'} = 
 2567:         &Apache::loncommon::languagedescription($Fields{'lang'});
 2568:     $Fields{'copyrighttag'} =
 2569:         &Apache::loncommon::copyrightdescription($Fields{'copyright'});
 2570:     $Fields{'mimetag'} =
 2571:         &Apache::loncommon::filedescription($Fields{'mime'});
 2572:     if ($Fields{'author'}=~/^(\s*|error)$/) {
 2573:         $Fields{'author'}="Unknown Author";
 2574:     }
 2575:     # Put spaces in the keyword list, if needed.
 2576:     $Fields{'keywords'}=~ s/,([A-z])/, $1/g; 
 2577:     if ($Fields{'title'}=~ /^\s*$/ ) { 
 2578:         $Fields{'title'}='Untitled'; 
 2579:     }
 2580:     unless ($ENV{'user.adv'}) {
 2581:         # What is this anyway?
 2582:         $Fields{'keywords'} = '- not displayed -';
 2583:         $Fields{'notes'}    = '- not displayed -';
 2584:         $Fields{'abstract'} = '- not displayed -';
 2585:         $Fields{'subject'}  = '- not displayed -';
 2586:     }
 2587:     if (length($Fields{'abstract'})>200) {
 2588:         $Fields{'abstract'} = 
 2589:             substr($Fields{'abstract'},0,200).'...';
 2590:     }
 2591:     if (length($Fields{'keywords'})>200) {
 2592:         $Fields{'keywords'} =
 2593:             substr($Fields{'keywords'},0,200).'...';
 2594:     }
 2595:     return %Fields;
 2596: }
 2597: 
 2598: ###########################################################
 2599: ###########################################################
 2600: 
 2601: =pod
 2602: 
 2603: =item &handle_custom_fields()
 2604: 
 2605: =cut
 2606: 
 2607: ###########################################################
 2608: ###########################################################
 2609: sub handle_custom_fields {
 2610:     my @results = @{shift()};
 2611:     my $customshow='';
 2612:     my $extrashow='';
 2613:     my @customfields;
 2614:     if ($ENV{'form.customshow'}) {
 2615:         $customshow=$ENV{'form.customshow'};
 2616:         $customshow=~s/[^\w\s]//g;
 2617:         my @fields=map {
 2618:             "<font color=\"#008000\">$_:</font><!-- $_ -->";
 2619:         } split(/\s+/,$customshow);
 2620:         @customfields=split(/\s+/,$customshow);
 2621:         if ($customshow) {
 2622:             $extrashow="<ul><li>".join("</li><li>",@fields)."</li></ul>\n";
 2623:         }
 2624:     }
 2625:     my $customdata='';
 2626:     my %customhash;
 2627:     foreach my $result (@results) {
 2628:         if ($result=~/^(custom\=.*)$/) { # grab all custom metadata
 2629:             my $tmp=$result;
 2630:             $tmp=~s/^custom\=//;
 2631:             my ($k,$v)=map {&Apache::lonnet::unescape($_);
 2632:                         } split(/\,/,$tmp);
 2633:             $customhash{$k}=$v;
 2634:         }
 2635:     }
 2636:     return ($extrashow,\@customfields,\%customhash);
 2637: }
 2638: 
 2639: ######################################################################
 2640: ######################################################################
 2641: 
 2642: =pod
 2643: 
 2644: =item &search_results_header
 2645: 
 2646: Output the proper html headers and javascript code to deal with different 
 2647: calling modes.
 2648: 
 2649: Takes most inputs directly from %ENV, except $mode.  
 2650: 
 2651: =over 4
 2652: 
 2653: =item $mode is either (at this writing) 'Basic' or 'Advanced'
 2654: 
 2655: =back
 2656: 
 2657: The following environment variables are checked:
 2658: 
 2659: =over 4
 2660: 
 2661: =item 'form.catalogmode' 
 2662: 
 2663: Checked for 'interactive' and 'groupsearch'.
 2664: 
 2665: =item 'form.mode'
 2666: 
 2667: Checked for existance & 'edit' mode.
 2668: 
 2669: =item 'form.form'
 2670: 
 2671: =item 'form.element'
 2672: 
 2673: =back
 2674: 
 2675: =cut
 2676: 
 2677: ######################################################################
 2678: ######################################################################
 2679: sub search_results_header {
 2680:     my ($importbutton,$closebutton) = @_;
 2681:     my $result = '';
 2682:     # output beginning of search page
 2683:     # conditional output of script functions dependent on the mode in
 2684:     # which the search was invoked
 2685:     if ($ENV{'form.catalogmode'} eq 'interactive'){
 2686: 	if (! exists($ENV{'form.mode'}) || $ENV{'form.mode'} ne 'edit') {
 2687:             $result.=<<SCRIPT;
 2688: <script type="text/javascript">
 2689:     function select_data(title,url) {
 2690: 	changeTitle(title);
 2691: 	changeURL(url);
 2692: 	parent.close();
 2693:     }
 2694:     function changeTitle(val) {
 2695: 	if (parent.opener.inf.document.forms.resinfo.elements.t) {
 2696: 	    parent.opener.inf.document.forms.resinfo.elements.t.value=val;
 2697: 	}
 2698:     }
 2699:     function changeURL(val) {
 2700: 	if (parent.opener.inf.document.forms.resinfo.elements.u) {
 2701: 	    parent.opener.inf.document.forms.resinfo.elements.u.value=val;
 2702: 	}
 2703:     }
 2704: </script>
 2705: SCRIPT
 2706:         } elsif ($ENV{'form.mode'} eq 'edit') {
 2707:             my $form = $ENV{'form.form'};
 2708:             my $element = $ENV{'form.element'};
 2709:             $result.=<<SCRIPT;
 2710: <script type="text/javascript">
 2711: function select_data(title,url) {
 2712:     changeURL(url);
 2713:     parent.close();
 2714: }
 2715: function changeTitle(val) {
 2716: }
 2717: function changeURL(val) {
 2718:     if (parent.targetwin.document) {
 2719:         parent.targetwin.document.forms["$form"].elements["$element"].value=val;
 2720:     } else {
 2721: 	var url = 'forms[\"$form\"].elements[\"$element\"].value';
 2722:         alert("Unable to transfer data to "+url);
 2723:     }
 2724: }
 2725: </script>
 2726: SCRIPT
 2727:         }
 2728:     }
 2729:     $result.=<<SCRIPT if $ENV{'form.catalogmode'} eq 'groupsearch';
 2730: <script type="text/javascript">
 2731:     function queue(checkbox_num,val) {
 2732:         if (document.forms.results.returnvalues[checkbox_num].checked) {
 2733:             parent.statusframe.document.forms.statusform.elements.Queue.value +='1a'+val+'b';
 2734:         } else {
 2735:             parent.statusframe.document.forms.statusform.elements.Queue.value +='0a'+val+'b';
 2736:         }
 2737:     }
 2738:     function select_group() {
 2739: 	parent.window.location=
 2740:     "/adm/groupsort?mode=$ENV{'form.mode'}&catalogmode=groupsearch&acts="+
 2741: 	    parent.statusframe.document.forms.statusform.elements.Queue.value;
 2742:     }
 2743: </script>
 2744: SCRIPT
 2745:     $result.=<<END;
 2746: </head>
 2747: $bodytag
 2748: <form name="results" method="post" action="" >
 2749: <input type="hidden" name="Queue" value="" />
 2750: $importbutton
 2751: END
 2752:     return $result;
 2753: }
 2754: 
 2755: ######################################################################
 2756: ######################################################################
 2757: sub search_status_header {
 2758:     return <<ENDSTATUS;
 2759: <html><head><title>Search Status</title></head>
 2760: $bodytag
 2761: <h3>Search Status</h3>
 2762: Sending search request to LON-CAPA servers.<br />
 2763: ENDSTATUS
 2764: }
 2765: 
 2766: sub results_link {
 2767:     my $basic_link   = "/adm/searchcat?"."&table=".$ENV{'form.table'}.
 2768:         "&persistent_db_id=".$ENV{'form.persistent_db_id'};
 2769:     my $results_link = $basic_link."&phase=results".
 2770:         "&pause=1"."&start=1";
 2771:     return $results_link;
 2772: }
 2773: 
 2774: ######################################################################
 2775: ######################################################################
 2776: sub print_frames_interface {
 2777:     my $r = shift;
 2778:     my $basic_link = "/adm/searchcat?"."&table=".$ENV{'form.table'}.
 2779:         "&persistent_db_id=".$ENV{'form.persistent_db_id'};
 2780:     my $run_search_link = $basic_link."&phase=run_search";
 2781:     my $results_link = &results_link();
 2782:     my $result = <<"ENDFRAMES";
 2783: <html>
 2784: <head>
 2785: <script>
 2786: var targetwin = opener;
 2787: var queue = '';
 2788: </script>
 2789: <title>LON-CAPA Digital Library Search Results</title>
 2790: </head>
 2791: <frameset rows="150,*">
 2792:     <frame name="statusframe"  src="$run_search_link">
 2793:     <frame name="resultsframe" src="$results_link">
 2794: </frameset>
 2795: </html>
 2796: ENDFRAMES
 2797: 
 2798:     $r->print($result);
 2799:     return;
 2800: }
 2801: 
 2802: ######################################################################
 2803: ######################################################################
 2804: 
 2805: =pod 
 2806: 
 2807: =item Metadata Viewing Functions
 2808: 
 2809: Output is a HTML-ified string.
 2810: Input arguments are title, author, subject, url, keywords, version,
 2811: notes, short abstract, mime, language, creation date,
 2812: last revision date, owner, copyright, hostname, and
 2813: extra custom metadata to show.
 2814: 
 2815: =over 4
 2816: 
 2817: =item &detailed_citation_view() 
 2818: 
 2819: =cut
 2820: 
 2821: ######################################################################
 2822: ######################################################################
 2823: sub detailed_citation_view {
 2824:     my ($prefix,%values) = @_;
 2825:     my $result=<<END;
 2826: <b>$prefix<a href="http://$ENV{'HTTP_HOST'}$values{'url'}" 
 2827:     target='search_preview'>$values{'title'}</a></b>
 2828: <p>
 2829: <b>$values{'author'}</b>, <i>$values{'owner'}</i><br />
 2830: 
 2831: <b>Subject:       </b> $values{'subject'}<br />
 2832: <b>Keyword(s):    </b> $values{'keywords'}<br />
 2833: <b>Notes:         </b> $values{'notes'}<br />
 2834: <b>MIME Type:     </b> $values{'mimetag'}<br />
 2835: <b>Language:      </b> $values{'language'}<br />
 2836: <b>Copyright/Distribution:</b> $values{'cprtag'}<br />
 2837: </p>
 2838: $values{'extrashow'}
 2839: <p>
 2840: $values{'shortabstract'}
 2841: </p>
 2842: <hr align='left' width='200' noshade />
 2843: END
 2844:     return $result;
 2845: }
 2846: 
 2847: ######################################################################
 2848: ######################################################################
 2849: 
 2850: =pod 
 2851: 
 2852: =item &summary_view() 
 2853: 
 2854: =cut
 2855: ######################################################################
 2856: ######################################################################
 2857: sub summary_view {
 2858:     my ($prefix,%values) = @_;
 2859:     my $result=<<END;
 2860: $prefix<a href="http://$ENV{'HTTP_HOST'}$values{'url'}" 
 2861:    target='search_preview'>$values{'author'}</a><br />
 2862: $values{'title'}<br />
 2863: $values{'owner'} -- $values{'lastrevisiondate'}<br />
 2864: $values{'copyrighttag'}<br />
 2865: $values{'extrashow'}
 2866: </p>
 2867: <hr align='left' width='200' noshade />
 2868: END
 2869:     return $result;
 2870: }
 2871: 
 2872: ######################################################################
 2873: ######################################################################
 2874: 
 2875: =pod 
 2876: 
 2877: =item &compact_view() 
 2878: 
 2879: =cut
 2880: 
 2881: ######################################################################
 2882: ######################################################################
 2883: sub compact_view {
 2884:     my ($prefix,%values) = @_;
 2885:     my $result=<<END;
 2886: $prefix <a href="http://$ENV{'HTTP_HOST'}$values{'url'}"  target='search_preview'>
 2887: $values{'title'}</a>
 2888: <b>$values{'author'}</b><br />
 2889: END
 2890:     return $result;
 2891: }
 2892: 
 2893: 
 2894: ######################################################################
 2895: ######################################################################
 2896: 
 2897: =pod 
 2898: 
 2899: =item &fielded_format_view() 
 2900: 
 2901: =cut
 2902: 
 2903: ######################################################################
 2904: ######################################################################
 2905: sub fielded_format_view {
 2906:     my ($prefix,%values) = @_;
 2907:     my $result=<<END;
 2908: $prefix
 2909: <b>URL: </b> <a href="http://$ENV{'HTTP_HOST'}$values{'url'}" 
 2910:               target='search_preview'>$values{'url'}</a>
 2911: <br />
 2912: <b>Title:</b> $values{'title'}<br />
 2913: <b>Author(s):</b> $values{'author'}<br />
 2914: <b>Subject:</b> $values{'subject'}<br />
 2915: <b>Keyword(s):</b> $values{'keywords'}<br />
 2916: <b>Notes:</b> $values{'notes'}<br />
 2917: <b>MIME Type:</b> $values{'mimetag'}<br />
 2918: <b>Language:</b> $values{'language'}<br />
 2919: <b>Creation Date:</b> $values{'creationdate'}<br />
 2920: <b>Last Revision Date:</b> $values{'lastrevisiondate'}<br />
 2921: <b>Publisher/Owner:</b> $values{'owner'}<br />
 2922: <b>Copyright/Distribution:</b> $values{'copyrighttag'}<br />
 2923: <b>Repository Location:</b> $values{'hostname'}<br />
 2924: <b>Abstract:</b> $values{'shortabstract'}<br />
 2925: $values{'extrashow'}
 2926: </p>
 2927: <hr align='left' width='200' noshade />
 2928: END
 2929:     return $result;
 2930: }
 2931: 
 2932: ######################################################################
 2933: ######################################################################
 2934: 
 2935: =pod 
 2936: 
 2937: =item &xml_sgml_view() 
 2938: 
 2939: =back 
 2940: 
 2941: =cut
 2942: 
 2943: ######################################################################
 2944: ######################################################################
 2945: sub xml_sgml_view {
 2946:     my ($prefix,%values) = @_;
 2947:     my $result=<<END;
 2948: $prefix
 2949: <pre>
 2950: &lt;LonCapaResource&gt;
 2951: &lt;url&gt;$values{'url'}&lt;/url&gt;
 2952: &lt;title&gt;$values{'title'}&lt;/title&gt;
 2953: &lt;author&gt;$values{'author'}&lt;/author&gt;
 2954: &lt;subject&gt;$values{'subject'}&lt;/subject&gt;
 2955: &lt;keywords&gt;$values{'keywords'}&lt;/keywords&gt;
 2956: &lt;notes&gt;$values{'notes'}&lt;/notes&gt;
 2957: &lt;mimeInfo&gt;
 2958: &lt;mime&gt;$values{'mime'}&lt;/mime&gt;
 2959: &lt;mimetag&gt;$values{'mimetag'}&lt;/mimetag&gt;
 2960: &lt;/mimeInfo&gt;
 2961: &lt;languageInfo&gt;
 2962: &lt;language&gt;$values{'lang'}&lt;/language&gt;
 2963: &lt;languagetag&gt;$values{'language'}&lt;/languagetag&gt;
 2964: &lt;/languageInfo&gt;
 2965: &lt;creationdate&gt;$values{'creationdate'}&lt;/creationdate&gt;
 2966: &lt;lastrevisiondate&gt;$values{'lastrevisiondate'}&lt;/lastrevisiondate&gt;
 2967: &lt;owner&gt;$values{'owner'}&lt;/owner&gt;
 2968: &lt;copyrightInfo&gt;
 2969: &lt;copyright&gt;$values{'copyright'}&lt;/copyright&gt;
 2970: &lt;copyrighttag&gt;$values{'copyrighttag'}&lt;/copyrighttag&gt;
 2971: &lt;/copyrightInfo&gt;
 2972: &lt;repositoryLocation&gt;$values{'hostname'}&lt;/repositoryLocation&gt;
 2973: &lt;shortabstract&gt;$values{'shortabstract'}&lt;/shortabstract&gt;
 2974: &lt;/LonCapaResource&gt;
 2975: </pre>
 2976: $values{'extrashow'}
 2977: <hr align='left' width='200' noshade />
 2978: END
 2979:     return $result;
 2980: }
 2981: 
 2982: ######################################################################
 2983: ######################################################################
 2984: 
 2985: =pod 
 2986: 
 2987: =item &filled() see if field is filled.
 2988: 
 2989: =cut
 2990: 
 2991: ######################################################################
 2992: ######################################################################
 2993: sub filled {
 2994:     my ($field)=@_;
 2995:     if ($field=~/\S/ && $field ne 'any') {
 2996: 	return 1;
 2997:     }
 2998:     else {
 2999: 	return 0;
 3000:     }
 3001: }
 3002: 
 3003: ######################################################################
 3004: ######################################################################
 3005: 
 3006: =pod 
 3007: 
 3008: =item &output_blank_field_error()
 3009: 
 3010: Output a complete page that indicates the user has not filled in enough
 3011: information to do a search.
 3012: 
 3013: Inputs: $r (Apache request handle), $closebutton, $parms.
 3014: 
 3015: Returns: nothing
 3016: 
 3017: $parms is extra information to include in the 'Revise search request' link.
 3018: 
 3019: =cut
 3020: 
 3021: ######################################################################
 3022: ######################################################################
 3023: sub output_blank_field_error {
 3024:     my ($r,$closebutton,$parms)=@_;
 3025:     # make query information persistent to allow for subsequent revision
 3026:     $r->print(<<BEGINNING);
 3027: <html>
 3028: <head>
 3029: <title>The LearningOnline Network with CAPA</title>
 3030: BEGINNING
 3031:     $r->print(<<RESULTS);
 3032: </head>
 3033: $bodytag
 3034: <img align='right' src='/adm/lonIcons/lonlogos.gif' />
 3035: <h1>Search Catalog</h1>
 3036: <form method="post" action="/adm/searchcat">
 3037: $hidden_fields
 3038: <a href="/adm/searchcat?$parms&persistent_db_id=$ENV{'form.persistent_db_id'}"
 3039: >Revise search request</a>&nbsp;
 3040: $closebutton
 3041: <hr />
 3042: <h3>Unactionable search query.</h3>
 3043: <p>
 3044: You did not fill in enough information for the search to be started.
 3045: You need to fill in relevant fields on the search page in order 
 3046: for a query to be processed.
 3047: </p>
 3048: </body>
 3049: </html>
 3050: RESULTS
 3051: }
 3052: 
 3053: ######################################################################
 3054: ######################################################################
 3055: 
 3056: =pod 
 3057: 
 3058: =item &output_date_error()
 3059: 
 3060: Output a full html page with an error message.
 3061: 
 3062: Inputs: 
 3063: 
 3064:     $r, the request pointer.
 3065:     $message, the error message for the user.
 3066:     $closebutton, the specialized close button needed for groupsearch.
 3067: 
 3068: =cut
 3069: 
 3070: ######################################################################
 3071: ######################################################################
 3072: sub output_date_error {
 3073:     my ($r,$message,$closebutton)=@_;
 3074:     # make query information persistent to allow for subsequent revision
 3075:     $r->print(<<RESULTS);
 3076: <html>
 3077: <head>
 3078: <title>The LearningOnline Network with CAPA</title>
 3079: </head>
 3080: $bodytag
 3081: <img align='right' src='/adm/lonIcons/lonlogos.gif' />
 3082: <h1>Search Catalog</h1>
 3083: <form method="post" action="/adm/searchcat">
 3084: $hidden_fields
 3085: <input type='button' value='Revise search request'
 3086: onClick='this.form.submit();' />
 3087: $closebutton
 3088: <hr />
 3089: <h3>Error</h3>
 3090: <p>
 3091: $message
 3092: </p>
 3093: </body>
 3094: </html>
 3095: RESULTS
 3096: }
 3097: 
 3098: ######################################################################
 3099: ######################################################################
 3100: 
 3101: =pod 
 3102: 
 3103: =item &start_fresh_session()
 3104: 
 3105: Cleans the global %groupsearch_db by removing all fields which begin with
 3106: 'pre_' or 'store'.
 3107: 
 3108: =cut
 3109: 
 3110: ######################################################################
 3111: ######################################################################
 3112: sub start_fresh_session {
 3113:     delete $groupsearch_db{'mode_catalog'};
 3114:     foreach (keys %groupsearch_db) {
 3115:         if ($_ =~ /^pre_/) {
 3116:             delete $groupsearch_db{$_};
 3117:         }
 3118:         if ($_ =~ /^store/) {
 3119: 	    delete $groupsearch_db{$_};
 3120: 	}
 3121:     }
 3122: }
 3123: 
 3124: 1;
 3125: 
 3126: sub cleanup {
 3127:     if (tied(%groupsearch_db)) {
 3128: 	&Apache::lonnet::logthis('Cleanup searchcat: groupsearch_db');
 3129:         unless (untie(%groupsearch_db)) {
 3130: 	  &Apache::lonnet::logthis('Failed cleanup searchcat: groupsearch_db');
 3131:         }
 3132:     }
 3133:     &untiehash();
 3134:     &Apache::lonmysql::disconnect_from_db();
 3135: }
 3136: 
 3137: __END__
 3138: 
 3139: =pod
 3140: 
 3141: =back 
 3142: 
 3143: =cut

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