File:  [LON-CAPA] / loncom / interface / lonsearchcat.pm
Revision 1.197: download - view: text, annotated - select for diffs
Sat Dec 27 17:32:08 2003 UTC (20 years, 5 months ago) by www
Branches: MAIN
CVS tags: HEAD
Produced internal server error, commented out.

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

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