File:  [LON-CAPA] / loncom / interface / lonsearchcat.pm
Revision 1.185: download - view: text, annotated - select for diffs
Mon Jul 14 19:26:24 2003 UTC (20 years, 10 months ago) by matthew
Branches: MAIN
CVS tags: version_1_0_2, version_1_0_1, version_1_0_0, version_0_99_5, version_0_99_4, HEAD
Bug 1752: import fails with only one resource.  Updated javascript to detect
the case of a non-array of the form element "returnvalues".

    1: # The LearningOnline Network with CAPA
    2: # Search Catalog
    3: #
    4: # $Id: lonsearchcat.pm,v 1.185 2003/07/14 19:26:24 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(1);
  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);
  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:         # Kludgification begins!
  856:         if ($name eq 'form.domains' && 
  857:             $ENV{'form.searchmode'} eq 'basic' &&
  858:             $ENV{'form.phase'} ne 'disp_basic') {
  859:             next;
  860:         }
  861:         # End kludge (hopefully)
  862:         next if (exists($ENV{$name}));
  863:         my @values = map { 
  864:             &Apache::lonnet::unescape($_);
  865:         } split(',',$persistent_db{$name});
  866:         next if (@values <1);
  867:         if ($arrays_allowed{$name}) {
  868:             $ENV{$name} = [@values];
  869:         } else {
  870:             $ENV{$name} = $values[0] if ($values[0]);
  871:         }
  872:     }
  873:     untie (%persistent_db);
  874:     return 1;
  875: }
  876: 
  877: ######################################################################
  878: ######################################################################
  879: 
  880: =pod 
  881: 
  882: =item &get_persistent_data
  883: 
  884: Inputs: filename of database, ref to array of values to recover.
  885: 
  886: Outputs: array of values.  Returns undef on error.
  887: 
  888: This function is the reverse of &make_persistent();
  889: Retrieve persistent data from %persistent_db.  Retrieved items will have their
  890: values unescaped.  If the item contains commas (before unescaping), the
  891: returned value will be an array pointer. 
  892: 
  893: =cut
  894: 
  895: ######################################################################
  896: ######################################################################
  897: sub get_persistent_data {
  898:     my $filename = shift;
  899:     my @Vars = @{shift()};
  900:     my @Values;   # Return array
  901:     return undef if (! -e $filename);
  902:     return undef if (! tie(%persistent_db,'GDBM_File',$filename,
  903:                            &GDBM_READER(),0640));
  904:     foreach my $name (@Vars) {
  905:         if (! exists($persistent_db{$name})) {
  906:             push @Values, undef;
  907:             next;
  908:         }
  909:         my @values = map { 
  910:             &Apache::lonnet::unescape($_);
  911:         } split(',',$persistent_db{$name});
  912:         if (@values <= 1) {
  913:             push @Values,$values[0];
  914:         } else {
  915:             push @Values,\@values;
  916:         }
  917:     }
  918:     untie (%persistent_db);
  919:     return @Values;
  920: }
  921: 
  922: ######################################################################
  923: ######################################################################
  924: 
  925: =pod 
  926: 
  927: =item &make_persistent() 
  928: 
  929: Inputs: Hash of values to save, filename of persistent database.
  930: 
  931: Store variables away to the %persistent_db.
  932: Values will be escaped.  Values that are array pointers will have their
  933: elements escaped and concatenated in a comma seperated string.  
  934: 
  935: =cut
  936: 
  937: ######################################################################
  938: ######################################################################
  939: sub make_persistent {
  940:     my %save = %{shift()};
  941:     my $filename = shift;
  942:     return undef if (! tie(%persistent_db,'GDBM_File',
  943:                            $filename,&GDBM_WRCREAT(),0640));
  944:     foreach my $name (keys(%save)) {
  945:         my @values = (ref($save{$name}) ? @{$save{$name}} : ($save{$name}));
  946:         # We handle array references, but not recursively.
  947:         my $store = join(',', map { &Apache::lonnet::escape($_); } @values );
  948:         $persistent_db{$name} = $store;
  949:     }
  950:     untie(%persistent_db);
  951:     return 1;
  952: }
  953: 
  954: ######################################################################
  955: ######################################################################
  956: 
  957: =pod 
  958: 
  959: =item &make_form_data_persistent() 
  960: 
  961: Inputs: filename of persistent database.
  962: 
  963: Store most form variables away to the %persistent_db.
  964: Values will be escaped.  Values that are array pointers will have their
  965: elements escaped and concatenated in a comma seperated string.  
  966: 
  967: =cut
  968: 
  969: ######################################################################
  970: ######################################################################
  971: sub make_form_data_persistent {
  972:     my $r = shift;
  973:     my $filename = shift;
  974:     my %save;
  975:     foreach (keys(%ENV)) {
  976:         next if (!/^form/ || /submit/);
  977:         $save{$_} = $ENV{$_};
  978:     }
  979:     return &make_persistent(\%save,$filename);
  980: }
  981: 
  982: ######################################################################
  983: #                HTML form building functions                        #  
  984: ######################################################################
  985: 
  986: =pod 
  987: 
  988: =item HTML form building functions
  989: 
  990: =over 4
  991: 
  992: =cut
  993: 
  994: ###############################################
  995: ###############################################
  996: 
  997: =pod
  998: 
  999: =item &simpletextfield() 
 1000: 
 1001: Inputs: $name,$value,$size
 1002: 
 1003: Returns a text input field with the given name, value, and size.  
 1004: If size is not specified, a value of 20 is used.
 1005: 
 1006: =cut
 1007: 
 1008: ###############################################
 1009: ###############################################
 1010: 
 1011: sub simpletextfield {
 1012:     my ($name,$value,$size)=@_;
 1013:     $size = 20 if (! defined($size));
 1014:     return '<input type="text" name="'.$name.
 1015:         '" size="'.$size.'" value="'.$value.'" />';
 1016: }
 1017: 
 1018: ###############################################
 1019: ###############################################
 1020: 
 1021: =pod
 1022: 
 1023: =item &simplecheckbox()
 1024: 
 1025: Inputs: $name,$value
 1026: 
 1027: Returns a simple check box with the given $name.
 1028: If $value eq 'on' the box is checked.
 1029: 
 1030: =cut
 1031: 
 1032: ###############################################
 1033: ###############################################
 1034: 
 1035: sub simplecheckbox{
 1036:     my ($name,$value,$checked)=@_;
 1037:     $checked="checked" if ($value eq 'on');
 1038:     return '<input type="checkbox" name="'.$name.'" value="'.$value.'" '.
 1039:         $checked.' />';
 1040: }
 1041: 
 1042: ###############################################
 1043: ###############################################
 1044: 
 1045: =pod
 1046: 
 1047: =item &fieldtitle()
 1048: 
 1049: Input: $title
 1050: 
 1051: Returns a scalar with html which will display $title as a search
 1052: field heading.
 1053: 
 1054: =cut
 1055: 
 1056: ###############################################
 1057: ###############################################
 1058: 
 1059: sub fieldtitle {
 1060:     my $title = uc(shift());
 1061:     return '<font color="#800000" face="helvetica"><b>'.$title.
 1062:         ':&nbsp;</b></font>';
 1063: }
 1064: 
 1065: ###############################################
 1066: ###############################################
 1067: 
 1068: =pod
 1069: 
 1070: =item &searchphrasefield()
 1071: 
 1072: Inputs: $title,$name,$value
 1073: 
 1074: Returns html for a title line and an input field for entering search terms.
 1075: The entry field (which is where the $name and $value are used) is a 50 column 
 1076: simpletextfield.  The html returned is for a row in a three column table.
 1077: 
 1078: =cut
 1079: 
 1080: ###############################################
 1081: ###############################################
 1082:     
 1083: sub searchphrasefield {
 1084:     my ($title,$name,$value)=@_;
 1085:     return '<tr><td>'.&fieldtitle($title).'</td><td>'.
 1086:         &simpletextfield($name,$value,50)."</td><td>&nbsp;</td></tr>\n";
 1087: }
 1088: 
 1089: ###############################################
 1090: ###############################################
 1091: 
 1092: =pod
 1093: 
 1094: =item &searchphrasefield_with_related()
 1095: 
 1096: Inputs: $title,$name,$value
 1097: 
 1098: Returns html for a title line and an input field for entering search terms
 1099: and a check box for 'related words'.  The entry field (which is where the 
 1100: $name and $value are used) is a 50 column simpletextfield.  The name of
 1101: the related words checkbox is "$name_related".
 1102: 
 1103: =cut
 1104: 
 1105: ###############################################
 1106: ###############################################
 1107:     
 1108: sub searchphrasefield_with_related {
 1109:     my ($title,$name,$value)=@_;
 1110:     return '<tr><td>'.&fieldtitle($title).'</td><td>'.
 1111:         &simpletextfield($name,$value,50).'</td><td align="center">&nbsp;'.
 1112:             &simplecheckbox($name.'_related',$ENV{'form.'.$name.'_related'}).
 1113:                 "&nbsp;</td></tr>\n";
 1114: }
 1115: 
 1116: ###############################################
 1117: ###############################################
 1118: 
 1119: =pod
 1120: 
 1121: =item &dateboxes()
 1122: 
 1123: Returns html selection form elements for the specification of 
 1124: the day, month, and year.
 1125: 
 1126: =cut
 1127: 
 1128: ###############################################
 1129: ###############################################
 1130: 
 1131: sub dateboxes {
 1132:     my ($name,$defaultmonth,$defaultday,$defaultyear,
 1133: 	$currentmonth,$currentday,$currentyear)=@_;
 1134:     ($defaultmonth,$defaultday,$defaultyear)=('','','');
 1135:     #
 1136:     # Day
 1137:     my $day=<<END;
 1138: <select name="${name}_day">
 1139: <option value='$defaultday'> </option>
 1140: END
 1141:     for (my $i = 1; $i<=31; $i++) {
 1142: 	$day.="<option value=\"$i\">$i</option>\n";
 1143:     }
 1144:     $day.="</select>\n";
 1145:     $day=~s/(\"$currentday\")/$1 SELECTED/ if length($currentday);
 1146:     #
 1147:     # Month
 1148:     my $month=<<END;
 1149: <select name="${name}_month">
 1150: <option value='$defaultmonth'> </option>
 1151: END
 1152:     my $i = 1;
 1153:     foreach (qw/January February March April May June 
 1154: 	     July August September October November December /){
 1155: 	$month .="<option value=\"$i\">$_</option>\n";
 1156: 	$i++;
 1157:     }
 1158:     $month.="</select>\n";
 1159:     $month=~s/(\"$currentmonth\")/$1 SELECTED/ if length($currentmonth);
 1160:     #
 1161:     # Year (obviously)
 1162:     my $year=<<END;
 1163: <select name="${name}_year">
 1164: <option value='$defaultyear'> </option>
 1165: END
 1166:     my $maxyear = 2051; 
 1167:     for (my $i = 1976; $i<=$maxyear; $i++) {
 1168: 	$year.="<option value=\"$i\">$i</option>\n";
 1169:     }
 1170:     $year.="</select>\n";
 1171:     $year=~s/(\"$currentyear\")/$1 SELECTED/ if length($currentyear);
 1172:     return "$month$day$year";
 1173: }
 1174: 
 1175: ###############################################
 1176: ###############################################
 1177: 
 1178: =pod
 1179: 
 1180: =item &selectbox()
 1181: 
 1182: Returns a scalar containing an html <select> form.  
 1183: 
 1184: Inputs: 
 1185: 
 1186: =over 4
 1187: 
 1188: =item $title 
 1189: 
 1190: Printed above the select box, in uppercase.  If undefined, only a select
 1191: box will be returned, with no additional html.
 1192: 
 1193: =item $name 
 1194: 
 1195: The name element of the <select> tag.
 1196: 
 1197: =item $default 
 1198: 
 1199: The default value of the form.  Can be $anyvalue, or in @idlist.
 1200: 
 1201: =item $anyvalue 
 1202: 
 1203: The <option value="..."> used to indicate a default of 
 1204: none of the values.  Can be undef.
 1205: 
 1206: =item $anytag 
 1207: 
 1208: The text associate with $anyvalue above.
 1209: 
 1210: =item $functionref 
 1211: 
 1212: Each element in @idlist will be passed as a parameter 
 1213: to the function referenced here.  The return value of the function should
 1214: be a scalar description of the items.  If this value is undefined the 
 1215: description of each item in @idlist will be the item name.
 1216: 
 1217: =item @idlist 
 1218: 
 1219: The items to be selected from.  One of these or $anyvalue will be the 
 1220: value returned by the form element, $ENV{form.$name}.
 1221: 
 1222: =back
 1223: 
 1224: =cut
 1225: 
 1226: ###############################################
 1227: 
 1228: sub selectbox {
 1229:     my ($title,$name,$default,$anyvalue,$anytag,$functionref,@idlist)=@_;
 1230:     if (! defined($functionref)) { $functionref = sub { $_[0]}; }
 1231:     my $selout='';
 1232:     if (defined($title)) {
 1233:         my $uctitle=uc($title);
 1234:         $selout="\n".'<p><font color="#800000" face="helvetica">'.
 1235:             '<b>'.$uctitle.': </b></font>';
 1236:     }
 1237:     $selout .= '<select name="'.$name.'">';
 1238:     unshift @idlist,$anyvalue if (defined($anyvalue));
 1239:     foreach (@idlist) {
 1240:         $selout.='<option value="'.$_.'"';
 1241:         if ($_ eq $default and !/^any$/) {
 1242: 	    $selout.=' selected >'.&{$functionref}($_).'</option>';
 1243: 	}
 1244: 	elsif ($_ eq $default and /^$anyvalue$/) {
 1245: 	    $selout.=' selected >'.$anytag.'</option>';
 1246: 	}
 1247:         else {$selout.='>'.&{$functionref}($_).'</option>';}
 1248:     }
 1249:     return $selout.'</select>'.(defined($title)?'</p>':' ');
 1250: }
 1251: 
 1252: ######################################################################
 1253: #                End of HTML form building functions                 #  
 1254: ######################################################################
 1255: 
 1256: =pod
 1257: 
 1258: =back 
 1259: 
 1260: =cut
 1261: 
 1262: 
 1263: ######################################################################
 1264: ######################################################################
 1265: 
 1266: =pod 
 1267: 
 1268: =item &parse_advanced_search()
 1269: 
 1270: Parse advanced search form and return the following:
 1271: 
 1272: =over 4
 1273: 
 1274: =item $query Scalar containing an SQL query.
 1275: 
 1276: =item $customquery Scalar containing a custom query.
 1277: 
 1278: =item $customshow Scalar containing commands to show custom metadata.
 1279: 
 1280: =item $libraries_to_query Reference to array of domains to search.
 1281: 
 1282: =back
 1283: 
 1284: =cut
 1285: 
 1286: ######################################################################
 1287: ######################################################################
 1288: sub parse_advanced_search {
 1289:     my ($r,$closebutton)=@_;
 1290:     my $fillflag=0;
 1291:     my $pretty_search_string = "<br />\n";
 1292:     # Clean up fields for safety
 1293:     for my $field ('title','author','subject','keywords','url','version',
 1294: 		   'creationdatestart_month','creationdatestart_day',
 1295: 		   'creationdatestart_year','creationdateend_month',
 1296: 		   'creationdateend_day','creationdateend_year',
 1297: 		   'lastrevisiondatestart_month','lastrevisiondatestart_day',
 1298: 		   'lastrevisiondatestart_year','lastrevisiondateend_month',
 1299: 		   'lastrevisiondateend_day','lastrevisiondateend_year',
 1300: 		   'notes','abstract','extension','language','owner',
 1301: 		   'custommetadata','customshow','category') {
 1302: 	$ENV{"form.$field"}=~s/[^\w\/\s\(\)\=\-\"\']//g;
 1303:     }
 1304:     foreach ('mode','form','element') {
 1305: 	# is this required?  Hmmm.
 1306: 	next unless (exists($ENV{"form.$_"}));
 1307: 	$ENV{"form.$_"}=&Apache::lonnet::unescape($ENV{"form.$_"});
 1308: 	$ENV{"form.$_"}=~s/[^\w\/\s\(\)\=\-\"\']//g;
 1309:     }
 1310:     # Preprocess the category form element.
 1311:     $ENV{'form.category'} = 'any' if (! defined($ENV{'form.category'}) ||
 1312:                                       ref($ENV{'form.category'}));
 1313:     #
 1314:     # Check to see if enough information was filled in
 1315:     for my $field ('title','author','subject','keywords','url','version',
 1316: 		   'notes','abstract','category','extension','language',
 1317:                    'owner','custommetadata') {
 1318: 	if (&filled($ENV{"form.$field"})) {
 1319: 	    $fillflag++;
 1320: 	}
 1321:     }
 1322:     unless ($fillflag) {
 1323: 	&output_blank_field_error($r,$closebutton,'phase=disp_adv');
 1324: 	return ;
 1325:     }
 1326:     # Turn the form input into a SQL-based query
 1327:     my $query='';
 1328:     my @queries;
 1329:     my $font = '<font color="#800000" face="helvetica">';
 1330:     # Evaluate logical expression AND/OR/NOT phrase fields.
 1331:     foreach my $field ('title','author','subject','notes','abstract','url',
 1332: 		       'keywords','version','owner') {
 1333: 	if ($ENV{'form.'.$field}) {
 1334:             my $searchphrase = $ENV{'form.'.$field};
 1335:             $pretty_search_string .= $font."$field</font> contains <b>".
 1336:                 $searchphrase."</b>";
 1337:             if ($ENV{'form.'.$field.'_related'}) {
 1338:                 my @New_Words;
 1339:                 ($searchphrase,@New_Words) = &related_version($searchphrase);
 1340:                 if (@New_Words) {
 1341:                     $pretty_search_string .= " with related words: ".
 1342:                         "<b>@New_Words</b>.";
 1343:                 } else {
 1344:                     $pretty_search_string .= " with no related words.";
 1345:                 }
 1346:             }
 1347:             $pretty_search_string .= "<br />\n";
 1348: 	    push @queries,&build_SQL_query($field,$searchphrase);
 1349:         }
 1350:     }
 1351:     #
 1352:     # Make the 'mime' from 'form.category' and 'form.extension'
 1353:     #
 1354:     my $searchphrase;
 1355:     if (exists($ENV{'form.category'})    && 
 1356:         $ENV{'form.category'} !~ /^\s*$/ &&
 1357:         $ENV{'form.category'} ne 'any')     {
 1358:         my @extensions = &Apache::loncommon::filecategorytypes
 1359:                                                    ($ENV{'form.category'});
 1360:         if (scalar(@extensions) > 0) {
 1361:             $searchphrase = join(' OR ',@extensions);
 1362:         }
 1363:     }
 1364:     if (exists($ENV{'form.extension'}) && $ENV{'form.extension'} !~ /^\s*$/) {
 1365:         $searchphrase .= ' OR ' if (defined($searchphrase));
 1366:         my @extensions = split(/,/,$ENV{'form.extension'});
 1367:         $searchphrase .= join(' OR ',@extensions);
 1368:     }
 1369:     if (defined($searchphrase)) {
 1370:         push @queries,&build_SQL_query('mime',$searchphrase);
 1371:         $pretty_search_string .=$font.'mime</font> contains <b>'.
 1372:             $searchphrase.'</b><br />';
 1373:     }
 1374:     #####
 1375:     # Evaluate option lists
 1376:     if ($ENV{'form.language'} and $ENV{'form.language'} ne 'any') {
 1377: 	push @queries,"(language like \"$ENV{'form.language'}\")";
 1378:         $pretty_search_string.=$font."language</font>= ".
 1379:             &Apache::loncommon::languagedescription($ENV{'form.language'}).
 1380:                 "<br />\n";
 1381:     }
 1382:     if ($ENV{'form.copyright'} and $ENV{'form.copyright'} ne 'any') {
 1383: 	push @queries,"(copyright like \"$ENV{'form.copyright'}\")";
 1384:         $pretty_search_string.=$font."copyright</font> = ".
 1385:             &Apache::loncommon::copyrightdescription($ENV{'form.copyright'}).
 1386:                 "<br \>\n";
 1387:     }
 1388:     #
 1389:     # Evaluate date windows
 1390:     my $datequery=&build_date_queries(
 1391: 			$ENV{'form.creationdatestart_month'},
 1392: 			$ENV{'form.creationdatestart_day'},
 1393: 			$ENV{'form.creationdatestart_year'},
 1394: 			$ENV{'form.creationdateend_month'},
 1395: 			$ENV{'form.creationdateend_day'},
 1396: 			$ENV{'form.creationdateend_year'},
 1397: 			$ENV{'form.lastrevisiondatestart_month'},
 1398: 			$ENV{'form.lastrevisiondatestart_day'},
 1399: 			$ENV{'form.lastrevisiondatestart_year'},
 1400: 			$ENV{'form.lastrevisiondateend_month'},
 1401: 			$ENV{'form.lastrevisiondateend_day'},
 1402: 			$ENV{'form.lastrevisiondateend_year'},
 1403: 			);
 1404:     # Test to see if date windows are legitimate
 1405:     if ($datequery=~/^Incorrect/) {
 1406: 	&output_date_error($r,$datequery,$closebutton);
 1407: 	return ;
 1408:     } elsif ($datequery) {
 1409:         # Here is where you would set up pretty_search_string to output
 1410:         # date query information.
 1411: 	push @queries,$datequery;
 1412:     }
 1413:     # Process form information for custom metadata querying
 1414:     my $customquery=undef;
 1415: #    if ($ENV{'form.custommetadata'}) {
 1416: #        $pretty_search_string .=$font."Custom Metadata Search</font>: <b>".
 1417: #            $ENV{'form.custommetadata'}."</b><br />\n";
 1418: #	$customquery=&build_custommetadata_query('custommetadata',
 1419: #				      $ENV{'form.custommetadata'});
 1420: #    }
 1421:     my $customshow=undef;
 1422: #    if ($ENV{'form.customshow'}) {
 1423: #        $pretty_search_string .=$font."Custom Metadata Display</font>: <b>".
 1424: #            $ENV{'form.customshow'}."</b><br />\n";
 1425: #	$customshow=$ENV{'form.customshow'};
 1426: #	$customshow=~s/[^\w\s]//g;
 1427: #	my @fields=split(/\s+/,$customshow);
 1428: #	$customshow=join(" ",@fields);
 1429: #    }
 1430:     ## ---------------------------------------------------------------
 1431:     ## Deal with restrictions to given domains
 1432:     ## 
 1433:     my ($libraries_to_query,$pretty_domains_string) = 
 1434:         &parse_domain_restrictions();
 1435:     $pretty_search_string .= $pretty_domains_string."<br />\n";
 1436:     #
 1437:     if (@queries) {
 1438: 	$query=join(" AND ",@queries);
 1439: 	$query="select * from metadata where $query";
 1440:     } elsif ($customquery) {
 1441:         $query = '';
 1442:     }
 1443:     return ($query,$customquery,$customshow,$libraries_to_query,
 1444:             $pretty_search_string);
 1445: }
 1446: 
 1447: sub parse_domain_restrictions {
 1448:     my $libraries_to_query = undef;
 1449:     # $ENV{'form.domains'} can be either a scalar or an array reference.
 1450:     # We need an array.
 1451:     if (! exists($ENV{'form.domains'})) {
 1452:         return (undef,'');
 1453:     }
 1454:     my @allowed_domains;
 1455:     if (ref($ENV{'form.domains'})) {
 1456:         @allowed_domains =  @{$ENV{'form.domains'}};
 1457:     } else {
 1458:         @allowed_domains = ($ENV{'form.domains'});
 1459:     }
 1460:     my %domain_hash = ();
 1461:     my $pretty_domains_string;
 1462:     foreach (@allowed_domains) {
 1463:         $domain_hash{$_}++;
 1464:     }
 1465:     if ($domain_hash{'any'}) {
 1466:         $pretty_domains_string = "In all LON-CAPA domains.";
 1467:     } else {
 1468:         if (@allowed_domains > 1) {
 1469:             $pretty_domains_string = "In LON-CAPA domains:";
 1470:         } else {
 1471:             $pretty_domains_string = "In LON-CAPA domain ";
 1472:         }
 1473:         foreach (sort @allowed_domains) {
 1474:             $pretty_domains_string .= "<b>".$_."</b> ";
 1475:         }
 1476:         foreach (keys(%Apache::lonnet::libserv)) {
 1477:             if (exists($domain_hash{$Apache::lonnet::hostdom{$_}})) {
 1478:                 push @$libraries_to_query,$_;
 1479:             }
 1480:         }
 1481:     }
 1482:     return ($libraries_to_query,$pretty_domains_string);
 1483: }
 1484: 
 1485: ######################################################################
 1486: ######################################################################
 1487: 
 1488: =pod 
 1489: 
 1490: =item &parse_basic_search() 
 1491: 
 1492: Parse the basic search form and return a scalar containing an sql query.
 1493: 
 1494: =cut
 1495: 
 1496: ######################################################################
 1497: ######################################################################
 1498: sub parse_basic_search {
 1499:     my ($r,$closebutton)=@_;
 1500:     # Clean up fields for safety
 1501:     for my $field ('basicexp') {
 1502: 	$ENV{"form.$field"}=~s/[^\w\s\(\)\-]//g;
 1503:     }
 1504:     foreach ('mode','form','element') {
 1505: 	# is this required?  Hmmm.
 1506: 	next unless (exists($ENV{"form.$_"}));
 1507: 	$ENV{"form.$_"}=&Apache::lonnet::unescape($ENV{"form.$_"});
 1508: 	$ENV{"form.$_"}=~s/[^\w\/\s\(\)\=\-\"\']//g;
 1509:     }
 1510:     my ($libraries_to_query,$pretty_domains_string) = 
 1511:         &parse_domain_restrictions();
 1512:     # Check to see if enough is filled in
 1513:     unless (&filled($ENV{'form.basicexp'})) {
 1514: 	&output_blank_field_error($r,$closebutton,'phase=disp_basic');
 1515: 	return OK;
 1516:     }
 1517:     my $pretty_search_string = '<b>'.$ENV{'form.basicexp'}.'</b>';
 1518:     my $search_string = $ENV{'form.basicexp'};
 1519:     if ($ENV{'form.related'}) {
 1520:         my @New_Words;
 1521:         ($search_string,@New_Words) = &related_version($ENV{'form.basicexp'});
 1522:         if (@New_Words) {
 1523:             $pretty_search_string .= " with related words: <b>@New_Words</b>.";
 1524:         } else {
 1525:             $pretty_search_string .= " with no related words.";
 1526:         }
 1527:     }
 1528:     # Build SQL query string based on form page
 1529:     my $query='';
 1530:     my $concatarg=join(',',
 1531: 		       ('title', 'author', 'subject', 'notes', 'abstract',
 1532:                         'keywords'));
 1533:     $concatarg='title' if $ENV{'form.titleonly'};
 1534:     $query=&build_SQL_query('concat_ws(" ",'.$concatarg.')',$search_string);
 1535:     if (defined($pretty_domains_string) && $pretty_domains_string ne '') {
 1536:         $pretty_search_string .= ' '.$pretty_domains_string;
 1537:     }
 1538:     $pretty_search_string .= "<br />\n";
 1539:     my $final_query = 'SELECT * FROM metadata WHERE '.$query;
 1540: #    &Apache::lonnet::logthis($final_query);
 1541:     return ($final_query,$pretty_search_string,
 1542:             $libraries_to_query);
 1543: }
 1544: 
 1545: 
 1546: ######################################################################
 1547: ######################################################################
 1548: 
 1549: =pod 
 1550: 
 1551: =item &related_version
 1552: 
 1553: Modifies an input string to include related words.  Words in the string
 1554: are replaced with parenthesized lists of 'OR'd words.  For example
 1555: "torque" is replaced with "(torque OR word1 OR word2 OR ...)".  
 1556: 
 1557: Note: Using this twice on a string is probably silly.
 1558: 
 1559: =cut
 1560: 
 1561: ######################################################################
 1562: ######################################################################
 1563: sub related_version {
 1564:     my $search_string = shift;
 1565:     my $result = $search_string;
 1566:     my %New_Words = ();
 1567:     while ($search_string =~ /(\w+)/cg) {
 1568:         my $word = $1;
 1569:         next if (lc($word) =~ /\b(or|and|not)\b/);
 1570:         my @Words = &Apache::loncommon::get_related_words($word);
 1571:         @Words = ($#Words>4? @Words[0..4] : @Words);
 1572:         foreach (@Words) { $New_Words{$_}++;}
 1573:         my $replacement = join " OR ", ($word,@Words);
 1574:         $result =~ s/(\b)$word(\b)/$1($replacement)$2/g;
 1575:     }
 1576:     return $result,sort(keys(%New_Words));
 1577: }
 1578: 
 1579: ######################################################################
 1580: ######################################################################
 1581: 
 1582: =pod 
 1583: 
 1584: =item &build_SQL_query() 
 1585: 
 1586: Builds a SQL query string from a logical expression with AND/OR keywords
 1587: using Text::Query and &recursive_SQL_query_builder()
 1588: 
 1589: =cut
 1590: 
 1591: ######################################################################
 1592: ######################################################################
 1593: sub build_SQL_query {
 1594:     my ($field_name,$logic_statement)=@_;
 1595:     my $q=new Text::Query('abc',
 1596: 			  -parse => 'Text::Query::ParseAdvanced',
 1597: 			  -build => 'Text::Query::Build');
 1598:     $q->prepare($logic_statement);
 1599:     my $matchexp=${$q}{'matchexp'}; chomp $matchexp;
 1600:     my $sql_query=&recursive_SQL_query_build($field_name,$matchexp);
 1601:     return $sql_query;
 1602: }
 1603: 
 1604: ######################################################################
 1605: ######################################################################
 1606: 
 1607: =pod 
 1608: 
 1609: =item &build_custommetadata_query() 
 1610: 
 1611: Constructs a custom metadata query using a rather heinous regular
 1612: expression.
 1613: 
 1614: =cut
 1615: 
 1616: ######################################################################
 1617: ######################################################################
 1618: sub build_custommetadata_query {
 1619:     my ($field_name,$logic_statement)=@_;
 1620:     my $q=new Text::Query('abc',
 1621: 			  -parse => 'Text::Query::ParseAdvanced',
 1622: 			  -build => 'Text::Query::BuildAdvancedString');
 1623:     $q->prepare($logic_statement);
 1624:     my $matchexp=${$q}{'-parse'}{'-build'}{'matchstring'};
 1625:     # quick fix to change literal into xml tag-matching
 1626:     # will eventually have to write a separate builder module
 1627:     # wordone=wordtwo becomes\<wordone\>[^\<] *wordtwo[^\<]*\<\/wordone\>
 1628:     $matchexp =~ s/(\w+)\\=([\w\\\+]+)?# wordone=wordtwo is changed to 
 1629:                  /\\<$1\\>?#           \<wordone\>
 1630:                    \[\^\\<\]?#        [^\<]         
 1631:                    \*$2\[\^\\<\]?#           *wordtwo[^\<]
 1632:                    \*\\<\\\/$1\\>?#                        *\<\/wordone\>
 1633:                    /g;
 1634:     return $matchexp;
 1635: }
 1636: 
 1637: ######################################################################
 1638: ######################################################################
 1639: 
 1640: =pod 
 1641: 
 1642: =item &recursive_SQL_query_build() 
 1643: 
 1644: Recursively constructs an SQL query.  Takes as input $dkey and $pattern.
 1645: 
 1646: =cut
 1647: 
 1648: ######################################################################
 1649: ######################################################################
 1650: sub recursive_SQL_query_build {
 1651:     my ($dkey,$pattern)=@_;
 1652:     my @matches=($pattern=~/(\[[^\]|\[]*\])/g);
 1653:     return $pattern unless @matches;
 1654:     foreach my $match (@matches) {
 1655:         $match=~/\[ (\w+)\s(.*) \]/;
 1656:         my ($key,$value)=($1,$2);
 1657:         my $replacement='';
 1658:         if ($key eq 'literal') {
 1659:             $replacement="($dkey LIKE \"\%$value\%\")";
 1660:         } elsif (lc($key) eq 'not') {
 1661:             $value=~s/LIKE/NOT LIKE/;
 1662: #          $replacement="($dkey not like $value)";
 1663:             $replacement="$value";
 1664:         } elsif ($key eq 'and') {
 1665:             $value=~/(.*[\"|\)]) ([|\(|\^].*)/;
 1666:             $replacement="($1 AND $2)";
 1667: 	} elsif ($key eq 'or') {
 1668:             $value=~/(.*[\"|\)]) ([|\(|\^].*)/;
 1669:             $replacement="($1 OR $2)";
 1670: 	}
 1671: 	substr($pattern,
 1672:                index($pattern,$match),
 1673:                length($match),
 1674:                $replacement);
 1675:     }
 1676:     &recursive_SQL_query_build($dkey,$pattern);
 1677: }
 1678: 
 1679: ######################################################################
 1680: ######################################################################
 1681: 
 1682: =pod 
 1683: 
 1684: =item &build_date_queries() 
 1685: 
 1686: Builds a SQL logic query to check time/date entries.
 1687: Also reports errors (check for /^Incorrect/).
 1688: 
 1689: =cut
 1690: 
 1691: ######################################################################
 1692: ######################################################################
 1693: sub build_date_queries {
 1694:     my ($cmonth1,$cday1,$cyear1,$cmonth2,$cday2,$cyear2,
 1695: 	$lmonth1,$lday1,$lyear1,$lmonth2,$lday2,$lyear2)=@_;
 1696:     my @queries;
 1697:     if ($cmonth1 or $cday1 or $cyear1 or $cmonth2 or $cday2 or $cyear2) {
 1698: 	unless ($cmonth1 and $cday1 and $cyear1 and
 1699: 		$cmonth2 and $cday2 and $cyear2) {
 1700: 	    return "Incorrect entry for the creation date.  You must specify ".
 1701: 		   "a starting month, day, and year and an ending month, ".
 1702: 		   "day, and year.";
 1703: 	}
 1704: 	my $cnumeric1=sprintf("%d%2d%2d",$cyear1,$cmonth1,$cday1);
 1705: 	$cnumeric1+=0;
 1706: 	my $cnumeric2=sprintf("%d%2d%2d",$cyear2,$cmonth2,$cday2);
 1707: 	$cnumeric2+=0;
 1708: 	if ($cnumeric1>$cnumeric2) {
 1709: 	    return "Incorrect entry for the creation date.  The starting ".
 1710: 		   "date must occur before the ending date.";
 1711: 	}
 1712: 	my $cquery="(creationdate BETWEEN '$cyear1-$cmonth1-$cday1' AND '".
 1713: 	           "$cyear2-$cmonth2-$cday2 23:59:59')";
 1714: 	push @queries,$cquery;
 1715:     }
 1716:     if ($lmonth1 or $lday1 or $lyear1 or $lmonth2 or $lday2 or $lyear2) {
 1717: 	unless ($lmonth1 and $lday1 and $lyear1 and
 1718: 		$lmonth2 and $lday2 and $lyear2) {
 1719: 	    return "Incorrect entry for the last revision date.  You must ".
 1720: 		   "specify a starting month, day, and year and an ending ".
 1721: 		   "month, day, and year.";
 1722: 	}
 1723: 	my $lnumeric1=sprintf("%d%2d%2d",$lyear1,$lmonth1,$lday1);
 1724: 	$lnumeric1+=0;
 1725: 	my $lnumeric2=sprintf("%d%2d%2d",$lyear2,$lmonth2,$lday2);
 1726: 	$lnumeric2+=0;
 1727: 	if ($lnumeric1>$lnumeric2) {
 1728: 	    return "Incorrect entry for the last revision date.  The ".
 1729: 		   "starting date must occur before the ending date.";
 1730: 	}
 1731: 	my $lquery="(lastrevisiondate BETWEEN '$lyear1-$lmonth1-$lday1' AND '".
 1732: 	           "$lyear2-$lmonth2-$lday2 23:59:59')";
 1733: 	push @queries,$lquery;
 1734:     }
 1735:     if (@queries) {
 1736: 	return join(" AND ",@queries);
 1737:     }
 1738:     return '';
 1739: }
 1740: 
 1741: ######################################################################
 1742: ######################################################################
 1743: 
 1744: =pod
 1745: 
 1746: =item &copyright_check()
 1747: 
 1748: =cut
 1749: 
 1750: ######################################################################
 1751: ######################################################################
 1752: sub copyright_check {
 1753:     my $Metadata = shift;
 1754:     # Check copyright tags and skip results the user cannot use
 1755:     my (undef,undef,$resdom,$resname) = split('/',
 1756:                                               $Metadata->{'url'});
 1757:     # Check for priv
 1758:     if (($Metadata->{'copyright'} eq 'priv') && 
 1759:         (($ENV{'user.name'} ne $resname) &&
 1760:          ($ENV{'user.domain'} ne $resdom))) {
 1761:         return 0;
 1762:     }
 1763:     # Check for domain
 1764:     if (($Metadata->{'copyright'} eq 'domain') &&
 1765:         ($ENV{'user.domain'} ne $resdom)) {
 1766:         return 0;
 1767:     }
 1768:     return 1;
 1769: }
 1770: 
 1771: 
 1772: ######################################################################
 1773: ######################################################################
 1774: 
 1775: =pod
 1776: 
 1777: =item &ensure_db_and_table
 1778: 
 1779: Ensure we can get lonmysql to connect to the database and the table we
 1780: need exists.
 1781: 
 1782: Inputs: $r, table id
 1783: 
 1784: Returns: undef on error, 1 if the table exists.
 1785: 
 1786: =cut
 1787: 
 1788: ######################################################################
 1789: ######################################################################
 1790: sub ensure_db_and_table {
 1791:     my ($r,$table) = @_;
 1792:     ##
 1793:     ## Sanity check the table id.
 1794:     ##
 1795:     if (! defined($table) || $table eq '' || $table =~ /\D/ ) {
 1796:         $r->print("Unable to retrieve search results.  ".
 1797:                   "Unable to determine the table results were stored in.  ".
 1798:                   "</body></html>");
 1799:         return undef;
 1800:     }
 1801:     ##
 1802:     ## Make sure we can connect and the table exists.
 1803:     ##
 1804:     my $connection_result = &Apache::lonmysql::connect_to_db();
 1805:     if (!defined($connection_result)) {
 1806:         $r->print("Unable to connect to the MySQL database where your results".
 1807:                   " are stored. </body></html>");
 1808:         &Apache::lonnet::logthis("lonsearchcat: unable to get lonmysql to".
 1809:                                  " connect to database.");
 1810:         &Apache::lonnet::logthis(&Apache::lonmysql::get_error());
 1811:         return undef;
 1812:     }
 1813:     my $table_check = &Apache::lonmysql::check_table($table);
 1814:     if (! defined($table_check)) {
 1815:         $r->print("A MySQL error has occurred.</form></body></html>");
 1816:         &Apache::lonnet::logthis("lonmysql was unable to determine the status".
 1817:                                  " of table ".$table);
 1818:         return undef;
 1819:     } elsif (! $table_check) {
 1820:         $r->print("The table of results could not be found.");
 1821:         &Apache::lonnet::logthis("The user requested a table, ".$table.
 1822:                                  ", that could not be found.");
 1823:         return undef;
 1824:     }
 1825:     return 1;
 1826: }
 1827: 
 1828: ######################################################################
 1829: ######################################################################
 1830: 
 1831: =pod
 1832: 
 1833: =item &print_sort_form
 1834: 
 1835: =cut
 1836: 
 1837: ######################################################################
 1838: ######################################################################
 1839: sub print_sort_form {
 1840:     my ($r,$pretty_query_string) = @_;
 1841:     ##
 1842:     my %SortableFields = 
 1843:         (id        => 'Default',
 1844:          title     => 'Title',
 1845:          author    => 'Author',
 1846:          subject   => 'Subject',
 1847:          url       => 'URL',
 1848:          version   => 'Version Number',
 1849:          mime      => 'Mime type',
 1850:          lang      => 'Language',
 1851:          owner     => 'Owner/Publisher',
 1852:          copyright => 'Copyright',
 1853:          hostname  => 'Host',
 1854:          creationdate     => 'Creation Date',
 1855:          lastrevisiondate => 'Revision Date',
 1856:      );
 1857:     ##
 1858:     my $table = $ENV{'form.table'};
 1859:     return if (! &ensure_db_and_table($r,$table));
 1860:     ##
 1861:     ## Get the number of results 
 1862:     ##
 1863:     my $total_results = &Apache::lonmysql::number_of_rows($table);
 1864:     if (! defined($total_results)) {
 1865:         $r->print("A MySQL error has occurred.</form></body></html>");
 1866:         &Apache::lonnet::logthis("lonmysql was unable to determine the number".
 1867:                                  " of rows in table ".$table);
 1868:         &Apache::lonnet::logthis(&Apache::lonmysql::get_error());
 1869:         return;
 1870:     }
 1871:     my $result;
 1872:     $result.=<<END;
 1873: <html>
 1874: <head>
 1875: <script>
 1876:     function change_sort() {
 1877:         var newloc = "/adm/searchcat?phase=results";
 1878:         newloc += "&persistent_db_id=$ENV{'form.persistent_db_id'}";
 1879:         newloc += "&sortby=";
 1880:         newloc += document.forms.statusform.elements.sortby.value;
 1881:         parent.resultsframe.location= newloc;
 1882:     }
 1883: </script>
 1884: <title>Results</title>
 1885: </head>
 1886: $bodytag
 1887: <form name="statusform" action="" method="post">
 1888: <input type="hidden" name="Queue" value="" />
 1889: END
 1890: 
 1891: #<h2>Sort Results</h2>
 1892: #Sort by: <select size="1" name="sortby" onchange="javascript:change_sort();">
 1893: #    $ENV{'form.sortby'} = 'id' if (! defined($ENV{'form.sortby'}));
 1894: #    foreach (keys(%SortableFields)) {
 1895: #        $result.="<option name=\"$_\"";
 1896: #        if ($_ eq $ENV{'form.sortby'}) {
 1897: #            $result.=" selected ";
 1898: #        }
 1899: #        $result.=" >$SortableFields{$_}</option>\n";
 1900: #    }
 1901: #    $result.="</select>\n";
 1902:     my $revise = &revise_button();
 1903:     $result.=<<END;
 1904: <p>
 1905: There are $total_results matches to your query. $revise
 1906: </p><p>
 1907: Search:$pretty_query_string
 1908: </p>
 1909: </form>
 1910: </body>
 1911: </html>
 1912: END
 1913:     $r->print($result);
 1914:     return;
 1915: }
 1916: 
 1917: #####################################################################
 1918: #####################################################################
 1919: 
 1920: =pod
 1921: 
 1922: =item MySQL Table Description
 1923: 
 1924: MySQL table creation requires a precise description of the data to be
 1925: stored.  The use of the correct types to hold data is vital to efficient
 1926: storage and quick retrieval of records.  The columns must be described in
 1927: the following format:
 1928: 
 1929: =cut
 1930: 
 1931: #####################################################################
 1932: #####################################################################
 1933: 
 1934: my @Datatypes = 
 1935:     ( { name => 'id', 
 1936:         type => 'MEDIUMINT',
 1937:         restrictions => 'UNSIGNED NOT NULL',
 1938:         primary_key  => 'yes',
 1939:         auto_inc     => 'yes' },
 1940:       { name => 'title',     type=>'TEXT'},
 1941:       { name => 'author',    type=>'TEXT'},
 1942:       { name => 'subject',   type=>'TEXT'},
 1943:       { name => 'url',       type=>'TEXT', restrictions => 'NOT NULL' },
 1944:       { name => 'keywords',  type=>'TEXT'},
 1945:       { name => 'version',   type=>'TEXT'},
 1946:       { name => 'notes',     type=>'TEXT'},
 1947:       { name => 'abstract',  type=>'TEXT'},
 1948:       { name => 'mime',      type=>'TEXT'},
 1949:       { name => 'lang',      type=>'TEXT'},
 1950:       { name => 'owner',     type=>'TEXT'},
 1951:       { name => 'copyright', type=>'TEXT'},
 1952:       { name => 'hostname',  type=>'TEXT'},
 1953:       #--------------------------------------------------
 1954:       { name => 'creationdate',     type=>'DATETIME'},
 1955:       { name => 'lastrevisiondate', type=>'DATETIME'},
 1956:       #--------------------------------------------------
 1957:       );
 1958: 
 1959: my @Fullindicies = 
 1960:     qw/title/;
 1961: #    qw/title author subject abstract mime language owner copyright/;
 1962:     
 1963: ######################################################################
 1964: ######################################################################
 1965: 
 1966: =pod
 1967: 
 1968: =item &create_results_table()
 1969: 
 1970: Creates the table of search results by calling lonmysql.  Stores the
 1971: table id in $ENV{'form.table'}
 1972: 
 1973: Inputs: none.
 1974: 
 1975: Returns: the identifier of the table on success, undef on error.
 1976: 
 1977: =cut
 1978: 
 1979: ######################################################################
 1980: ######################################################################
 1981: sub create_results_table {
 1982:     my $table = &Apache::lonmysql::create_table
 1983:         ( { columns => \@Datatypes,
 1984:             FULLTEXT => [{'columns' => \@Fullindicies},],
 1985:         } );
 1986:     if (defined($table)) {
 1987:         $ENV{'form.table'} = $table;
 1988:         return $table;
 1989:     } 
 1990:     return undef; # Error...
 1991: }
 1992: 
 1993: ######################################################################
 1994: ######################################################################
 1995: 
 1996: =pod
 1997: 
 1998: =item Search Status update functions
 1999: 
 2000: Each of the following functions changes the values of one of the
 2001: input fields used to display the search status to the user.  The names
 2002: should be explanatory.
 2003: 
 2004: Inputs: Apache request handler ($r), text to display.
 2005: 
 2006: Returns: Nothing.
 2007: 
 2008: =over 4
 2009: 
 2010: =item &update_count_status()
 2011: 
 2012: =item &update_status()
 2013: 
 2014: =item &update_seconds()
 2015: 
 2016: =back
 2017: 
 2018: =cut
 2019: 
 2020: ######################################################################
 2021: ######################################################################
 2022: sub update_count_status {
 2023:     my ($r,$text) = @_;
 2024:     $text =~ s/\'/\\\'/g;
 2025:     $r->print
 2026:         ("<script>document.statusform.count.value = ' $text'</script>\n");
 2027:     $r->rflush();
 2028: }
 2029: 
 2030: sub update_status {
 2031:     my ($r,$text) = @_;
 2032:     $text =~ s/\'/\\\'/g;
 2033:     $r->print
 2034:         ("<script>document.statusform.status.value = ' $text'</script>\n");
 2035:     $r->rflush();
 2036: }
 2037: 
 2038: sub update_seconds {
 2039:     my ($r,$text) = @_;
 2040:     $text =~ s/\'/\\\'/g;
 2041:     $r->print
 2042:         ("<script>document.statusform.seconds.value = ' $text'</script>\n");
 2043:     $r->rflush();
 2044: }
 2045: 
 2046: ######################################################################
 2047: ######################################################################
 2048: 
 2049: =pod
 2050: 
 2051: =item &revise_button
 2052: 
 2053: Inputs: None
 2054: 
 2055: Returns: html string for a 'revise search' button.
 2056: 
 2057: =cut
 2058: 
 2059: ######################################################################
 2060: ######################################################################
 2061: sub revise_button {
 2062:     my $revise_phase = 'disp_basic';
 2063:     $revise_phase = 'disp_adv' if ($ENV{'form.searchmode'} eq 'advanced');
 2064:     my $newloc = '/adm/searchcat'.
 2065:         '?persistent_db_id='.$ENV{'form.persistent_db_id'}.
 2066:             '&cleargroupsort=1'.
 2067:             '&phase='.$revise_phase;
 2068:     my $result = qq{<input type="button" value="Revise search" name="revise"} .
 2069:         qq{ onClick="parent.location='$newloc';" /> };
 2070:     return $result;
 2071: }
 2072: 
 2073: ######################################################################
 2074: ######################################################################
 2075: 
 2076: =pod
 2077: 
 2078: =item &run_search 
 2079: 
 2080: =cut
 2081: 
 2082: ######################################################################
 2083: ######################################################################
 2084: sub run_search {
 2085:     my ($r,$query,$customquery,$customshow,$serverlist,$pretty_string) = @_;
 2086:     my $connection = $r->connection;
 2087:     #
 2088:     # Timing variables
 2089:     #
 2090:     my $starttime = time;
 2091:     my $max_time  = 30;  # seconds for the search to complete
 2092:     #
 2093:     # Print run_search header
 2094:     #
 2095:     $r->print(<<END);
 2096: <html>
 2097: <head><title>Search Status</title></head>
 2098: $bodytag
 2099: <form name="statusform" action="" method="post">
 2100: <input type="hidden" name="Queue" value="" />
 2101: END
 2102:     # Check to see if $pretty_string has more than one carriage return.
 2103:     # Assume \n s are following <br /> s and truncate the value.
 2104:     # (there is probably a better way)...
 2105:     my @Lines = split /<br \/>/,$pretty_string;
 2106:     if (@Lines > 2) {
 2107:         $pretty_string = join '<br \>',(@Lines[0..2],'....<br />');
 2108:     }
 2109:     $r->print("Search: ".$pretty_string);
 2110:     $r->rflush();
 2111:     #
 2112:     # Determine the servers we need to contact.
 2113:     #
 2114:     my @Servers_to_contact;
 2115:     if (defined($serverlist)) {
 2116:         if (ref($serverlist) eq 'ARRAY') {
 2117:             @Servers_to_contact = @$serverlist;
 2118:         } else {
 2119:             @Servers_to_contact = ($serverlist);
 2120:         }
 2121:     } else {
 2122:         @Servers_to_contact = sort(keys(%Apache::lonnet::libserv));
 2123:     }
 2124:     my %Server_status;
 2125:     my $table =$ENV{'form.table'};
 2126:     if (! defined($table) || $table eq '' || $table =~ /\D/ ) {
 2127:         $r->print("Unable to determine table id to store search results in.".
 2128:                   "The search has been aborted.</body></html>");
 2129:         return;
 2130:     }
 2131:     my $table_status = &Apache::lonmysql::check_table($table);
 2132:     if (! defined($table_status)) {
 2133:         $r->print("Unable to determine status of table.</body></html>");
 2134:         &Apache::lonnet::logthis("Bogus table id of $table for ".
 2135:                                  "$ENV{'user.name'} @ $ENV{'user.domain'}");
 2136:         &Apache::lonnet::logthis("lonmysql error = ".
 2137:                                  &Apache::lonmysql::get_error());
 2138:         return;
 2139:     }
 2140:     if (! $table_status) {
 2141:         $r->print("The table id,$table, we tried to use is invalid.".
 2142:                   "The search has been aborted.</body></html>");
 2143:         return;
 2144:     }
 2145:     ##
 2146:     ## Prepare for the big loop.
 2147:     ##
 2148:     my $hitcountsum;
 2149:     my $server; 
 2150:     my $status;
 2151:     my $revise = &revise_button();
 2152:     $r->print(<<END);
 2153: <table>
 2154: <tr><th>Status</th><th>Total Matches</th><th>Time Remaining</th><th></th></tr>
 2155: <tr>
 2156: <td><input type="text" name="status"  value="" size="30" /></td>
 2157: <td><input type="text" name="count"   value="" size="10" /></td>
 2158: <td><input type="text" name="seconds" value="" size="8" /></td>
 2159: <td>$revise</td>
 2160: </tr>
 2161: </table>
 2162: </form>
 2163: END
 2164:     $r->rflush();
 2165:     my $time_remaining = $max_time - (time - $starttime) ;
 2166:     my $last_time = $time_remaining;
 2167:     &update_seconds($r,$time_remaining);
 2168:     &update_status($r,'contacting '.$Servers_to_contact[0]);
 2169:     while (($time_remaining > 0) &&
 2170:            ((@Servers_to_contact) || keys(%Server_status))) {
 2171:         # Send out a search request if it needs to be done.
 2172:         if (@Servers_to_contact) {
 2173:             # Contact one server
 2174:             my $server = shift(@Servers_to_contact);
 2175:             &update_status($r,'contacting '.$server);
 2176:             my $reply=&Apache::lonnet::metadata_query($query,$customquery,
 2177:                                                       $customshow,[$server]);
 2178:             ($server) = keys(%$reply);
 2179:             $Server_status{$server} = $reply->{$server};
 2180:         } else {
 2181:             # wait a sec. to give time for files to be written
 2182:             # This sleep statement is here instead of outside the else 
 2183:             # block because we do not want to pause if we have servers
 2184:             # left to contact.  
 2185:             if (scalar (keys(%Server_status))) {
 2186:                 &update_status($r,
 2187:                                'waiting on '.(join(' ',keys(%Server_status))));
 2188:             }
 2189:             sleep(1); 
 2190:         }
 2191:         #
 2192:         #
 2193:         # Loop through the servers we have contacted but do not
 2194:         # have results from yet, looking for results.
 2195:         while (my ($server,$status) = each(%Server_status)) {
 2196:             last if ($connection->aborted());
 2197:             if ($status eq 'con_lost') {
 2198:                 delete ($Server_status{$server});
 2199:                 next;
 2200:             }
 2201:             $status=~/^([\.\w]+)$/; 
 2202:        	    my $datafile=$r->dir_config('lonDaemons').'/tmp/'.$1;
 2203:             if (-e $datafile && ! -e "$datafile.end") {
 2204:                 &update_status($r,'Receiving results from '.$server);
 2205:                 next;
 2206:             }
 2207:             last if ($connection->aborted());
 2208:             if (-e "$datafile.end") {
 2209:                 &update_status($r,'Reading results from '.$server);
 2210:                 if (-z "$datafile") {
 2211:                     delete($Server_status{$server});
 2212:                     next;
 2213:                 }
 2214:                 my $fh;
 2215:                 if (!($fh=Apache::File->new($datafile))) { 
 2216:                     $r->print("Unable to open search results file for ".
 2217:                                   "server $server.  Omitting from search");
 2218:                     delete($Server_status{$server}); 
 2219:                    next;
 2220:                 }
 2221:                 # Read in the whole file.
 2222:                 while (my $result = <$fh>) {
 2223:                     last if ($connection->aborted());
 2224:                     # handle custom fields?  Someday we will!
 2225:                     chomp($result);
 2226:                     next unless $result;
 2227:                     # Parse the result.
 2228:                     my %Fields = &parse_raw_result($result,$server);
 2229:                     $Fields{'hostname'} = $server;
 2230:                     next if (! &copyright_check(\%Fields));
 2231:                     # Store the result in the mysql database
 2232:                     my $result = &Apache::lonmysql::store_row($table,\%Fields);
 2233:                     if (! defined($result)) {
 2234:                         $r->print(&Apache::lonmysql::get_error());
 2235:                     }
 2236:                     # $r->print(&Apache::lonmysql::get_debug());
 2237:                     $hitcountsum ++;
 2238:                     $time_remaining = $max_time - (time - $starttime) ;
 2239:                     if ($last_time - $time_remaining > 0) {
 2240:                         &update_seconds($r,$time_remaining);
 2241:                         $last_time = $time_remaining;
 2242:                     }
 2243:                     if ($hitcountsum % 50 == 0) {
 2244:                         &update_count_status($r,$hitcountsum);
 2245:                     }
 2246:                 } # End of foreach (@results)
 2247:                 $fh->close();
 2248:                 # $server is only deleted if the results file has been 
 2249:                 # found and (successfully) opened.  This may be a bad idea.
 2250:                 delete($Server_status{$server});
 2251:             }
 2252:             last if ($connection->aborted());
 2253:             &update_count_status($r,$hitcountsum);
 2254:         }
 2255:         last if ($connection->aborted());
 2256:         # Finished looping through the servers
 2257:         $starttime = time if (@Servers_to_contact);
 2258:         $time_remaining = $max_time - (time - $starttime) ;
 2259:         if ($last_time - $time_remaining > 0) {
 2260:             $last_time = $time_remaining;
 2261:             &update_seconds($r,$time_remaining);
 2262:         }
 2263:     }
 2264:     &update_status($r,'Search Complete'.$server);
 2265:     &update_seconds($r,0);
 2266:     &Apache::lonmysql::disconnect_from_db();
 2267:     # We have run out of time or run out of servers to talk to and
 2268:     # results to get.  
 2269:     $r->print("</body></html>");
 2270:     if ($ENV{'form.catalogmode'} ne 'groupsearch') {
 2271:         $r->print("<script>".
 2272:                       "window.location='/adm/searchcat?".
 2273:                       "phase=sort&".
 2274:                       "persistent_db_id=$ENV{'form.persistent_db_id'}';".
 2275:                   "</script>");
 2276:     }
 2277:     return;
 2278: }
 2279: 
 2280: ######################################################################
 2281: ######################################################################
 2282: =pod
 2283: 
 2284: =item &prev_next_buttons
 2285: 
 2286: =cut
 2287: 
 2288: ######################################################################
 2289: ######################################################################
 2290: sub prev_next_buttons {
 2291:     my ($current_min,$show,$total,$parms) = @_;
 2292:     return '' if ($show eq 'all'); # No links if you get them all at once.
 2293:     my $links;
 2294:     ##
 2295:     ## Prev
 2296:     my $prev_min = $current_min - $show;
 2297:     $prev_min = 1 if $prev_min < 1;
 2298:     if ($prev_min < $current_min) {
 2299:         $links .= qq{
 2300: <a href="/adm/searchcat?$parms&start=$prev_min&show=$show">prev</a>
 2301: };    
 2302:     } else {
 2303:         $links .= 'prev';
 2304:     }
 2305:     ##
 2306:     ## Pages.... Someday.
 2307:     ##
 2308:     $links .= qq{ &nbsp;
 2309: <a href="/adm/searchcat?$parms&start=$current_min&$show=$show">reload</a>
 2310: };
 2311:     ##
 2312:     ## Next
 2313:     my $next_min = $current_min + $show;
 2314:     $next_min = $current_min if ($next_min > $total);
 2315:     if ($next_min != $current_min) {
 2316:         $links .= qq{ &nbsp;
 2317: <a href="/adm/searchcat?$parms&start=$next_min&show=$show">next</a>
 2318: };    
 2319:     } else {
 2320:         $links .= '&nbsp;next';
 2321:     }
 2322:     return $links;
 2323: }
 2324: ######################################################################
 2325: ######################################################################
 2326: 
 2327: =pod
 2328: 
 2329: =item &display_results
 2330: 
 2331: =cut
 2332: 
 2333: ######################################################################
 2334: ######################################################################
 2335: sub display_results {
 2336:     my ($r,$importbutton,$closebutton) = @_;
 2337:     my $connection = $r->connection;
 2338:     $r->print(&search_results_header($importbutton,$closebutton));
 2339:     ##
 2340:     ## Set viewing function
 2341:     ##
 2342:     my $viewfunction = $Views{$ENV{'form.viewselect'}};
 2343:     if (!defined($viewfunction)) {
 2344:         $r->print("Internal Error - Bad view selected.\n");
 2345:         $r->rflush();
 2346:         return;
 2347:     }
 2348:     ##
 2349:     ## $checkbox_num is a count of the number of checkboxes output on the 
 2350:     ## page this is used only during catalogmode=groupsearch.
 2351:     my $checkbox_num = 0;
 2352:     ##
 2353:     ## Get the catalog controls setup
 2354:     ##
 2355:     my $action = "/adm/searchcat?phase=results";
 2356:     ##
 2357:     ## Deal with groupsearch
 2358:     ##
 2359:     if ($ENV{'form.catalogmode'} eq 'groupsearch') {
 2360:         if (! tie(%groupsearch_db,'GDBM_File',$diropendb,
 2361:                   &GDBM_WRCREAT(),0640)) {
 2362:             $r->print('Unable to store import results.</form></body></html>');
 2363:             $r->rflush();
 2364:             return;
 2365:         } 
 2366:     }
 2367:     ##
 2368:     ## Prepare the table for querying
 2369:     ##
 2370:     my $table = $ENV{'form.table'};
 2371:     return if (! &ensure_db_and_table($r,$table));
 2372:     ##
 2373:     ## Get the number of results 
 2374:     ##
 2375:     my $total_results = &Apache::lonmysql::number_of_rows($table);
 2376:     if (! defined($total_results)) {
 2377:         $r->print("A MySQL error has occurred.</form></body></html>");
 2378:         &Apache::lonnet::logthis("lonmysql was unable to determine the number".
 2379:                                  " of rows in table ".$table);
 2380:         &Apache::lonnet::logthis(&Apache::lonmysql::get_error());
 2381:         return;
 2382:     }
 2383:     ##
 2384:     ## Determine how many results we need to get
 2385:     ##
 2386:     $ENV{'form.start'} = 1      if (! exists($ENV{'form.start'}));
 2387:     $ENV{'form.show'}  = 'all'  if (! exists($ENV{'form.show'}));
 2388:     my $min = $ENV{'form.start'};
 2389:     my $max;
 2390:     if ($ENV{'form.show'} eq 'all') {
 2391:         $max = $total_results ;
 2392:     } else {
 2393:         $max = $min + $ENV{'form.show'} - 1;
 2394:         $max = $total_results if ($max > $total_results);
 2395:     }
 2396:     ##
 2397:     ## Output links (if necessary) for 'prev' and 'next' pages.
 2398:     ##
 2399:     $r->print
 2400:         ('<center>'.
 2401:          &prev_next_buttons($min,$ENV{'form.show'},$total_results,
 2402:                             "table=".$ENV{'form.table'}.
 2403:                             "&phase=results".
 2404:                             "&persistent_db_id=".$ENV{'form.persistent_db_id'})
 2405:          ."</center>\n"
 2406:          );
 2407:     if ($total_results == 0) {
 2408:         $r->print('<meta HTTP-EQUIV="Refresh" CONTENT="1">'.
 2409:                   '<h3>There are currently no results.</h3>'.
 2410:                   "</form></body></html>");
 2411:         return;
 2412:     } else {
 2413:         $r->print
 2414:             ("<center>Results $min to $max out of $total_results</center>\n");
 2415:     }
 2416:     ##
 2417:     ## Get results from MySQL table
 2418:     ##
 2419:     my @Results = &Apache::lonmysql::get_rows($table,
 2420:                                               'id>='.$min.' AND id<='.$max);
 2421:     ##
 2422:     ## Loop through the results and output them.
 2423:     ##
 2424:     foreach my $row (@Results) {
 2425:         if ($connection->aborted()) {
 2426:             &cleanup();
 2427:             return;
 2428:         }
 2429:         my %Fields = %{&parse_row(@$row)};
 2430:         my $output="<p>\n";
 2431:         my $prefix=&catalogmode_output($Fields{'title'},$Fields{'url'},
 2432:                                        $Fields{'id'},$checkbox_num++);
 2433:         # Render the result into html
 2434:         $output.= &$viewfunction($prefix,%Fields);
 2435:         # Print them out as they come in.
 2436:         $r->print($output);
 2437:         $r->rflush();
 2438:     }
 2439:     if (@Results < 1) {
 2440:         $r->print("There were no results matching your query");
 2441:     } else {
 2442:         $r->print
 2443:             ('<center>'.
 2444:              &prev_next_buttons($min,$ENV{'form.show'},$total_results,
 2445:                                 "table=".$ENV{'form.table'}.
 2446:                                 "&phase=results".
 2447:                                 "&persistent_db_id=".
 2448:                                 $ENV{'form.persistent_db_id'})
 2449:              ."</center>\n"
 2450:              );
 2451:     }
 2452:     $r->print("</form></body></html>");
 2453:     $r->rflush();
 2454:     untie %groupsearch_db if (tied(%groupsearch_db));
 2455:     return;
 2456: }
 2457: 
 2458: ######################################################################
 2459: ######################################################################
 2460: 
 2461: =pod
 2462: 
 2463: =item &catalogmode_output($title,$url,$fnum,$checkbox_num)
 2464: 
 2465: Returns html needed for the various catalog modes.  Gets inputs from
 2466: $ENV{'form.catalogmode'}.  Stores data in %groupsearch_db.
 2467: 
 2468: =cut
 2469: 
 2470: ######################################################################
 2471: ######################################################################
 2472: sub catalogmode_output {
 2473:     my $output = '';
 2474:     my ($title,$url,$fnum,$checkbox_num) = @_;
 2475:     if ($ENV{'form.catalogmode'} eq 'interactive') {
 2476:         $title=~ s/\'/\\\'/g;
 2477:         if ($ENV{'form.catalogmode'} eq 'interactive') {
 2478:             $output.=<<END 
 2479: <font size='-1'><INPUT TYPE="button" NAME="returnvalues" VALUE="SELECT"
 2480: onClick="javascript:select_data('$title','$url')">
 2481: </font>
 2482: END
 2483:         }
 2484:     } elsif ($ENV{'form.catalogmode'} eq 'groupsearch') {
 2485:         $groupsearch_db{"pre_${fnum}_link"}=$url;
 2486:         $groupsearch_db{"pre_${fnum}_title"}=$title;
 2487:         $output.=<<END;
 2488: <font size='-1'>
 2489: <input type="checkbox" name="returnvalues" value="SELECT"
 2490: onClick="javascript:queue($checkbox_num,$fnum)" />
 2491: </font>
 2492: END
 2493:     }
 2494:     return $output;
 2495: }
 2496: ######################################################################
 2497: ######################################################################
 2498: 
 2499: =pod
 2500: 
 2501: =item &parse_row
 2502: 
 2503: Parse a row returned from the database.
 2504: 
 2505: =cut
 2506: 
 2507: ######################################################################
 2508: ######################################################################
 2509: sub parse_row {
 2510:     my @Row = @_;
 2511:     my %Fields;
 2512:     for (my $i=0;$i<=$#Row;$i++) {
 2513:         $Fields{$Datatypes[$i]->{'name'}}=&Apache::lonnet::unescape($Row[$i]);
 2514:     }
 2515:     $Fields{'language'} = 
 2516:         &Apache::loncommon::languagedescription($Fields{'lang'});
 2517:     $Fields{'copyrighttag'} =
 2518:         &Apache::loncommon::copyrightdescription($Fields{'copyright'});
 2519:     $Fields{'mimetag'} =
 2520:         &Apache::loncommon::filedescription($Fields{'mime'});
 2521:     return \%Fields;
 2522: }
 2523: 
 2524: ###########################################################
 2525: ###########################################################
 2526: 
 2527: =pod
 2528: 
 2529: =item &parse_raw_result()
 2530: 
 2531: Takes a line from the file of results and parse it.  Returns a hash 
 2532: with keys for the following fields:
 2533: 'title', 'author', 'subject', 'url', 'keywords', 'version', 'notes', 
 2534: 'abstract', 'mime', 'lang', 'owner', 'copyright', 'creationdate', 
 2535: 'lastrevisiondate'.
 2536: 
 2537: In addition, the following tags are set by calling the appropriate 
 2538: lonnet function: 'language', 'cprtag', 'mimetag'.
 2539: 
 2540: The 'title' field is set to "Untitled" if the title field is blank.
 2541: 
 2542: 'abstract' and 'keywords' are truncated to 200 characters.
 2543: 
 2544: =cut
 2545: 
 2546: ###########################################################
 2547: ###########################################################
 2548: sub parse_raw_result {
 2549:     my ($result,$hostname) = @_;
 2550:     # Check for a comma - if it is there then we do not need to unescape the
 2551:     # string.  There seems to be some kind of problem with some items in
 2552:     # the database - the entire string gets sent out unescaped...?
 2553:     unless ($result =~ /,/) {
 2554:         $result = &Apache::lonnet::unescape($result);
 2555:     }
 2556:     my @fields=map {
 2557:         &Apache::lonnet::unescape($_);
 2558:     } (split(/\,/,$result));
 2559:     my ($title,$author,$subject,$url,$keywords,$version,
 2560:         $notes,$abstract,$mime,$lang,
 2561:         $creationdate,$lastrevisiondate,$owner,$copyright)=@fields;
 2562:     my %Fields = 
 2563:         ( title     => &Apache::lonnet::unescape($title),
 2564:           author    => &Apache::lonnet::unescape($author),
 2565:           subject   => &Apache::lonnet::unescape($subject),
 2566:           url       => &Apache::lonnet::unescape($url),
 2567:           keywords  => &Apache::lonnet::unescape($keywords),
 2568:           version   => &Apache::lonnet::unescape($version),
 2569:           notes     => &Apache::lonnet::unescape($notes),
 2570:           abstract  => &Apache::lonnet::unescape($abstract),
 2571:           mime      => &Apache::lonnet::unescape($mime),
 2572:           lang      => &Apache::lonnet::unescape($lang),
 2573:           owner     => &Apache::lonnet::unescape($owner),
 2574:           copyright => &Apache::lonnet::unescape($copyright),
 2575:           creationdate     => &Apache::lonnet::unescape($creationdate),
 2576:           lastrevisiondate => &Apache::lonnet::unescape($lastrevisiondate)
 2577:         );
 2578:     $Fields{'language'} = 
 2579:         &Apache::loncommon::languagedescription($Fields{'lang'});
 2580:     $Fields{'copyrighttag'} =
 2581:         &Apache::loncommon::copyrightdescription($Fields{'copyright'});
 2582:     $Fields{'mimetag'} =
 2583:         &Apache::loncommon::filedescription($Fields{'mime'});
 2584:     if ($Fields{'author'}=~/^(\s*|error)$/) {
 2585:         $Fields{'author'}="Unknown Author";
 2586:     }
 2587:     # Put spaces in the keyword list, if needed.
 2588:     $Fields{'keywords'}=~ s/,([A-z])/, $1/g; 
 2589:     if ($Fields{'title'}=~ /^\s*$/ ) { 
 2590:         $Fields{'title'}='Untitled'; 
 2591:     }
 2592:     unless ($ENV{'user.adv'}) {
 2593:         # What is this anyway?
 2594:         $Fields{'keywords'} = '- not displayed -';
 2595:         $Fields{'notes'}    = '- not displayed -';
 2596:         $Fields{'abstract'} = '- not displayed -';
 2597:         $Fields{'subject'}  = '- not displayed -';
 2598:     }
 2599:     if (length($Fields{'abstract'})>200) {
 2600:         $Fields{'abstract'} = 
 2601:             substr($Fields{'abstract'},0,200).'...';
 2602:     }
 2603:     if (length($Fields{'keywords'})>200) {
 2604:         $Fields{'keywords'} =
 2605:             substr($Fields{'keywords'},0,200).'...';
 2606:     }
 2607:     return %Fields;
 2608: }
 2609: 
 2610: ###########################################################
 2611: ###########################################################
 2612: 
 2613: =pod
 2614: 
 2615: =item &handle_custom_fields()
 2616: 
 2617: =cut
 2618: 
 2619: ###########################################################
 2620: ###########################################################
 2621: sub handle_custom_fields {
 2622:     my @results = @{shift()};
 2623:     my $customshow='';
 2624:     my $extrashow='';
 2625:     my @customfields;
 2626:     if ($ENV{'form.customshow'}) {
 2627:         $customshow=$ENV{'form.customshow'};
 2628:         $customshow=~s/[^\w\s]//g;
 2629:         my @fields=map {
 2630:             "<font color=\"#008000\">$_:</font><!-- $_ -->";
 2631:         } split(/\s+/,$customshow);
 2632:         @customfields=split(/\s+/,$customshow);
 2633:         if ($customshow) {
 2634:             $extrashow="<ul><li>".join("</li><li>",@fields)."</li></ul>\n";
 2635:         }
 2636:     }
 2637:     my $customdata='';
 2638:     my %customhash;
 2639:     foreach my $result (@results) {
 2640:         if ($result=~/^(custom\=.*)$/) { # grab all custom metadata
 2641:             my $tmp=$result;
 2642:             $tmp=~s/^custom\=//;
 2643:             my ($k,$v)=map {&Apache::lonnet::unescape($_);
 2644:                         } split(/\,/,$tmp);
 2645:             $customhash{$k}=$v;
 2646:         }
 2647:     }
 2648:     return ($extrashow,\@customfields,\%customhash);
 2649: }
 2650: 
 2651: ######################################################################
 2652: ######################################################################
 2653: 
 2654: =pod
 2655: 
 2656: =item &search_results_header
 2657: 
 2658: Output the proper html headers and javascript code to deal with different 
 2659: calling modes.
 2660: 
 2661: Takes most inputs directly from %ENV, except $mode.  
 2662: 
 2663: =over 4
 2664: 
 2665: =item $mode is either (at this writing) 'Basic' or 'Advanced'
 2666: 
 2667: =back
 2668: 
 2669: The following environment variables are checked:
 2670: 
 2671: =over 4
 2672: 
 2673: =item 'form.catalogmode' 
 2674: 
 2675: Checked for 'interactive' and 'groupsearch'.
 2676: 
 2677: =item 'form.mode'
 2678: 
 2679: Checked for existance & 'edit' mode.
 2680: 
 2681: =item 'form.form'
 2682: 
 2683: =item 'form.element'
 2684: 
 2685: =back
 2686: 
 2687: =cut
 2688: 
 2689: ######################################################################
 2690: ######################################################################
 2691: sub search_results_header {
 2692:     my ($importbutton,$closebutton) = @_;
 2693:     my $result = '';
 2694:     # output beginning of search page
 2695:     # conditional output of script functions dependent on the mode in
 2696:     # which the search was invoked
 2697:     if ($ENV{'form.catalogmode'} eq 'interactive'){
 2698: 	if (! exists($ENV{'form.mode'}) || $ENV{'form.mode'} ne 'edit') {
 2699:             $result.=<<SCRIPT;
 2700: <script type="text/javascript">
 2701:     function select_data(title,url) {
 2702: 	changeTitle(title);
 2703: 	changeURL(url);
 2704: 	parent.close();
 2705:     }
 2706:     function changeTitle(val) {
 2707: 	if (parent.opener.inf.document.forms.resinfo.elements.t) {
 2708: 	    parent.opener.inf.document.forms.resinfo.elements.t.value=val;
 2709: 	}
 2710:     }
 2711:     function changeURL(val) {
 2712: 	if (parent.opener.inf.document.forms.resinfo.elements.u) {
 2713: 	    parent.opener.inf.document.forms.resinfo.elements.u.value=val;
 2714: 	}
 2715:     }
 2716: </script>
 2717: SCRIPT
 2718:         } elsif ($ENV{'form.mode'} eq 'edit') {
 2719:             my $form = $ENV{'form.form'};
 2720:             my $element = $ENV{'form.element'};
 2721:             $result.=<<SCRIPT;
 2722: <script type="text/javascript">
 2723: function select_data(title,url) {
 2724:     changeURL(url);
 2725:     parent.close();
 2726: }
 2727: function changeTitle(val) {
 2728: }
 2729: function changeURL(val) {
 2730:     if (parent.targetwin.document) {
 2731:         parent.targetwin.document.forms["$form"].elements["$element"].value=val;
 2732:     } else {
 2733: 	var url = 'forms[\"$form\"].elements[\"$element\"].value';
 2734:         alert("Unable to transfer data to "+url);
 2735:     }
 2736: }
 2737: </script>
 2738: SCRIPT
 2739:         }
 2740:     }
 2741:     $result.=<<SCRIPT if $ENV{'form.catalogmode'} eq 'groupsearch';
 2742: <script type="text/javascript">
 2743:     function queue(checkbox_num,val) {
 2744:         if (document.forms.results.returnvalues.length != "undefined" &&
 2745:             typeof(document.forms.results.returnvalues.length) == "number") {
 2746:             if (document.forms.results.returnvalues[checkbox_num].checked) {
 2747:                 parent.statusframe.document.forms.statusform.elements.Queue.value +='1a'+val+'b';
 2748:             } else {
 2749:                 parent.statusframe.document.forms.statusform.elements.Queue.value +='0a'+val+'b';
 2750:             }
 2751:         } else {
 2752:             if (document.forms.results.returnvalues.checked) {
 2753:                 parent.statusframe.document.forms.statusform.elements.Queue.value +='1a'+val+'b';
 2754:             } else {
 2755:                 parent.statusframe.document.forms.statusform.elements.Queue.value +='0a'+val+'b';
 2756:             }
 2757:         }
 2758:     }
 2759:     function select_group() {
 2760: 	parent.window.location=
 2761:     "/adm/groupsort?mode=$ENV{'form.mode'}&catalogmode=groupsearch&acts="+
 2762: 	    parent.statusframe.document.forms.statusform.elements.Queue.value;
 2763:     }
 2764: </script>
 2765: SCRIPT
 2766:     $result.=<<END;
 2767: </head>
 2768: $bodytag
 2769: <form name="results" method="post" action="" >
 2770: <input type="hidden" name="Queue" value="" />
 2771: $importbutton
 2772: END
 2773:     return $result;
 2774: }
 2775: 
 2776: ######################################################################
 2777: ######################################################################
 2778: sub search_status_header {
 2779:     return <<ENDSTATUS;
 2780: <html><head><title>Search Status</title></head>
 2781: $bodytag
 2782: <h3>Search Status</h3>
 2783: Sending search request to LON-CAPA servers.<br />
 2784: ENDSTATUS
 2785: }
 2786: 
 2787: sub results_link {
 2788:     my $basic_link   = "/adm/searchcat?"."&table=".$ENV{'form.table'}.
 2789:         "&persistent_db_id=".$ENV{'form.persistent_db_id'};
 2790:     my $results_link = $basic_link."&phase=results".
 2791:         "&pause=1"."&start=1";
 2792:     return $results_link;
 2793: }
 2794: 
 2795: ######################################################################
 2796: ######################################################################
 2797: sub print_frames_interface {
 2798:     my $r = shift;
 2799:     my $basic_link = "/adm/searchcat?"."&table=".$ENV{'form.table'}.
 2800:         "&persistent_db_id=".$ENV{'form.persistent_db_id'};
 2801:     my $run_search_link = $basic_link."&phase=run_search";
 2802:     my $results_link = &results_link();
 2803:     my $result = <<"ENDFRAMES";
 2804: <html>
 2805: <head>
 2806: <script>
 2807: var targetwin = opener;
 2808: var queue = '';
 2809: </script>
 2810: <title>LON-CAPA Digital Library Search Results</title>
 2811: </head>
 2812: <frameset rows="150,*">
 2813:     <frame name="statusframe"  src="$run_search_link">
 2814:     <frame name="resultsframe" src="$results_link">
 2815: </frameset>
 2816: </html>
 2817: ENDFRAMES
 2818: 
 2819:     $r->print($result);
 2820:     return;
 2821: }
 2822: 
 2823: ######################################################################
 2824: ######################################################################
 2825: 
 2826: =pod 
 2827: 
 2828: =item Metadata Viewing Functions
 2829: 
 2830: Output is a HTML-ified string.
 2831: Input arguments are title, author, subject, url, keywords, version,
 2832: notes, short abstract, mime, language, creation date,
 2833: last revision date, owner, copyright, hostname, and
 2834: extra custom metadata to show.
 2835: 
 2836: =over 4
 2837: 
 2838: =item &detailed_citation_view() 
 2839: 
 2840: =cut
 2841: 
 2842: ######################################################################
 2843: ######################################################################
 2844: sub detailed_citation_view {
 2845:     my ($prefix,%values) = @_;
 2846:     my $result=<<END;
 2847: <b>$prefix<a href="http://$ENV{'HTTP_HOST'}$values{'url'}" 
 2848:     target='search_preview'>$values{'title'}</a></b>
 2849: <p>
 2850: <b>$values{'author'}</b>, <i>$values{'owner'}</i><br />
 2851: 
 2852: <b>Subject:       </b> $values{'subject'}<br />
 2853: <b>Keyword(s):    </b> $values{'keywords'}<br />
 2854: <b>Notes:         </b> $values{'notes'}<br />
 2855: <b>MIME Type:     </b> $values{'mimetag'}<br />
 2856: <b>Language:      </b> $values{'language'}<br />
 2857: <b>Copyright/Distribution:</b> $values{'cprtag'}<br />
 2858: </p>
 2859: $values{'extrashow'}
 2860: <p>
 2861: $values{'shortabstract'}
 2862: </p>
 2863: <hr align='left' width='200' noshade />
 2864: END
 2865:     return $result;
 2866: }
 2867: 
 2868: ######################################################################
 2869: ######################################################################
 2870: 
 2871: =pod 
 2872: 
 2873: =item &summary_view() 
 2874: 
 2875: =cut
 2876: ######################################################################
 2877: ######################################################################
 2878: sub summary_view {
 2879:     my ($prefix,%values) = @_;
 2880:     my $result=<<END;
 2881: $prefix<a href="http://$ENV{'HTTP_HOST'}$values{'url'}" 
 2882:    target='search_preview'>$values{'author'}</a><br />
 2883: $values{'title'}<br />
 2884: $values{'owner'} -- $values{'lastrevisiondate'}<br />
 2885: $values{'copyrighttag'}<br />
 2886: $values{'extrashow'}
 2887: </p>
 2888: <hr align='left' width='200' noshade />
 2889: END
 2890:     return $result;
 2891: }
 2892: 
 2893: ######################################################################
 2894: ######################################################################
 2895: 
 2896: =pod 
 2897: 
 2898: =item &compact_view() 
 2899: 
 2900: =cut
 2901: 
 2902: ######################################################################
 2903: ######################################################################
 2904: sub compact_view {
 2905:     my ($prefix,%values) = @_;
 2906:     my $result=<<END;
 2907: $prefix <a href="http://$ENV{'HTTP_HOST'}$values{'url'}"  target='search_preview'>
 2908: $values{'title'}</a>
 2909: <b>$values{'author'}</b><br />
 2910: END
 2911:     return $result;
 2912: }
 2913: 
 2914: 
 2915: ######################################################################
 2916: ######################################################################
 2917: 
 2918: =pod 
 2919: 
 2920: =item &fielded_format_view() 
 2921: 
 2922: =cut
 2923: 
 2924: ######################################################################
 2925: ######################################################################
 2926: sub fielded_format_view {
 2927:     my ($prefix,%values) = @_;
 2928:     my $result=<<END;
 2929: $prefix
 2930: <b>URL: </b> <a href="http://$ENV{'HTTP_HOST'}$values{'url'}" 
 2931:               target='search_preview'>$values{'url'}</a>
 2932: <br />
 2933: <b>Title:</b> $values{'title'}<br />
 2934: <b>Author(s):</b> $values{'author'}<br />
 2935: <b>Subject:</b> $values{'subject'}<br />
 2936: <b>Keyword(s):</b> $values{'keywords'}<br />
 2937: <b>Notes:</b> $values{'notes'}<br />
 2938: <b>MIME Type:</b> $values{'mimetag'}<br />
 2939: <b>Language:</b> $values{'language'}<br />
 2940: <b>Creation Date:</b> $values{'creationdate'}<br />
 2941: <b>Last Revision Date:</b> $values{'lastrevisiondate'}<br />
 2942: <b>Publisher/Owner:</b> $values{'owner'}<br />
 2943: <b>Copyright/Distribution:</b> $values{'copyrighttag'}<br />
 2944: <b>Repository Location:</b> $values{'hostname'}<br />
 2945: <b>Abstract:</b> $values{'shortabstract'}<br />
 2946: $values{'extrashow'}
 2947: </p>
 2948: <hr align='left' width='200' noshade />
 2949: END
 2950:     return $result;
 2951: }
 2952: 
 2953: ######################################################################
 2954: ######################################################################
 2955: 
 2956: =pod 
 2957: 
 2958: =item &xml_sgml_view() 
 2959: 
 2960: =back 
 2961: 
 2962: =cut
 2963: 
 2964: ######################################################################
 2965: ######################################################################
 2966: sub xml_sgml_view {
 2967:     my ($prefix,%values) = @_;
 2968:     my $result=<<END;
 2969: $prefix
 2970: <pre>
 2971: &lt;LonCapaResource&gt;
 2972: &lt;url&gt;$values{'url'}&lt;/url&gt;
 2973: &lt;title&gt;$values{'title'}&lt;/title&gt;
 2974: &lt;author&gt;$values{'author'}&lt;/author&gt;
 2975: &lt;subject&gt;$values{'subject'}&lt;/subject&gt;
 2976: &lt;keywords&gt;$values{'keywords'}&lt;/keywords&gt;
 2977: &lt;notes&gt;$values{'notes'}&lt;/notes&gt;
 2978: &lt;mimeInfo&gt;
 2979: &lt;mime&gt;$values{'mime'}&lt;/mime&gt;
 2980: &lt;mimetag&gt;$values{'mimetag'}&lt;/mimetag&gt;
 2981: &lt;/mimeInfo&gt;
 2982: &lt;languageInfo&gt;
 2983: &lt;language&gt;$values{'lang'}&lt;/language&gt;
 2984: &lt;languagetag&gt;$values{'language'}&lt;/languagetag&gt;
 2985: &lt;/languageInfo&gt;
 2986: &lt;creationdate&gt;$values{'creationdate'}&lt;/creationdate&gt;
 2987: &lt;lastrevisiondate&gt;$values{'lastrevisiondate'}&lt;/lastrevisiondate&gt;
 2988: &lt;owner&gt;$values{'owner'}&lt;/owner&gt;
 2989: &lt;copyrightInfo&gt;
 2990: &lt;copyright&gt;$values{'copyright'}&lt;/copyright&gt;
 2991: &lt;copyrighttag&gt;$values{'copyrighttag'}&lt;/copyrighttag&gt;
 2992: &lt;/copyrightInfo&gt;
 2993: &lt;repositoryLocation&gt;$values{'hostname'}&lt;/repositoryLocation&gt;
 2994: &lt;shortabstract&gt;$values{'shortabstract'}&lt;/shortabstract&gt;
 2995: &lt;/LonCapaResource&gt;
 2996: </pre>
 2997: $values{'extrashow'}
 2998: <hr align='left' width='200' noshade />
 2999: END
 3000:     return $result;
 3001: }
 3002: 
 3003: ######################################################################
 3004: ######################################################################
 3005: 
 3006: =pod 
 3007: 
 3008: =item &filled() see if field is filled.
 3009: 
 3010: =cut
 3011: 
 3012: ######################################################################
 3013: ######################################################################
 3014: sub filled {
 3015:     my ($field)=@_;
 3016:     if ($field=~/\S/ && $field ne 'any') {
 3017: 	return 1;
 3018:     }
 3019:     else {
 3020: 	return 0;
 3021:     }
 3022: }
 3023: 
 3024: ######################################################################
 3025: ######################################################################
 3026: 
 3027: =pod 
 3028: 
 3029: =item &output_blank_field_error()
 3030: 
 3031: Output a complete page that indicates the user has not filled in enough
 3032: information to do a search.
 3033: 
 3034: Inputs: $r (Apache request handle), $closebutton, $parms.
 3035: 
 3036: Returns: nothing
 3037: 
 3038: $parms is extra information to include in the 'Revise search request' link.
 3039: 
 3040: =cut
 3041: 
 3042: ######################################################################
 3043: ######################################################################
 3044: sub output_blank_field_error {
 3045:     my ($r,$closebutton,$parms)=@_;
 3046:     # make query information persistent to allow for subsequent revision
 3047:     $r->print(<<BEGINNING);
 3048: <html>
 3049: <head>
 3050: <title>The LearningOnline Network with CAPA</title>
 3051: BEGINNING
 3052:     $r->print(<<RESULTS);
 3053: </head>
 3054: $bodytag
 3055: <img align='right' src='/adm/lonIcons/lonlogos.gif' />
 3056: <h1>Search Catalog</h1>
 3057: <form method="post" action="/adm/searchcat">
 3058: $hidden_fields
 3059: <a href="/adm/searchcat?$parms&persistent_db_id=$ENV{'form.persistent_db_id'}"
 3060: >Revise search request</a>&nbsp;
 3061: $closebutton
 3062: <hr />
 3063: <h3>Unactionable search query.</h3>
 3064: <p>
 3065: You did not fill in enough information for the search to be started.
 3066: You need to fill in relevant fields on the search page in order 
 3067: for a query to be processed.
 3068: </p>
 3069: </body>
 3070: </html>
 3071: RESULTS
 3072: }
 3073: 
 3074: ######################################################################
 3075: ######################################################################
 3076: 
 3077: =pod 
 3078: 
 3079: =item &output_date_error()
 3080: 
 3081: Output a full html page with an error message.
 3082: 
 3083: Inputs: 
 3084: 
 3085:     $r, the request pointer.
 3086:     $message, the error message for the user.
 3087:     $closebutton, the specialized close button needed for groupsearch.
 3088: 
 3089: =cut
 3090: 
 3091: ######################################################################
 3092: ######################################################################
 3093: sub output_date_error {
 3094:     my ($r,$message,$closebutton)=@_;
 3095:     # make query information persistent to allow for subsequent revision
 3096:     $r->print(<<RESULTS);
 3097: <html>
 3098: <head>
 3099: <title>The LearningOnline Network with CAPA</title>
 3100: </head>
 3101: $bodytag
 3102: <img align='right' src='/adm/lonIcons/lonlogos.gif' />
 3103: <h1>Search Catalog</h1>
 3104: <form method="post" action="/adm/searchcat">
 3105: $hidden_fields
 3106: <input type='button' value='Revise search request'
 3107: onClick='this.form.submit();' />
 3108: $closebutton
 3109: <hr />
 3110: <h3>Error</h3>
 3111: <p>
 3112: $message
 3113: </p>
 3114: </body>
 3115: </html>
 3116: RESULTS
 3117: }
 3118: 
 3119: ######################################################################
 3120: ######################################################################
 3121: 
 3122: =pod 
 3123: 
 3124: =item &start_fresh_session()
 3125: 
 3126: Cleans the global %groupsearch_db by removing all fields which begin with
 3127: 'pre_' or 'store'.
 3128: 
 3129: =cut
 3130: 
 3131: ######################################################################
 3132: ######################################################################
 3133: sub start_fresh_session {
 3134:     delete $groupsearch_db{'mode_catalog'};
 3135:     foreach (keys %groupsearch_db) {
 3136:         if ($_ =~ /^pre_/) {
 3137:             delete $groupsearch_db{$_};
 3138:         }
 3139:         if ($_ =~ /^store/) {
 3140: 	    delete $groupsearch_db{$_};
 3141: 	}
 3142:     }
 3143: }
 3144: 
 3145: 1;
 3146: 
 3147: sub cleanup {
 3148:     if (tied(%groupsearch_db)) {
 3149: 	&Apache::lonnet::logthis('Cleanup searchcat: groupsearch_db');
 3150:         unless (untie(%groupsearch_db)) {
 3151: 	  &Apache::lonnet::logthis('Failed cleanup searchcat: groupsearch_db');
 3152:         }
 3153:     }
 3154:     &untiehash();
 3155:     &Apache::lonmysql::disconnect_from_db();
 3156: }
 3157: 
 3158: __END__
 3159: 
 3160: =pod
 3161: 
 3162: =back 
 3163: 
 3164: =cut

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