File:  [LON-CAPA] / loncom / interface / lonsearchcat.pm
Revision 1.186: download - view: text, annotated - select for diffs
Mon Sep 22 00:48:32 2003 UTC (20 years, 9 months ago) by www
Branches: MAIN
CVS tags: HEAD
Internationalization, German Localization

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

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