File:  [LON-CAPA] / loncom / interface / lonsearchcat.pm
Revision 1.234: download - view: text, annotated - select for diffs
Mon Sep 27 14:58:01 2004 UTC (19 years, 8 months ago) by matthew
Branches: MAIN
CVS tags: version_1_2_99_1, version_1_2_99_0, HEAD
<label>s around course search checkboxes.

    1: # The LearningOnline Network with CAPA
    2: # Search Catalog
    3: #
    4: # $Id: lonsearchcat.pm,v 1.234 2004/09/27 14:58:01 matthew Exp $
    5: #
    6: # Copyright Michigan State University Board of Trustees
    7: #
    8: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
    9: #
   10: # LON-CAPA is free software; you can redistribute it and/or modify
   11: # it under the terms of the GNU General Public License as published by
   12: # the Free Software Foundation; either version 2 of the License, or
   13: # (at your option) any later version.
   14: #
   15: # LON-CAPA is distributed in the hope that it will be useful,
   16: # but WITHOUT ANY WARRANTY; without even the implied warranty of
   17: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   18: # GNU General Public License for more details.
   19: #
   20: # You should have received a copy of the GNU General Public License
   21: # along with LON-CAPA; if not, write to the Free Software
   22: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
   23: #
   24: # /home/httpd/html/adm/gpl.txt
   25: #
   26: # http://www.lon-capa.org/
   27: #
   28: ###############################################################################
   29: ###############################################################################
   30: 
   31: =pod 
   32: 
   33: =head1 NAME
   34: 
   35: lonsearchcat - LONCAPA Search Interface
   36: 
   37: =head1 SYNOPSIS
   38: 
   39: Search interface to LON-CAPAs digital library
   40: 
   41: =head1 DESCRIPTION
   42: 
   43: This module enables searching for a distributed browseable catalog.
   44: 
   45: This is part of the LearningOnline Network with CAPA project
   46: described at http://www.lon-capa.org.
   47: 
   48: lonsearchcat presents the user with an interface to search the LON-CAPA
   49: digital library.  lonsearchcat also initiates the execution of a search
   50: by sending the search parameters to LON-CAPA servers.  The progress of 
   51: search (on a server basis) is displayed to the user in a separate 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::lonmeta;
   74: use Apache::lonhtmlcommon;
   75: use Apache::lonlocal;
   76: use LONCAPA::lonmetadata();
   77: use HTML::Entities();
   78: use Parse::RecDescent;
   79: use Apache::lonnavmaps;
   80: 
   81: ######################################################################
   82: ######################################################################
   83: ##
   84: ## Global variables
   85: ##
   86: ######################################################################
   87: ######################################################################
   88: my %groupsearch_db;  # Database hash used to save values for the 
   89:                      # groupsearch RAT interface.
   90: my %persistent_db;   # gdbm hash which holds data which is supposed to
   91:                      # persist across calls to lonsearchcat.pm
   92: 
   93: # The different view modes and associated functions
   94: 
   95: my %Views = ("detailed" => \&detailed_citation_view,
   96: 	     "summary"  => \&summary_view,
   97: 	     "fielded"  => \&fielded_format_view,
   98: 	     "xml"      => \&xml_sgml_view,
   99: 	     "compact"  => \&compact_view);
  100: 
  101: ######################################################################
  102: ######################################################################
  103: sub handler {
  104:     my $r = shift;
  105: #    &set_defaults();
  106:     #
  107:     # set form defaults
  108:     #
  109:     my $hidden_fields;# Hold all the hidden fields used to keep track
  110:                       # of the search system state
  111:     my $importbutton; # button to take the selected results and go to group 
  112:                       # sorting
  113:     my $diropendb;    # The full path to the (temporary) search database file.
  114:                       # This is set and used in &handler() and is also used in 
  115:                       # &output_results().
  116:     my $bodytag;  # LON-CAPA standard body tag, gotten from 
  117:                   # &Apache::lonnet::bodytag. 
  118:                   # No title, no table, just a <body> tag.
  119: 
  120:     my $loaderror=&Apache::lonnet::overloaderror($r);
  121:     if ($loaderror) { return $loaderror; }
  122:     #
  123:     my $closebutton;  # button that closes the search window 
  124:                       # This button is different for the RAT compared to
  125:                       # normal invocation.
  126:     #
  127:     &Apache::loncommon::content_type($r,'text/html');
  128:     $r->send_http_header;
  129:     return OK if $r->header_only;
  130:     ##
  131:     ## Prevent caching of the search interface window.  Hopefully this means
  132:     ## we will get the launch=1 passed in a little more.
  133:     &Apache::loncommon::no_cache($r);
  134:     ## 
  135:     ## Pick up form fields passed in the links.
  136:     ##
  137:     &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
  138:              ['catalogmode','launch','acts','mode','form','element','pause',
  139:               'phase','persistent_db_id','table','start','show',
  140:               'cleargroupsort','titleelement']);
  141:     ##
  142:     ## The following is a trick - we wait a few seconds if asked to so
  143:     ##     the daemon running the search can get ahead of the daemon
  144:     ##     printing the results.  We only need (theoretically) to do
  145:     ##     this once, so the pause indicator is deleted
  146:     ##
  147:     if (exists($ENV{'form.pause'})) {
  148:         sleep(1);
  149:         delete($ENV{'form.pause'});
  150:     }
  151:     ##
  152:     ## Initialize global variables
  153:     ##
  154:     my $domain  = $r->dir_config('lonDefDomain');
  155:     $diropendb= "/home/httpd/perl/tmp/".
  156:         "$ENV{'user.domain'}_$ENV{'user.name'}_searchcat.db";
  157:     #
  158:     # set the name of the persistent database
  159:     #          $ENV{'form.persistent_db_id'} can only have digits in it.
  160:     if (! exists($ENV{'form.persistent_db_id'}) ||
  161:         ($ENV{'form.persistent_db_id'} =~ /\D/) ||
  162:         ($ENV{'form.launch'} eq '1')) {
  163:         $ENV{'form.persistent_db_id'} = time;
  164:     }
  165:     $bodytag=&Apache::loncommon::bodytag(undef,undef,undef,1);
  166:     my $persistent_db_file = "/home/httpd/perl/tmp/".
  167:         &Apache::lonnet::escape($domain).
  168:             '_'.&Apache::lonnet::escape($ENV{'user.name'}).
  169:                 '_'.$ENV{'form.persistent_db_id'}.'_persistent_search.db';
  170:     ##
  171:     &Apache::lonhtmlcommon::clear_breadcrumbs();
  172:     if (exists($ENV{'request.course.id'}) && $ENV{'request.course.id'} ne '') {
  173:         &Apache::lonhtmlcommon::add_breadcrumb
  174:              ({href=>'/adm/searchcat?'.
  175:                    'catalogmode='.$ENV{'form.catalogmode'}.
  176:                    '&launch='.$ENV{'form.launch'}.
  177:                    '&mode='.$ENV{'form.mode'},
  178:               text=>"Course and Catalog Search",
  179:               target=>'_top',
  180:               bug=>'Searching',});
  181:     } else {
  182:         &Apache::lonhtmlcommon::add_breadcrumb
  183:              ({href=>'/adm/searchcat?'.
  184:                    'catalogmode='.$ENV{'form.catalogmode'}.
  185:                    '&launch='.$ENV{'form.launch'}.
  186:                    '&mode='.$ENV{'form.mode'},
  187:               text=>"Catalog Search",
  188:               target=>'_top',
  189:               bug=>'Searching',});
  190:     }
  191:     #
  192:     if ($ENV{'form.phase'} !~ m/(basic|adv|course)_search/) {
  193:         if (! &get_persistent_form_data($persistent_db_file)) {
  194:             if ($ENV{'form.phase'} =~ /(run_search|results)/) {
  195:                 &Apache::lonnet::logthis('lonsearchcat:'.
  196:                                          'Unable to recover data from '.
  197:                                          $persistent_db_file);
  198:                 $r->print(<<END);
  199: <html>
  200: <head><title>LON-CAPA Search Error</title></head>
  201: $bodytag
  202: We were unable to retrieve data describing your search.  This is a serious
  203: error and has been logged.  Please alert your LON-CAPA administrator.
  204: </body>
  205: </html>
  206: END
  207:                 return OK;
  208:             }
  209:         }
  210:     } else {
  211:         &clean_up_environment();
  212:     }
  213:     ##
  214:     ## Clear out old values from groupsearch database
  215:     ##
  216:     untie %groupsearch_db if (tied(%groupsearch_db));
  217:     if (($ENV{'form.cleargroupsort'} eq '1') || 
  218:         (($ENV{'form.launch'} eq '1') && 
  219:          ($ENV{'form.catalogmode'} eq 'groupsearch'))) {
  220: 	if (tie(%groupsearch_db,'GDBM_File',$diropendb,&GDBM_WRCREAT(),0640)) {
  221: 	    &start_fresh_session();
  222: 	    untie %groupsearch_db;
  223:             delete($ENV{'form.cleargroupsort'});
  224: 	} else {
  225:             # This is a stupid error to give to the user.  
  226:             # It really tells them nothing.
  227: 	    $r->print('<html><head></head>'.$bodytag.
  228:                       'Unable to tie hash to db file</body></html>');
  229: 	    return OK;
  230: 	}
  231:     }
  232:     ##
  233:     ## Configure hidden fields
  234:     ##
  235:     $hidden_fields = '<input type="hidden" name="persistent_db_id" value="'.
  236:         $ENV{'form.persistent_db_id'}.'" />'."\n";
  237:     if (exists($ENV{'form.catalogmode'})) {
  238:         $hidden_fields .= &hidden_field('catalogmode');
  239:     }
  240:     if (exists($ENV{'form.form'})) {
  241:         $hidden_fields .= &hidden_field('form');
  242:     }
  243:     if (exists($ENV{'form.element'})) {
  244:         $hidden_fields .= &hidden_field('element');
  245:     }
  246:     if (exists($ENV{'form.titleelement'})) {
  247:         $hidden_fields .= &hidden_field('titleelement');
  248:     }
  249:     if (exists($ENV{'form.mode'})) {
  250:         $hidden_fields .= &hidden_field('mode');
  251:     }
  252:     ##
  253:     ## Configure dynamic components of interface
  254:     ##
  255:     if ($ENV{'form.catalogmode'} eq 'interactive') {
  256:         $closebutton="<input type='button' name='close' value='CLOSE' ";
  257:         if ($ENV{'form.phase'} =~ /(results|run_search)/) {
  258: 	    $closebutton .="onClick='parent.close()'";
  259:         } else {
  260:             $closebutton .="onClick='self.close()'";
  261:         }
  262:         $closebutton .=">\n";
  263:     } elsif ($ENV{'form.catalogmode'} eq 'groupsearch') {
  264:         $closebutton="<input type='button' name='close' value='CLOSE' ";
  265:         if ($ENV{'form.phase'} =~ /(results|run_search)/) {
  266: 	    $closebutton .="onClick='parent.close()'";
  267:         } else {
  268:             $closebutton .="onClick='self.close()'";
  269:         }
  270:         $closebutton .= ">";
  271:         $importbutton=<<END;
  272: <input type='button' name='import' value='IMPORT'
  273: onClick='javascript:select_group()'>
  274: END
  275:     } else {
  276:         $closebutton = '';
  277:         $importbutton = '';
  278:     }
  279:     ##
  280:     ## Sanity checks on form elements
  281:     ##
  282:     if (!defined($ENV{'form.viewselect'})) {
  283:         if (($ENV{'form.catalogmode'} eq 'groupsearch') ||
  284:             ($ENV{'form.catalogmode'} eq 'interactive')) {
  285:             $ENV{'form.viewselect'} ="Compact View";
  286:         } else {
  287:             $ENV{'form.viewselect'} ="Detailed Citation View";
  288:         }
  289:     }
  290:     $ENV{'form.phase'} = 'disp_basic' if (! exists($ENV{'form.phase'}));
  291:     $ENV{'form.show'} = 20 if (! exists($ENV{'form.show'}));
  292:     #
  293:     $ENV{'form.searchmode'} = 'basic' if (! exists($ENV{'form.searchmode'}));
  294:     if ($ENV{'form.phase'} eq 'adv_search' ||
  295:         $ENV{'form.phase'} eq 'disp_adv') {
  296:         $ENV{'form.searchmode'} = 'advanced';
  297:     } elsif ($ENV{'form.phase'} eq 'course_search') {
  298:         $ENV{'form.searchmode'} = 'course_search';
  299:     }
  300:     #
  301:     if ($ENV{'form.searchmode'} eq 'advanced') {
  302:         &Apache::lonhtmlcommon::add_breadcrumb
  303:             ({href=>'/adm/searchcat?phase=disp_adv&'.
  304:                   'catalogmode='.$ENV{'form.catalogmode'}.
  305:                   '&launch='.$ENV{'form.launch'}.
  306:                   '&mode='.$ENV{'form.mode'},
  307:                   text=>"Advanced Search",
  308:                   bug=>'Searching',});
  309:     } elsif ($ENV{'form.searchmode'} eq 'course search') {
  310:         &Apache::lonhtmlcommon::add_breadcrumb
  311:             ({href=>'/adm/searchcat?phase=disp_adv&'.
  312:                   'catalogmode='.$ENV{'form.catalogmode'}.
  313:                   '&launch='.$ENV{'form.launch'}.
  314:                   '&mode='.$ENV{'form.mode'},
  315:                   text=>"Course Search",
  316:                   bug=>'Searching',});
  317:     }
  318:     ##
  319:     ## Switch on the phase
  320:     ##
  321:     if ($ENV{'form.phase'} eq 'disp_basic') {
  322:         &print_basic_search_form($r,$closebutton,$hidden_fields);
  323:     } elsif ($ENV{'form.phase'} eq 'disp_adv') {
  324:         &print_advanced_search_form($r,$closebutton,$hidden_fields);
  325:     } elsif ($ENV{'form.phase'} eq 'results') {
  326:         &display_results($r,$importbutton,$closebutton,$diropendb);
  327:     } elsif ($ENV{'form.phase'} =~ /^(sort|run_search)$/) {
  328:         my ($query,$customquery,$customshow,$libraries,$pretty_string) =
  329:             &get_persistent_data($persistent_db_file,
  330:                  ['query','customquery','customshow',
  331:                   'libraries','pretty_string']);
  332:         if ($ENV{'form.phase'} eq 'sort') {
  333:             &print_sort_form($r,$pretty_string);
  334:         } elsif ($ENV{'form.phase'} eq 'run_search') {
  335:             &run_search($r,$query,$customquery,$customshow,
  336:                         $libraries,$pretty_string);
  337:         }
  338:     } elsif ($ENV{'form.phase'} eq 'course_search') {
  339:         &course_search($r);
  340:     } elsif(($ENV{'form.phase'} eq 'basic_search') ||
  341:             ($ENV{'form.phase'} eq 'adv_search')) {
  342:         #
  343:         # We are running a search, try to parse it
  344:         my ($query,$customquery,$customshow,$libraries) = 
  345:             (undef,undef,undef,undef);
  346:         my $pretty_string;
  347:         if ($ENV{'form.phase'} eq 'basic_search') {
  348:             ($query,$pretty_string,$libraries) = 
  349:                 &parse_basic_search($r,$closebutton,$hidden_fields);
  350:             return OK if (! defined($query));
  351:             &make_persistent({ basicexp => $ENV{'form.basicexp'}},
  352:                              $persistent_db_file);
  353:         } else {                      # Advanced search
  354:             ($query,$customquery,$customshow,$libraries,$pretty_string) 
  355:                 = &parse_advanced_search($r,$closebutton,$hidden_fields);
  356:             return OK if (! defined($query));
  357:         }
  358:         &make_persistent({ query => $query,
  359:                            customquery => $customquery,
  360:                            customshow => $customshow,
  361:                            libraries => $libraries,
  362:                            pretty_string => $pretty_string },
  363:                          $persistent_db_file);
  364:         #
  365:         # Set up table
  366:         if (! defined(&create_results_table())) {
  367: 	    my $errorstring=&Apache::lonmysql::get_error();
  368:             &Apache::lonnet::logthis('lonsearchcat.pm: Unable to create '.
  369:                                      'needed table.  lonmysql error:'.
  370:                                      $errorstring);
  371:             $r->print(<<END);
  372: <html><head><title>Search Error</title></head>
  373: $bodytag
  374: Unable to create table in which to store search results.  
  375: The search has been aborted.
  376: </body>
  377: </html>
  378: END
  379:             return OK;
  380:         }
  381:         delete($ENV{'form.launch'});
  382:         if (! &make_form_data_persistent($r,$persistent_db_file)) {
  383:             $r->print(<<END);
  384: <html><head><title>Search Error</title></head>
  385: $bodytag
  386: Unable to properly store search information.  The search has been aborted.
  387: </body>
  388: </html>
  389: END
  390:             return OK;
  391:         }
  392:         ##
  393:         ## Print out the frames interface
  394:         ##
  395:         if (defined($query)) {
  396:             &print_frames_interface($r);
  397:         }
  398:     }
  399:     return OK;
  400: } 
  401: 
  402: #
  403: # The mechanism used to store values away and retrieve them does not
  404: # handle the case of missing environment variables being significant.
  405: #
  406: # This routine sets non existant checkbox form elements to ''.
  407: #
  408: sub clean_up_environment {
  409:     if ($ENV{'form.phase'} eq 'basic_search') {
  410:         if (! exists($ENV{'form.related'})) {
  411:             $ENV{'form.related'} = '';
  412:         }
  413:         if (! exists($ENV{'form.domains'})) {
  414:             $ENV{'form.domains'} = '';
  415:         }
  416:     } elsif ($ENV{'form.phase'} eq 'adv_search') {
  417:         foreach my $field ('title','keywords','notes',
  418:                            'abstract','standards','mime') {
  419:             if (! exists($ENV{'form.'.$field.'_related'})) {
  420:                 $ENV{'form.'.$field.'_related'} = '';
  421:             }
  422:         }
  423:     } elsif ($ENV{'form.phase'} eq 'course_search') {
  424:         if (! exists($ENV{'form.crsrelated'})) {
  425:             $ENV{'form.crsrelated'} = '';
  426:         }
  427:     }
  428: }
  429: 
  430: sub hidden_field {
  431:     my ($name,$value) = @_;
  432:     if (! defined($value)) {
  433:         $value = $ENV{'form.'.$name};
  434:     }
  435:     return '<input type="hidden" name="'.$name.'" value="'.$value.'" />'.$/;
  436: }
  437: 
  438: ######################################################################
  439: ######################################################################
  440: ##
  441: ##   Course Search
  442: ##
  443: ######################################################################
  444: ######################################################################
  445: {   # Scope the course search to avoid global variables
  446: #
  447: # Variables For course search
  448: my %alreadyseen;
  449: my %hash;
  450: my $totalfound;
  451: 
  452: sub course_search {
  453:     my $r=shift;
  454:     my $bodytag=&Apache::loncommon::bodytag('Course Search');
  455:     my $pretty_search_string = '<b>'.$ENV{'form.courseexp'}.'</b>';
  456:     my $search_string = $ENV{'form.courseexp'};
  457:     my @New_Words;
  458:     if ($ENV{'form.crsrelated'}) {
  459:         ($search_string,@New_Words) = &related_version($ENV{'form.courseexp'});
  460:         if (@New_Words) {
  461:             $pretty_search_string .= ' '.&mt("with related words").": <b>@New_Words</b>.";
  462:         } else {
  463:             $pretty_search_string .= ' '.&mt('with no related words').".";
  464:         }
  465:     }
  466:     my $fulltext=$ENV{'form.crsfulltext'};
  467:     my $discuss=$ENV{'form.crsdiscuss'};
  468:     my @allwords=($search_string,@New_Words);
  469:     $totalfound=0;
  470:     $r->print('<html><head><title>LON-CAPA Course Search</title></head>'.
  471: 	      $bodytag.'<hr /><center><font size="+2" face="arial">'.$pretty_search_string.'</font></center><hr /><b>'.&mt('Course content').':</b><br />');
  472:     $r->rflush();
  473: # ======================================================= Go through the course
  474:     undef %alreadyseen;
  475:     %alreadyseen=();
  476:     my $c=$r->connection;
  477:     if (tie(%hash,'GDBM_File',$ENV{'request.course.fn'}.".db",
  478:             &GDBM_READER(),0640)) {
  479:         foreach (keys %hash) {
  480:             if ($c->aborted()) { last; }
  481:             if (($_=~/^src\_(.+)$/) && (!$alreadyseen{$hash{$_}})) {
  482:                 &checkonthis($r,$hash{$_},0,$hash{'title_'.$1},$fulltext,
  483:                              @allwords);
  484:             }
  485:         }
  486:         untie(%hash);
  487:     }
  488:     unless ($totalfound) {
  489: 	$r->print('<p>'.&mt('No matches found in resources').'.</p>');
  490:     }
  491: 
  492: # Check discussions if requested
  493:     if ($discuss) {
  494:         my $totaldiscussions = 0;
  495:         $r->print('<br /><br /><b>'.&mt('Discussion postings').':</b><br />'); 
  496:         my $navmap = Apache::lonnavmaps::navmap->new();
  497:         my @allres=$navmap->retrieveResources();
  498:         my %discussiontime = &Apache::lonnet::dump('discussiontimes',
  499:                                $ENV{'course.'.$ENV{'request.course.id'}.'.domain'},
  500:                                $ENV{'course.'.$ENV{'request.course.id'}.'.num'});
  501:         foreach my $resource (@allres) {
  502:             my $result = '';
  503:             my $applies = 0;
  504:             my $symb = $resource->symb();
  505:             my $ressymb = $symb;
  506:             if ($symb =~ m#(___adm/\w+/\w+)/(\d+)/bulletinboard$#) {
  507:                 $ressymb = 'bulletin___'.$2.$1.'/'.$2.'/bulletinboard';
  508:                 unless ($ressymb =~ m#bulletin___\d+___adm/wrapper#) {
  509:                     $ressymb=~s#(bulletin___\d+___)#$1adm/wrapper/#;
  510:                 }
  511:             }
  512:             if (defined($discussiontime{$ressymb})) { 
  513:                 my %contrib = &Apache::lonnet::restore($ressymb,$ENV{'request.course.id'},
  514:                      $ENV{'course.'.$ENV{'request.course.id'}.'.domain'},
  515:                      $ENV{'course.'.$ENV{'request.course.id'}.'.num'});
  516:                 if ($contrib{'version'}) {
  517:                     for (my $id=1;$id<=$contrib{'version'};$id++) {
  518:                         unless (($contrib{'hidden'}=~/\.$id\./) || ($contrib{'deleted'}=~/\.$id\./)) { 
  519:                             if ($contrib{$id.':subject'}) {
  520:                                 $result .= $contrib{$id.':subject'};
  521:                             }
  522:                             if ($contrib{$id.':message'}) {
  523:                                 $result .= $contrib{$id.':message'};
  524:                             }
  525:                             if ($contrib{$id,':attachmenturl'}) {
  526:                                 if ($contrib{$id,':attachmenturl'} =~ m-/([^/]+)$-) {
  527:                                     $result .= $1;
  528:                                 }
  529:                             }
  530:                             $applies = &checkwords($result,$applies,@allwords);
  531:                         }
  532:                     }
  533:                 }
  534:             }
  535: # Does this discussion apply?
  536:             if ($applies) {
  537:                 my ($map,$ind,$url)=&Apache::lonnet::decode_symb($ressymb);
  538:                 my $disctype = &mt('resource');
  539:                 if ($url =~ m#/bulletinboard$#) {
  540:                     if ($url =~m#^adm/wrapper/adm/.*/bulletinboard$#) {
  541:                         $url =~s#^adm/wrapper##;
  542:                     }
  543:                     $disctype = &mt('bulletin board');
  544:                 } else {
  545:                     $url = '/res/'.$url;
  546:                 }
  547:                 if ($url =~ /\?/) {
  548:                     $url .= '&symb=';
  549:                 } else {
  550:                     $url .= '?symb=';
  551:                 }
  552:                 $url .= &Apache::lonnet::escape($resource->symb());
  553:                 my $title = $resource->compTitle();
  554:                 $r->print('<br /><a href="'.$url.'" target="cat">'.
  555:                      ($title?$title:$url).'</a>&nbsp;&nbsp;-&nbsp;'.$disctype.'<br />');
  556:                 $totaldiscussions++;
  557:             } else {
  558:                 $r->print(' .');
  559:             }
  560:         }
  561:         unless ($totaldiscussions) {
  562:             $r->print('<p>'.&mt('No matches found in postings').'.</p>');
  563:         }
  564:     }
  565:  
  566: # =================================================== Done going through course
  567:     $r->print('</body></html>');
  568: }
  569: 
  570: # =============================== This pulls up a resource and its dependencies
  571: 
  572: sub checkonthis {
  573:     my ($r,$url,$level,$title,$fulltext,@allwords)=@_;
  574:     $alreadyseen{$url}=1;
  575:     $r->rflush();
  576:     my $result=&Apache::lonnet::metadata($url,'title').' '.
  577:                &Apache::lonnet::metadata($url,'subject').' '.
  578:                &Apache::lonnet::metadata($url,'abstract').' '.
  579:                &Apache::lonnet::metadata($url,'keywords');
  580:     if (($url) && ($fulltext)) {
  581: 	$result.=&Apache::lonnet::ssi_body($url);
  582:     }
  583:     $result=~s/\s+/ /gs;
  584:     my $applies = 0;
  585:     $applies = &checkwords($result,$applies,@allwords);
  586: # Does this resource apply?
  587:     if ($applies) {
  588:        $r->print('<br />');
  589:        for (my $i=0;$i<=$level*5;$i++) {
  590:            $r->print('&nbsp;');
  591:        }
  592:        $r->print('<a href="'.$url.'" target="cat">'.
  593: 		 ($title?$title:$url).'</a><br />');
  594:        $totalfound++;
  595:     } elsif ($fulltext) {
  596:        $r->print(' .');
  597:     }
  598:     $r->rflush();
  599: # Check also the dependencies of this one
  600:     my $dependencies=
  601:                 &Apache::lonnet::metadata($url,'dependencies');
  602:     foreach (split(/\,/,$dependencies)) {
  603:        if (($_=~/^\/res\//) && (!$alreadyseen{$_})) {
  604:           &checkonthis($r,$_,$level+1,'',$fulltext,@allwords);
  605:        }
  606:     }
  607: }
  608: 
  609: sub checkwords {
  610:     my ($result,$applies,@allwords) = @_;
  611:     foreach (@allwords) {
  612:         if ($_=~/\w/) {
  613:             if ($result=~/$_/si) {
  614:                 $applies++;
  615:             }
  616:         }
  617:     }
  618:     return $applies;
  619: }
  620: 
  621: sub untiehash {
  622:     if (tied(%hash)) {
  623:         untie(%hash);
  624:     }
  625: }
  626: 
  627: } # End of course search scoping
  628: 
  629: sub search_html_header {
  630:     my $Str = <<ENDHEADER;
  631: <html>
  632: <head>
  633: <title>The LearningOnline Network with CAPA</title>
  634: </head>
  635: ENDHEADER
  636:     return $Str;
  637: }
  638: 
  639: ######################################################################
  640: ######################################################################
  641: 
  642: =pod 
  643: 
  644: =item &print_basic_search_form() 
  645: 
  646: Prints the form for the basic search.  Sorry the name is so cryptic.
  647: 
  648: =cut
  649: 
  650: ######################################################################
  651: ######################################################################
  652: sub print_basic_search_form {
  653:     my ($r,$closebutton,$hidden_fields) = @_;
  654:     my $result = ($ENV{'form.catalogmode'} ne 'groupsearch');
  655:     my $bodytag=&Apache::loncommon::bodytag('Search').
  656:         &Apache::lonhtmlcommon::breadcrumbs(undef,'Searching','Search_Basic',
  657:                                    undef,undef,
  658:                                    $ENV{'form.catalogmode'} ne 'groupsearch');
  659:     my $scrout = &search_html_header().$bodytag;
  660:     if (&Apache::lonnet::allowed('bre',$ENV{'request.role.domain'})) {
  661:         # Define interface components
  662:         my $userelatedwords= '<label>'.
  663:             &mt('[_1] use related words',
  664:                 &Apache::lonhtmlcommon::checkbox
  665:                 ('related',$ENV{'form.related'},'related')).'</label>';
  666:         my $onlysearchdomain='<label>'.
  667:             &mt('[_1] only search domain [_2]',
  668:                 &Apache::lonhtmlcommon::checkbox('domains',
  669:                                                  $ENV{'form.domains'},
  670:                                                  $r->dir_config('lonDefDomain')
  671:                                                  ),
  672:                 $r->dir_config('lonDefDomain')
  673:                 ).'</label>';
  674:         my $adv_search_link = 
  675:             '<a href="/adm/searchcat?'.
  676:             'phase=disp_adv&'.
  677:             'catalogmode='.$ENV{'form.catalogmode'}.
  678:             '&launch='.$ENV{'form.launch'}.
  679:             '&mode='.$ENV{'form.mode'}.
  680:             '">'.&mt('Advanced Search').'</a>';
  681:         #
  682:         $scrout.='<form name="loncapa_search" method="post" '.
  683:             'action="/adm/searchcat">'.
  684:             '<input type="hidden" name="phase" value="basic_search" />'.
  685:             $hidden_fields;
  686:         #
  687:         $scrout .= '<center>'.$/;
  688:         if ($ENV{'request.course.id'}) {
  689:             $scrout .= '<h1>'.&mt('LON-CAPA Catalog Search').'</h1>';
  690:         } else {
  691:             # No need to tell them they are searching
  692:             $scrout.= ('<br />'x2);
  693:         }
  694:         $scrout.='<table>'.
  695:             '<tr><td align="center" valign="top">'.
  696:             &Apache::lonhtmlcommon::textbox
  697:             ('basicexp',
  698:              &HTML::Entities::encode($ENV{'form.basicexp'},'<>&"'),50
  699:              ).
  700:              '<br />'.
  701:             '<font size="-1">'.&searchhelp().'</font>'.'</td>'.
  702:             '<td><font size="-1">'.
  703:             '<nobr>'.('&nbsp;'x3).$adv_search_link.'</nobr>'.'<br />'.
  704:             '<nobr>'.('&nbsp;'x1).$userelatedwords.'</nobr>'.'<br />'.
  705:             '<nobr>'.('&nbsp;'x1).$onlysearchdomain.'</nobr>'.'<br />'.
  706:             '</font></td>'.
  707:             '</tr>'.$/;
  708:         #
  709:         $scrout .= '<tr><td align="center" colspan="2">'.
  710:             '<font size="-1">'.
  711:             '<input type="submit" name="basicsubmit" '.
  712:             'value="'.&mt('Search').'" />'.
  713:             ('&nbsp;'x2).$closebutton.('&nbsp;'x2).
  714:             &viewoptions().
  715:             '</font>'.
  716:             '</td></tr>'.$/;
  717:         $scrout .= '</table>'.$/.'</center>'.'</form>';
  718:     }
  719:     if ($ENV{'request.course.id'}) {
  720: 	my %lt=&Apache::lonlocal::texthash('srch' => 'Search',
  721:                                            'header' => 'Course Search',
  722: 	 'note' => 'Enter terms or phrases, then press "Search" below',
  723: 	 'use' => 'use related words',
  724: 	 'full' =>'fulltext search (time consuming)',
  725:          'disc' => 'search discussion postings (resources and bulletin boards)',
  726: 					   );
  727:         $scrout.=(<<ENDCOURSESEARCH);
  728: <form name="loncapa_search" method="post" action="/adm/searchcat">
  729: <center>
  730: <hr />
  731: <h1>$lt{'header'}</h1>    
  732: <input type="hidden" name="phase" value="course_search" />
  733: $hidden_fields
  734: <p>
  735: $lt{'note'}.
  736: </p>
  737: <p>
  738: <table>
  739: <tr><td>
  740: ENDCOURSESEARCH
  741:         $scrout.='&nbsp;'.
  742:             &Apache::lonhtmlcommon::textbox('courseexp',
  743:                                   $ENV{'form.courseexp'},40);
  744:         my $crscheckbox = 
  745:             &Apache::lonhtmlcommon::checkbox('crsfulltext',
  746:                                    $ENV{'form.crsfulltext'});
  747:         my $relcheckbox = 
  748:             &Apache::lonhtmlcommon::checkbox('crsrelated',
  749: 				   $ENV{'form.crsrelated'});
  750:         my $discheckbox = 
  751:             &Apache::lonhtmlcommon::checkbox('crsdiscuss',
  752:                                    $ENV{'form.crsrelated'});
  753:         $scrout.=(<<ENDENDCOURSE);
  754: </td></tr>
  755: <tr><td><label>$relcheckbox $lt{'use'}</label></td><td></td></tr>
  756: <tr><td><label>$crscheckbox $lt{'full'}</label></td><td></td></tr>
  757: <tr><td><label>$discheckbox $lt{'disc'}</label></td><td></td></tr>
  758: </table><p>
  759: &nbsp;<input type="submit" name="coursesubmit" value='$lt{'srch'}' />
  760: </p>
  761: </center>
  762: </form>
  763: ENDENDCOURSE
  764:     }
  765:     $scrout.=(<<ENDDOCUMENT);
  766: </body>
  767: </html>
  768: ENDDOCUMENT
  769:     $r->print($scrout);
  770:     return;
  771: }
  772: ######################################################################
  773: ######################################################################
  774: 
  775: =pod 
  776: 
  777: =item &advanced_search_form() 
  778: 
  779: Prints the advanced search form.
  780: 
  781: =cut
  782: 
  783: ######################################################################
  784: ######################################################################
  785: sub print_advanced_search_form{
  786:     my ($r,$closebutton,$hidden_fields) = @_;
  787:     my $bodytag=&Apache::loncommon::bodytag('Advanced Catalog Search').
  788:         &Apache::lonhtmlcommon::breadcrumbs(undef,'Searching',
  789:                                             'Search_Advanced',
  790:                                             undef,undef,
  791:                                   $ENV{'form.catalogmode'} ne 'groupsearch');
  792:     my %lt=&Apache::lonlocal::texthash('srch' => 'Search',
  793: 				       'reset' => 'Reset',
  794: 				       'help' => 'Help');
  795:     my $advanced_buttons=<<"END";
  796: <input type="submit" name="advancedsubmit" value='$lt{"srch"}' />
  797: <input type="reset" name="reset" value='$lt{"reset"}' />
  798: $closebutton
  799: END
  800:     my $scrout=&search_html_header();
  801:     $scrout .= <<"ENDHEADER";
  802: $bodytag
  803: <form method="post" action="/adm/searchcat" name="advsearch">
  804: <p>
  805: $advanced_buttons
  806: ENDHEADER
  807:     $scrout.=('&nbsp;'x2).&viewoptions().'</p>'.$hidden_fields. 
  808:         '<input type="hidden" name="phase" value="adv_search" />';
  809:     my %fields=&Apache::lonmeta::fieldnames();
  810:     #
  811:     $scrout .= '<h3>'.&mt('Standard Metadata').'</h3>';
  812:     $scrout .= "<table>\n";
  813:     $scrout .= '<tr><td>&nbsp;</td><td colspan="2"><font size="-1">'.
  814:         ('&nbsp;'x2).&searchhelp()."</font></td></tr>\n";
  815:     my %related_word_search = 
  816:         ('title'    => 1,
  817:          'author'   => 0,
  818:          'owner'    => 0,
  819:          'authorspace'  => 0,
  820:          'modifyinguser'=> 0,
  821:          'keywords' => 1,
  822:          'notes'    => 1,
  823:          'abstract' => 1,
  824:          'standards'=> 1,
  825:          'mime'     => 1,
  826:          );
  827:     #
  828:     foreach my $field ('title','author','owner','authorspace','modifyinguser',
  829: 	     'keywords','notes','abstract','standards','mime') {
  830: 	$scrout.='<tr><td align="right">'.&titlefield($fields{$field}).'</td><td>'.
  831: 	    &Apache::lonmeta::prettyinput($field,
  832:                                           $ENV{'form.'.$field},
  833:                                           $field,
  834:                                           'advsearch',
  835: 					  $related_word_search{$field},
  836:                                           '</td><td align="left">',
  837:                                           $ENV{'form.'.$field.'_related'},
  838:                                           50);
  839:         if ($related_word_search{$field}) {
  840:             $scrout .= 'related words';
  841:         } else {
  842:             $scrout .= '</td><td>&nbsp;';
  843:         }
  844:         $scrout .= '</td></tr>'.$/;
  845:     }
  846:     foreach my $field ('lowestgradelevel','highestgradelevel') {
  847: 	$scrout.='<tr>'.
  848:             '<td align="right">'.&titlefield($fields{$field}).'</td>'.
  849:             '<td colspan="2">'.
  850: 	    &Apache::lonmeta::prettyinput($field,
  851:                                           $ENV{'form.'.$field},
  852:                                           $field,
  853:                                           'advsearch',
  854: 					  0).
  855:                                           '</td></tr>'.$/;
  856:     }
  857:     $scrout.='<tr><td align="right">'.
  858: 	&titlefield(&mt('MIME Type Category')).'</td><td colspan="2">'. 
  859: 	    &Apache::loncommon::filecategoryselect('category',
  860: 						   $ENV{'form.category'}).
  861: 	    '</td></tr>'.$/;
  862:     $scrout.='<tr><td align="right" valign="top">'.
  863: 	&titlefield(&mt('Domains')).'</td><td colspan="2">'. 
  864: 	    &Apache::loncommon::domain_select('domains',
  865: 						   $ENV{'form.domains'},1).
  866: 	    '</td></tr>'.$/;
  867:     #
  868:     # Misc metadata
  869:     $scrout.='<tr><td align="right" valign="top">'.
  870: 	&titlefield(&mt('Copyright/Distribution')).'</td><td colspan="2">'.
  871:         &Apache::lonmeta::selectbox('copyright',
  872:                                     $ENV{'form.copyright'},
  873:                                     \&Apache::loncommon::copyrightdescription,
  874:                                     ( undef,
  875:                                       &Apache::loncommon::copyrightids)
  876:                                     ).'</td></tr>'.$/;
  877:     $scrout.='<tr><td align="right" valign="top">'.
  878: 	&titlefield(&mt('Language')).'</td><td colspan="2">'.
  879:         &Apache::lonmeta::selectbox('language',
  880:                                     $ENV{'form.language'},
  881:                                     \&Apache::loncommon::languagedescription,
  882:                                     ('any',&Apache::loncommon::languageids)
  883:                                     ).'</td></tr>';
  884:     $scrout .= "</table>\n";    
  885:     #
  886:     # Dynamic metadata
  887:     $scrout .= '<h3>'.&mt('Problem Statistics').'</h3>';
  888:     $scrout .= "<table>\n";
  889:     $scrout .= '<tr><td>&nbsp;</td><td align="center">'.&mt('Minimum').'</td>'.
  890:         '<td align="center">'.&mt('Maximum').'</td></tr>'."\n";
  891:     foreach my $statistic 
  892:         ({ name=>'count',
  893:            description=>'Network-wide number of accesses (hits)',},
  894:          { name=>'stdno',
  895:            description=>
  896:                'Total number of students who have worked on this problem',},
  897:          { name => 'avetries',
  898:            description=>'Average number of tries till solved',},
  899:          { name => 'difficulty',
  900:            description=>'Degree of difficulty',},
  901:          { name => 'disc',
  902:            description=>'Degree of discrimination'}) {
  903:         $scrout .= '<tr><td align="right">'.
  904:             &titlefield(&mt($statistic->{'description'})).
  905:             '</td><td align="center">'.
  906:             '<input type="text" name="'.$statistic->{'name'}.'_min" '.
  907:             'value="" size="6" />'.
  908:             '</td><td align="center">'.
  909:             '<input type="text" name="'.$statistic->{'name'}.'_max" '.
  910:             'value="" size="6" />'.
  911:             '</td></tr>'.$/;
  912:     }
  913:     $scrout .= "</table>\n";
  914:     $scrout .= '<h3>'.&mt('Evaluation Data').'</h3>';
  915:     $scrout .= "<table>\n";
  916:     $scrout .= '<tr><td>&nbsp;</td><td align="center">'.&mt('Minimum').'</td>'.
  917:         '<td align="center">'.&mt('Maximum').'</td></tr>'."\n";
  918:     foreach my $evaluation
  919:         ( { name => 'clear',
  920:             description => 'Material presented in clear way'},
  921:           { name =>'depth',
  922:             description => 'Material covered with sufficient depth'},
  923:           { name => 'helpful',
  924:             description => 'Material is helpful'},
  925:           { name => 'correct',
  926:             description => 'Material appears to be correct'},
  927:           { name => 'technical',
  928:             description => 'Resource is technically correct'}){
  929:         $scrout .= '<tr><td align="right">'.
  930:             &titlefield(&mt($evaluation->{'description'})).
  931:             '</td><td align="center">'.
  932:             '<input type="text" name="'.$evaluation->{'name'}.'_min" '.
  933:             'value="" size="6" />'.
  934:             '</td><td align="center">'.
  935:             '<input type="text" name="'.$evaluation->{'name'}.'_max" '.
  936:             'value="" size="6" />'.
  937:             '</td></tr>'.$/;
  938:     }
  939:     $scrout .= "</table>\n";
  940:     #
  941:     # Creation/Modification date limits
  942:     $scrout .= '<h3>'.&mt('Creation and Modification dates').'</h3>';
  943:     $scrout .= "\n<table>\n";
  944:     my $cafter = 
  945:         &Apache::lonhtmlcommon::date_setter('advsearch',         # formname
  946:                                             'creationdate1', # fieldname
  947:                                             0,           # current value
  948:                                             '',          # special 
  949:                                             1,           # includeempty
  950:                                             '',          # state
  951:                                             1,           # no_hh_mm_ss
  952:                                             );
  953:     my $cbefore = 
  954:         &Apache::lonhtmlcommon::date_setter('advsearch',         # formname
  955:                                             'creationdate2', # fieldname
  956:                                             0,           # current value
  957:                                             '',          # special 
  958:                                             1,           # includeempty
  959:                                             '',          # state
  960:                                             1,           # no_hh_mm_ss
  961:                                             );
  962:     $scrout .= &mt('<tr><td align="right">Created between</td>'.
  963:                    '<td>[_1]</td></tr>'.
  964:                    '<tr><td align="right">and </td>'.
  965:                    '<td>[_2]</td></tr>',$cafter,$cbefore);
  966:     my $lafter = 
  967:         &Apache::lonhtmlcommon::date_setter('advsearch',
  968:                                             'revisiondate1', 
  969:                                             0,           # current value
  970:                                             '',          # special 
  971:                                             1,           # includeempty
  972:                                             '',          # state
  973:                                             1,           # no_hh_mm_ss
  974:                                             );
  975:     my $lbefore = 
  976:         &Apache::lonhtmlcommon::date_setter('advsearch',
  977:                                             'revisiondate2',
  978:                                             0,           # current value
  979:                                             '',          # special 
  980:                                             1,           # includeempty
  981:                                             '',          # state
  982:                                             1,           # no_hh_mm_ss
  983:                                             );
  984:     $scrout .= &mt('<tr><td align="right">Last modified between </td>'.
  985:                    '<td>[_1]</td></tr>'.
  986:                    '<tr><td align="right">and</td>'.
  987:                    '<td>[_2]</td></tr>',$lafter,$lbefore);
  988:     $scrout.="</table>\n";
  989:     $scrout.=<<ENDDOCUMENT;
  990: $advanced_buttons
  991: </form>
  992: </body>
  993: </html>
  994: ENDDOCUMENT
  995:     $r->print($scrout);
  996:     return;
  997: }
  998: 
  999: ######################################################################
 1000: ######################################################################
 1001: 
 1002: =pod 
 1003: 
 1004: =item &titlefield()
 1005: 
 1006: Inputs: title text
 1007: 
 1008: Outputs: titletext with font wrapper
 1009: 
 1010: =cut
 1011: 
 1012: ######################################################################
 1013: ######################################################################
 1014: sub titlefield {
 1015:     my $title=shift;
 1016:     return $title;
 1017: }
 1018: 
 1019: ######################################################################
 1020: ######################################################################
 1021: 
 1022: =pod 
 1023: 
 1024: =item viewoptiontext()
 1025: 
 1026: Inputs: codename for view option
 1027: 
 1028: Outputs: displayed text
 1029: 
 1030: =cut
 1031: 
 1032: ######################################################################
 1033: ######################################################################
 1034: sub viewoptiontext {
 1035:     my $code=shift;
 1036:     my %desc=&Apache::lonlocal::texthash
 1037:         ('detailed' => "Detailed Citation View",
 1038:          'xml' => 'XML/SGML',
 1039:          'compact' => 'Compact View',
 1040:          'fielded' => 'Fielded Format',
 1041:          'summary' => 'Summary View');
 1042:     return $desc{$code};
 1043: }
 1044: 
 1045: ######################################################################
 1046: ######################################################################
 1047: 
 1048: =pod 
 1049: 
 1050: =item viewoptions()
 1051: 
 1052: Inputs: none
 1053: 
 1054: Outputs: text for box with view options
 1055: 
 1056: =cut
 1057: 
 1058: ######################################################################
 1059: ######################################################################
 1060: sub viewoptions {
 1061:     my $scrout;
 1062:     if (! defined($ENV{'form.viewselect'})) { 
 1063:         $ENV{'form.viewselect'}='detailed'; 
 1064:     }
 1065:     $scrout.=&Apache::lonmeta::selectbox('viewselect',
 1066: 			$ENV{'form.viewselect'},
 1067: 			\&viewoptiontext,
 1068: 			sort(keys(%Views)));
 1069:     $scrout.= '&nbsp;&nbsp;';
 1070:     my $countselect = &Apache::lonmeta::selectbox('show',
 1071:                                                   $ENV{'form.show'},
 1072:                                                   undef,
 1073:                                                   (10,20,50,100,1000,10000));
 1074:     $scrout .= ('&nbsp;'x2).&mt('[_1] Records per Page',$countselect).
 1075:         '</nobr>'.$/;
 1076:     return $scrout;
 1077: }
 1078: 
 1079: ######################################################################
 1080: ######################################################################
 1081: 
 1082: =pod 
 1083: 
 1084: =item searchhelp()
 1085: 
 1086: Inputs: none
 1087: 
 1088: Outputs: return little blurb on how to enter searches
 1089: 
 1090: =cut
 1091: 
 1092: ######################################################################
 1093: ######################################################################
 1094: sub searchhelp {
 1095:     return &mt('Enter words and quoted phrases');
 1096: }
 1097: 
 1098: ######################################################################
 1099: ######################################################################
 1100: 
 1101: =pod 
 1102: 
 1103: =item &get_persistent_form_data()
 1104: 
 1105: Inputs: filename of database
 1106: 
 1107: Outputs: returns undef on database errors.
 1108: 
 1109: This function is the reverse of &make_persistent() for form data.
 1110: Retrieve persistent data from %persistent_db.  Retrieved items will have their
 1111: values unescaped.  If a form value already exists in $ENV, it will not be
 1112: overwritten.  Form values that are array references may have values appended
 1113: to them.
 1114: 
 1115: =cut
 1116: 
 1117: ######################################################################
 1118: ######################################################################
 1119: sub get_persistent_form_data {
 1120:     my $filename = shift;
 1121:     return 0 if (! -e $filename);
 1122:     return undef if (! tie(%persistent_db,'GDBM_File',$filename,
 1123:                            &GDBM_READER(),0640));
 1124:     #
 1125:     # These make sure we do not get array references printed out as 'values'.
 1126:     my %arrays_allowed = ('form.domains'=>1);
 1127:     #
 1128:     # Loop through the keys, looking for 'form.'
 1129:     foreach my $name (keys(%persistent_db)) {
 1130:         next if ($name !~ /^form./);
 1131:         # Kludgification begins!
 1132:         if ($name eq 'form.domains' && 
 1133:             $ENV{'form.searchmode'} eq 'basic' &&
 1134:             $ENV{'form.phase'} ne 'disp_basic') {
 1135:             next;
 1136:         }
 1137:         # End kludge (hopefully)
 1138:         next if (exists($ENV{$name}));
 1139:         my @values = map { 
 1140:             &Apache::lonnet::unescape($_);
 1141:         } split(',',$persistent_db{$name});
 1142:         next if (@values <1);
 1143:         if ($arrays_allowed{$name}) {
 1144:             $ENV{$name} = [@values];
 1145:         } else {
 1146:             $ENV{$name} = $values[0] if ($values[0]);
 1147:         }
 1148:     }
 1149:     untie (%persistent_db);
 1150:     return 1;
 1151: }
 1152: 
 1153: ######################################################################
 1154: ######################################################################
 1155: 
 1156: =pod 
 1157: 
 1158: =item &get_persistent_data()
 1159: 
 1160: Inputs: filename of database, ref to array of values to recover.
 1161: 
 1162: Outputs: array of values.  Returns undef on error.
 1163: 
 1164: This function is the reverse of &make_persistent();
 1165: Retrieve persistent data from %persistent_db.  Retrieved items will have their
 1166: values unescaped.  If the item contains commas (before unescaping), the
 1167: returned value will be an array pointer. 
 1168: 
 1169: =cut
 1170: 
 1171: ######################################################################
 1172: ######################################################################
 1173: sub get_persistent_data {
 1174:     my $filename = shift;
 1175:     my @Vars = @{shift()};
 1176:     my @Values;   # Return array
 1177:     return undef if (! -e $filename);
 1178:     return undef if (! tie(%persistent_db,'GDBM_File',$filename,
 1179:                            &GDBM_READER(),0640));
 1180:     foreach my $name (@Vars) {
 1181:         if (! exists($persistent_db{$name})) {
 1182:             push @Values, undef;
 1183:             next;
 1184:         }
 1185:         my @values = map { 
 1186:             &Apache::lonnet::unescape($_);
 1187:         } split(',',$persistent_db{$name});
 1188:         if (@values <= 1) {
 1189:             push @Values,$values[0];
 1190:         } else {
 1191:             push @Values,\@values;
 1192:         }
 1193:     }
 1194:     untie (%persistent_db);
 1195:     return @Values;
 1196: }
 1197: 
 1198: ######################################################################
 1199: ######################################################################
 1200: 
 1201: =pod 
 1202: 
 1203: =item &make_persistent() 
 1204: 
 1205: Inputs: Hash of values to save, filename of persistent database.
 1206: 
 1207: Store variables away to the %persistent_db.
 1208: Values will be escaped.  Values that are array pointers will have their
 1209: elements escaped and concatenated in a comma separated string.  
 1210: 
 1211: =cut
 1212: 
 1213: ######################################################################
 1214: ######################################################################
 1215: sub make_persistent {
 1216:     my %save = %{shift()};
 1217:     my $filename = shift;
 1218:     return undef if (! tie(%persistent_db,'GDBM_File',
 1219:                            $filename,&GDBM_WRCREAT(),0640));
 1220:     foreach my $name (keys(%save)) {
 1221:         my @values = (ref($save{$name}) ? @{$save{$name}} : ($save{$name}));
 1222:         # We handle array references, but not recursively.
 1223:         my $store = join(',', map { &Apache::lonnet::escape($_); } @values );
 1224:         $persistent_db{$name} = $store;
 1225:     }
 1226:     untie(%persistent_db);
 1227:     return 1;
 1228: }
 1229: 
 1230: ######################################################################
 1231: ######################################################################
 1232: 
 1233: =pod 
 1234: 
 1235: =item &make_form_data_persistent() 
 1236: 
 1237: Inputs: filename of persistent database.
 1238: 
 1239: Store most form variables away to the %persistent_db.
 1240: Values will be escaped.  Values that are array pointers will have their
 1241: elements escaped and concatenated in a comma separated string.  
 1242: 
 1243: =cut
 1244: 
 1245: ######################################################################
 1246: ######################################################################
 1247: sub make_form_data_persistent {
 1248:     my $r = shift;
 1249:     my $filename = shift;
 1250:     my %save;
 1251:     foreach (keys(%ENV)) {
 1252:         next if (!/^form/ || /submit/);
 1253:         $save{$_} = $ENV{$_};
 1254:     }
 1255:     return &make_persistent(\%save,$filename);
 1256: }
 1257: 
 1258: ######################################################################
 1259: ######################################################################
 1260: 
 1261: =pod 
 1262: 
 1263: =item &parse_advanced_search()
 1264: 
 1265: Parse advanced search form and return the following:
 1266: 
 1267: =over 4
 1268: 
 1269: =item $query Scalar containing an SQL query.
 1270: 
 1271: =item $customquery Scalar containing a custom query.
 1272: 
 1273: =item $customshow Scalar containing commands to show custom metadata.
 1274: 
 1275: =item $libraries_to_query Reference to array of domains to search.
 1276: 
 1277: =back
 1278: 
 1279: =cut
 1280: 
 1281: ######################################################################
 1282: ######################################################################
 1283: sub parse_advanced_search {
 1284:     my ($r,$closebutton,$hidden_fields)=@_;
 1285:     my @BasicFields = ('title','author','subject','keywords','url','version',
 1286:                        'notes','abstract','extension','owner','authorspace',
 1287: #                       'custommetadata','customshow',
 1288:                        'modifyinguser','standards','mime');
 1289:     my @StatsFields = &statfields();
 1290:     my @EvalFields = &evalfields();
 1291:     my $fillflag=0;
 1292:     my $pretty_search_string = "";
 1293:     # Clean up fields for safety
 1294:     for my $field (@BasicFields,
 1295:                    'creationdatestart_month','creationdatestart_day',
 1296: 		   'creationdatestart_year','creationdateend_month',
 1297: 		   'creationdateend_day','creationdateend_year',
 1298: 		   'lastrevisiondatestart_month','lastrevisiondatestart_day',
 1299: 		   'lastrevisiondatestart_year','lastrevisiondateend_month',
 1300: 		   'lastrevisiondateend_day','lastrevisiondateend_year') {
 1301: 	$ENV{'form.'.$field}=~s/[^\w\/\s\(\)\=\-\"\']//g;
 1302:     }
 1303:     foreach ('mode','form','element') {
 1304: 	# is this required?  Hmmm.
 1305: 	next if (! exists($ENV{'form.'.$_}));
 1306: 	$ENV{'form.'.$_}=&Apache::lonnet::unescape($ENV{'form.'.$_});
 1307: 	$ENV{'form.'.$_}=~s/[^\w\/\s\(\)\=\-\"\']//g;
 1308:     }
 1309:     # Preprocess the category form element.
 1310:     $ENV{'form.category'} = 'any' if (! defined($ENV{'form.category'}) ||
 1311:                                       ref($ENV{'form.category'}));
 1312:     #
 1313:     # Check to see if enough information was filled in
 1314:     foreach my $field (@BasicFields) {
 1315: 	if (&filled($ENV{'form.'.$field})) {
 1316: 	    $fillflag++;
 1317: 	}
 1318:     }
 1319:     foreach my $field (@StatsFields,@EvalFields) {
 1320:         if (&filled($ENV{'form.'.$field.'_max'})) {
 1321:             $fillflag++;
 1322:         }
 1323:         if (&filled($ENV{'form.'.$field.'_min'})) {
 1324:             $fillflag++;
 1325:         }
 1326:     }
 1327: 
 1328:     for my $field ('lowestgradelevel','highestgradelevel') {
 1329:         if ( $ENV{'form.'.$field} =~ /^\d+$/ &&
 1330:              $ENV{'form.'.$field} > 0) {
 1331:             $fillflag++;
 1332:         }
 1333:     }
 1334:     if (! $fillflag) {
 1335: 	&output_blank_field_error($r,$closebutton,
 1336:                                   'phase=disp_adv',$hidden_fields);
 1337: 	return ;
 1338:     }
 1339:     # Turn the form input into a SQL-based query
 1340:     my $query='';
 1341:     my @queries;
 1342:     my $font = '<font color="#800000" face="helvetica">';
 1343:     # Evaluate logical expression AND/OR/NOT phrase fields.
 1344:     foreach my $field (@BasicFields) {
 1345: 	next if (!defined($ENV{'form.'.$field}) || $ENV{'form.'.$field} eq '');
 1346:         my ($error,$SQLQuery) = 
 1347:             &process_phrase_input($ENV{'form.'.$field},
 1348:                                   $ENV{'form.'.$field.'_related'},$field);
 1349:         if (defined($error)) {
 1350:             &output_unparsed_phrase_error($r,$closebutton,'phase=disp_adv',
 1351:                                          $hidden_fields,$field);
 1352:             return;
 1353:         } else {
 1354:             $pretty_search_string .= 
 1355:                 $font.$field.'</font>: '.$ENV{'form.'.$field};
 1356:             if ($ENV{'form.'.$field.'_related'}) {
 1357:                 my @Words = 
 1358:                     &Apache::loncommon::get_related_words
 1359:                     ($ENV{'form.'.$field});
 1360:                 if (@Words) {
 1361:                     $pretty_search_string.= ' with related words: '.
 1362:                         join(', ',@Words[0..4]);
 1363:                 } else {
 1364:                     $pretty_search_string.= ' with related words.';
 1365:                 }
 1366:             }
 1367:             $pretty_search_string .= '<br />';
 1368:             push (@queries,$SQLQuery);
 1369:         }
 1370:     }
 1371:     #
 1372:     # Make the 'mime' from 'form.category' and 'form.extension'
 1373:     #
 1374:     my $searchphrase;
 1375:     if (exists($ENV{'form.category'})    && 
 1376:         $ENV{'form.category'} !~ /^\s*$/ &&
 1377:         $ENV{'form.category'} ne 'any')     {
 1378:         my @extensions = &Apache::loncommon::filecategorytypes
 1379:                                                    ($ENV{'form.category'});
 1380:         if (scalar(@extensions) > 0) {
 1381:             $searchphrase = join(' OR ',@extensions);
 1382:         }
 1383:     }
 1384:     if (defined($searchphrase)) {
 1385:         my ($error,$SQLsearch) = &process_phrase_input($searchphrase,0,'mime');
 1386:         push @queries,$SQLsearch;
 1387:         $pretty_search_string .=$font.'mime</font> contains <b>'.
 1388:             $searchphrase.'</b><br />';
 1389:     }
 1390:     #
 1391:     # Evaluate option lists
 1392:     if ($ENV{'form.lowestgradelevel'}        &&
 1393:         $ENV{'form.lowestgradelevel'} ne '0' &&
 1394:         $ENV{'form.lowestgradelevel'} =~ /^\d+$/) {
 1395: 	push(@queries,
 1396:              '(lowestgradelevel>='.$ENV{'form.lowestgradelevel'}.')');
 1397:         $pretty_search_string.="lowestgradelevel>=".
 1398:             $ENV{'form.lowestgradelevel'}."<br />\n";
 1399:     }
 1400:     if ($ENV{'form.highestgradelevel'}        &&
 1401:         $ENV{'form.highestgradelevel'} ne '0' &&
 1402:         $ENV{'form.highestgradelevel'} =~ /^\d+$/) {
 1403: 	push(@queries,
 1404:              '(highestgradelevel<='.$ENV{'form.highestgradelevel'}.')');
 1405:         $pretty_search_string.="highestgradelevel<=".
 1406:             $ENV{'form.highestgradelevel'}."<br />\n";
 1407:     }
 1408:     if ($ENV{'form.language'} and $ENV{'form.language'} ne 'any') {
 1409: 	push @queries,"(language like \"$ENV{'form.language'}\")";
 1410:         $pretty_search_string.=$font."language</font>= ".
 1411:             &Apache::loncommon::languagedescription($ENV{'form.language'}).
 1412:                 "<br />\n";
 1413:     }
 1414:     if ($ENV{'form.copyright'} and $ENV{'form.copyright'} ne 'any') {
 1415: 	push @queries,"(copyright like \"$ENV{'form.copyright'}\")";
 1416:         $pretty_search_string.=$font."copyright</font> = ".
 1417:             &Apache::loncommon::copyrightdescription($ENV{'form.copyright'}).
 1418:                 "<br />\n";
 1419:     }
 1420:     #
 1421:     # Statistics
 1422:     foreach my $field (@StatsFields,@EvalFields) {
 1423:         my ($min,$max);
 1424:         if (exists($ENV{'form.'.$field.'_min'}) && 
 1425:             $ENV{'form.'.$field.'_min'} ne '') {
 1426:             $min = $ENV{'form.'.$field.'_min'};
 1427:         }
 1428:         if (exists($ENV{'form.'.$field.'_max'}) &&
 1429:             $ENV{'form.'.$field.'_max'} ne '') {
 1430:             $max = $ENV{'form.'.$field.'_max'};
 1431:         }
 1432:         next if (! defined($max) && ! defined($min));
 1433:         if (defined($min) && defined($max)) {
 1434:             ($min,$max) = sort {$a <=>$b} ($min,$max);
 1435:         }
 1436:         if (defined($min) && $min =~ /^(\d+\.\d+|\d+|\.\d+)$/) {
 1437:             push(@queries,'('.$field.'>'.$min.')');
 1438:             $pretty_search_string.=$font.$field.'</font>&gt;'.$min.'<br />';
 1439:         }
 1440:         if (defined($max) && $max =~ /^(\d+\.\d+|\d+|\.\d+)$/) {
 1441:             push(@queries,'('.$field.'<'.$max.')');
 1442:             $pretty_search_string.=$font.$field.'</font>&lt;'.$max.'<br />';
 1443:         }
 1444:     }
 1445:     #
 1446:     # Evaluate date windows
 1447:     my $cafter =
 1448:         &Apache::lonhtmlcommon::get_date_from_form('creationdate1');
 1449:     my $cbefore = 
 1450:         &Apache::lonhtmlcommon::get_date_from_form('creationdate2');
 1451:     if ($cafter > $cbefore) {
 1452:         my $tmp = $cafter;
 1453:         $cafter = $cbefore;
 1454:         $cbefore = $tmp;
 1455:     }
 1456:     my $mafter = 
 1457:         &Apache::lonhtmlcommon::get_date_from_form('revisiondate1');
 1458:     my $mbefore =
 1459:         &Apache::lonhtmlcommon::get_date_from_form('revisiondate2');
 1460:     if ($mafter > $mbefore) {
 1461:         my $tmp = $mafter;
 1462:         $mafter = $mbefore;
 1463:         $mbefore = $tmp;
 1464:     }
 1465:     my ($datequery,$error,$prettydate)=&build_date_queries($cafter,$cbefore,
 1466:                                                            $mafter,$mbefore);
 1467:     if (defined($error)) {
 1468:         &output_date_error($r,$error,$closebutton,$hidden_fields);
 1469:     } elsif (defined($datequery)) {
 1470:         # Here is where you would set up pretty_search_string to output
 1471:         # date query information.
 1472:         $pretty_search_string .= '<br />'.$prettydate.'<br />';
 1473: 	push @queries,$datequery;
 1474:     }
 1475:     #
 1476:     # Process form information for custom metadata querying
 1477:     my $customquery=undef;
 1478:     ##
 1479:     ## The custom metadata search was removed q long time ago mostly 
 1480:     ## because I was unable to figureout exactly how it worked and could
 1481:     ## not imagine people actually using it.  MH
 1482:     ##
 1483:     # if ($ENV{'form.custommetadata'}) {
 1484:     #    $pretty_search_string .=$font."Custom Metadata Search</font>: <b>".
 1485:     #    $ENV{'form.custommetadata'}."</b><br />\n";
 1486:     #    $customquery=&build_custommetadata_query('custommetadata',
 1487:     #                                             $ENV{'form.custommetadata'});
 1488:     # }
 1489:     my $customshow=undef;
 1490:     # if ($ENV{'form.customshow'}) {
 1491:     # $pretty_search_string .=$font."Custom Metadata Display</font>: <b>".
 1492:     #                         $ENV{'form.customshow'}."</b><br />\n";
 1493:     #    $customshow=$ENV{'form.customshow'};
 1494:     #    $customshow=~s/[^\w\s]//g;
 1495:     #    my @fields=split(/\s+/,$customshow);
 1496:     #    $customshow=join(" ",@fields);
 1497:     # }
 1498:     ##
 1499:     ## Deal with restrictions to given domains
 1500:     ## 
 1501:     my ($libraries_to_query,$pretty_domains_string) = 
 1502:         &parse_domain_restrictions();
 1503:     $pretty_search_string .= $pretty_domains_string."<br />\n";
 1504:     #
 1505:     if (@queries) {
 1506: 	$query="SELECT * FROM metadata WHERE (".join(") AND (",@queries).')';
 1507:     } elsif ($customquery) {
 1508:         $query = '';
 1509:     }
 1510:     # &Apache::lonnet::logthis('query = '.$/.$query);
 1511:     return ($query,$customquery,$customshow,$libraries_to_query,
 1512:             $pretty_search_string);
 1513: }
 1514: 
 1515: sub parse_domain_restrictions {
 1516:     my $libraries_to_query = undef;
 1517:     # $ENV{'form.domains'} can be either a scalar or an array reference.
 1518:     # We need an array.
 1519:     if (! exists($ENV{'form.domains'}) || $ENV{'form.domains'} eq '') {
 1520:         return (undef,'');
 1521:     }
 1522:     my @allowed_domains;
 1523:     if (ref($ENV{'form.domains'})) {
 1524:         @allowed_domains =  @{$ENV{'form.domains'}};
 1525:     } else {
 1526:         @allowed_domains = ($ENV{'form.domains'});
 1527:     }
 1528:     #
 1529:     my %domain_hash = ();
 1530:     my $pretty_domains_string;
 1531:     foreach (@allowed_domains) {
 1532:         $domain_hash{$_}++;
 1533:     }
 1534:     if ($domain_hash{'any'}) {
 1535:         $pretty_domains_string = "In all LON-CAPA domains.";
 1536:     } else {
 1537:         if (@allowed_domains > 1) {
 1538:             $pretty_domains_string = "In LON-CAPA domains:";
 1539:         } else {
 1540:             $pretty_domains_string = "In LON-CAPA domain ";
 1541:         }
 1542:         foreach (sort @allowed_domains) {
 1543:             $pretty_domains_string .= "<b>".$_."</b> ";
 1544:         }
 1545:         foreach (keys(%Apache::lonnet::libserv)) {
 1546:             if (exists($domain_hash{$Apache::lonnet::hostdom{$_}})) {
 1547:                 push @$libraries_to_query,$_;
 1548:             }
 1549:         }
 1550:     }
 1551:     return ($libraries_to_query,$pretty_domains_string);
 1552: }
 1553: 
 1554: ######################################################################
 1555: ######################################################################
 1556: 
 1557: =pod 
 1558: 
 1559: =item &parse_basic_search() 
 1560: 
 1561: Parse the basic search form and return a scalar containing an sql query.
 1562: 
 1563: =cut
 1564: 
 1565: ######################################################################
 1566: ######################################################################
 1567: sub parse_basic_search {
 1568:     my ($r,$closebutton)=@_;
 1569:     #
 1570:     # Clean up fields for safety
 1571:     for my $field ('basicexp') {
 1572: 	$ENV{"form.$field"}=~s/[^\w\s\'\"\!\(\)\-]//g;
 1573:     }
 1574:     foreach ('mode','form','element') {
 1575: 	# is this required?  Hmmm.
 1576: 	next unless (exists($ENV{"form.$_"}));
 1577: 	$ENV{"form.$_"}=&Apache::lonnet::unescape($ENV{"form.$_"});
 1578: 	$ENV{"form.$_"}=~s/[^\w\/\s\(\)\=\-\"\']//g;
 1579:     }
 1580:     my ($libraries_to_query,$pretty_domains_string) = 
 1581:         &parse_domain_restrictions();
 1582:     #
 1583:     # Check to see if enough of a query is filled in
 1584:     my $search_string = $ENV{'form.basicexp'};
 1585:     if (! &filled($search_string)) {
 1586: 	&output_blank_field_error($r,$closebutton,'phase=disp_basic');
 1587: 	return OK;
 1588:     }
 1589:     my $pretty_search_string=$search_string;
 1590:     my @Queries;
 1591:     my $searchfield = 'concat_ws(" ",'.join(',',
 1592:                                             ('title','author','subject',
 1593:                                              'notes','abstract','keywords')
 1594:                                             ).')';
 1595:     my ($error,$SQLQuery) = &process_phrase_input($search_string,
 1596:                                                     $ENV{'form.related'},
 1597:                                                     $searchfield);
 1598:     if ($error) {
 1599:         &output_unparsed_phrase_error($r,$closebutton,'phase=disp_basic',
 1600:                                       '','basicexp');
 1601:         return;
 1602:     }
 1603:     push(@Queries,$SQLQuery);
 1604:     #foreach my $q (@Queries) {
 1605:     #    &Apache::lonnet::logthis('    '.$q);
 1606:     #}
 1607:     my $final_query = 'SELECT * FROM metadata WHERE '.join(" AND ",@Queries);
 1608:     #
 1609:     if (defined($pretty_domains_string) && $pretty_domains_string ne '') {
 1610:         $pretty_search_string .= ' '.$pretty_domains_string;
 1611:     }
 1612:     $pretty_search_string .= "<br />\n";
 1613:     $pretty_search_string =~ s:^<br /> and ::;
 1614:     # &Apache::lonnet::logthis($final_query);
 1615:     return ($final_query,$pretty_search_string,
 1616:             $libraries_to_query);
 1617: }
 1618: 
 1619: 
 1620: ###############################################################
 1621: ###############################################################
 1622: 
 1623: my @Phrases;
 1624: 
 1625: sub concat {
 1626:     my ($item) = @_;
 1627:     my $results = '';
 1628:     foreach (@$item) {
 1629:         if (ref($_) eq 'ARRAY') {
 1630:             $results .= join(' ',@$_);
 1631:         }
 1632:     }
 1633:     return $results;
 1634: }
 1635: 
 1636: sub process_phrase_input {
 1637:     my ($phrase,$related,$field)=@_;
 1638:     #&Apache::lonnet::logthis('phrase = :'.$phrase.':');
 1639:     my $grammar = <<'ENDGRAMMAR';
 1640:     searchphrase:
 1641:         expression /^\Z/ {
 1642:             # &Apache::lonsearchcat::print_item(\@item,0);
 1643:             [@item];
 1644:         }
 1645:     expression:
 1646:         phrase(s)   {
 1647:             [@item];
 1648:         }
 1649:     phrase:
 1650:         orword {
 1651:             [@item];
 1652:         }
 1653:       | andword {
 1654:             [@item];
 1655:         }
 1656:       | minusword {
 1657:             unshift(@::Phrases,$item[1]->[0]);
 1658:             unshift(@::Phrases,$item[1]->[1]);
 1659:             [@item];
 1660:         }
 1661:       | word {
 1662:             unshift(@::Phrases,$item[1]);
 1663:             [@item];
 1664:         } 
 1665:     #
 1666:     orword:
 1667:         word 'OR' phrase {
 1668:             unshift(@::Phrases,'OR');
 1669:             unshift(@::Phrases,$item[1]);
 1670:             [@item];
 1671:         }
 1672:         | word 'or' phrase {
 1673:             unshift(@::Phrases,'OR');
 1674:             unshift(@::Phrases,$item[1]);
 1675:             [@item];
 1676:         }    
 1677:         | minusword 'OR' phrase {
 1678:             unshift(@::Phrases,'OR');
 1679:             unshift(@::Phrases,$item[1]->[0]);
 1680:             unshift(@::Phrases,$item[1]->[1]);
 1681:             [@item];
 1682:         }
 1683:         | minusword 'or' phrase {
 1684:             unshift(@::Phrases,'OR');
 1685:             unshift(@::Phrases,$item[1]->[0]);
 1686:             unshift(@::Phrases,$item[1]->[1]);
 1687:             [@item];
 1688:         }    
 1689:     andword:
 1690:         word phrase {
 1691:             unshift(@::Phrases,'AND');
 1692:             unshift(@::Phrases,$item[1]);
 1693:             [@item];
 1694:         }
 1695:         | minusword phrase {
 1696:             unshift(@::Phrases,'AND');
 1697:             unshift(@::Phrases,$item[1]->[0]);
 1698:             unshift(@::Phrases,$item[1]->[1]);
 1699:             [@item];
 1700:         }
 1701:     #
 1702:     minusword:
 1703:         '-' word {
 1704:             [$item[2],'NOT'];
 1705:         }
 1706:     word:
 1707:         "'" term(s) "'" {
 1708:           &Apache::lonsearchcat::concat(\@item);
 1709:         }
 1710:       | '"' term(s) '"' {
 1711:           &Apache::lonsearchcat::concat(\@item);
 1712:         }
 1713:       | term {
 1714:             $item[1];
 1715:         }
 1716:     term:
 1717:         /[\w\Q:!@#$%^&*()+_=|{}<>,.;\\\/?\E]+/ {
 1718:             $item[1];
 1719:         }
 1720: ENDGRAMMAR
 1721:     #
 1722:     # The end result of parsing the phrase with the grammar is an array
 1723:     # @::Phrases.
 1724:     # $phrase = "gene splicing" or cat -> "gene splicing","OR","cat"
 1725:     # $phrase = "genetic engineering" -dna ->
 1726:     #                      "genetic engineering","AND","NOT","dna"
 1727:     # $phrase = cat or dog -poodle -> "cat","OR","dog","AND","NOT","poodle"
 1728:     undef(@::Phrases);
 1729:     my $p = new Parse::RecDescent($grammar);
 1730:     if (! defined($p->searchphrase($phrase))) {
 1731:         &Apache::lonnet::logthis('lonsearchcat:unable to process:'.$phrase);
 1732:         return 'Unable to process phrase '.$phrase;
 1733:     }
 1734:     #
 1735:     # Go through the phrases and make sense of them.  
 1736:     # Apply modifiers NOT OR and AND to the phrases.
 1737:     my @NewPhrases;
 1738:     while(@::Phrases) {
 1739:         my $phrase = shift(@::Phrases);
 1740:         # &Apache::lonnet::logthis('phrase = '.$phrase);
 1741:         my $phrasedata;
 1742:         if ($phrase =~ /^(NOT|OR|AND)$/) {
 1743:             if ($phrase eq 'OR') {
 1744:                 $phrasedata->{'or'}++;
 1745:                 if (! @::Phrases) { $phrasedata = undef; last; }
 1746:                 $phrase = shift(@::Phrases);
 1747:             } elsif ($phrase eq 'AND') {
 1748:                 $phrasedata->{'and'}++;
 1749:                 if (! @::Phrases) { $phrasedata = undef; last; }
 1750:                 $phrase = shift(@::Phrases);
 1751:             }
 1752:             if ($phrase eq 'NOT') {
 1753:                 $phrasedata->{'negate'}++;
 1754:                 if (! @::Phrases) { $phrasedata = undef; last; }
 1755:                 $phrase = shift(@::Phrases);
 1756:             }
 1757:         }
 1758:         $phrasedata->{'phrase'} = $phrase;
 1759:         if ($related) {
 1760:             my @NewWords;
 1761:             (undef,@NewWords) = &related_version($phrasedata->{'phrase'});
 1762:             $phrasedata->{'related_words'} = \@NewWords;
 1763:         }
 1764:         push(@NewPhrases,$phrasedata);
 1765:     }
 1766:     #
 1767:     # Actually build the sql query from the phrases
 1768:     my $SQLQuery;
 1769:     foreach my $phrase (@NewPhrases) {
 1770:         my $query;
 1771:         if ($phrase->{'negate'}) {
 1772:             $query .= $field.' NOT LIKE "%'.$phrase->{'phrase'}.'%"';
 1773:         } else {
 1774:             $query .= $field.' LIKE "%'.$phrase->{'phrase'}.'%"';
 1775:         }
 1776:         foreach my $related (@{$phrase->{'related_words'}}) {
 1777:             if ($phrase->{'negate'}) {
 1778:                 $query .= ' AND '.$field.' NOT LIKE "%'.$related.'%"';
 1779:             } else {
 1780:                 $query .= ' OR '.$field.' LIKE "%'.$related.'%"';
 1781:             }
 1782:         }
 1783:         if ($SQLQuery) {
 1784:             if ($phrase->{'or'}) {
 1785:                 $SQLQuery .= ' OR ('.$query.')';
 1786:             } else {
 1787:                 $SQLQuery .= ' AND ('.$query.')';
 1788:             }
 1789:         } else {
 1790:             $SQLQuery = '('.$query.')';
 1791:         }
 1792:     }
 1793:     #
 1794:     # &Apache::lonnet::logthis("SQLQuery = $SQLQuery");
 1795:     #
 1796:     return undef,$SQLQuery;
 1797: }
 1798: 
 1799: ######################################################################
 1800: ######################################################################
 1801: 
 1802: =pod 
 1803: 
 1804: =item &related_version()
 1805: 
 1806: Modifies an input string to include related words.  Words in the string
 1807: are replaced with parenthesized lists of 'OR'd words.  For example
 1808: "torque" is replaced with "(torque OR word1 OR word2 OR ...)".  
 1809: 
 1810: Note: Using this twice on a string is probably silly.
 1811: 
 1812: =cut
 1813: 
 1814: ######################################################################
 1815: ######################################################################
 1816: sub related_version {
 1817:     my ($word) = @_;
 1818:     return (undef) if (lc($word) =~ /\b(or|and|not)\b/);
 1819:     my @Words = &Apache::loncommon::get_related_words($word);
 1820:     # Only use 4 related words
 1821:     @Words = ($#Words>4? @Words[0..4] : @Words);
 1822:     my $result = join " OR ", ($word,@Words);
 1823:     return $result,sort(@Words);
 1824: }
 1825: 
 1826: 
 1827: ######################################################################
 1828: ######################################################################
 1829: 
 1830: =pod 
 1831: 
 1832: =item &build_custommetadata_query() 
 1833: 
 1834: Constructs a custom metadata query using a rather heinous regular
 1835: expression.
 1836: 
 1837: =cut
 1838: 
 1839: ######################################################################
 1840: ######################################################################
 1841: sub build_custommetadata_query {
 1842:     my ($field_name,$logic_statement)=@_;
 1843:     my $q=new Text::Query('abc',
 1844: 			  -parse => 'Text::Query::ParseAdvanced',
 1845: 			  -build => 'Text::Query::BuildAdvancedString');
 1846:     $q->prepare($logic_statement);
 1847:     my $matchexp=${$q}{'-parse'}{'-build'}{'matchstring'};
 1848:     # quick fix to change literal into xml tag-matching
 1849:     # will eventually have to write a separate builder module
 1850:     # wordone=wordtwo becomes\<wordone\>[^\<] *wordtwo[^\<]*\<\/wordone\>
 1851:     $matchexp =~ s/(\w+)\\=([\w\\\+]+)?# wordone=wordtwo is changed to 
 1852:                  /\\<$1\\>?#           \<wordone\>
 1853:                    \[\^\\<\]?#        [^\<]         
 1854:                    \*$2\[\^\\<\]?#           *wordtwo[^\<]
 1855:                    \*\\<\\\/$1\\>?#                        *\<\/wordone\>
 1856:                    /g;
 1857:     return $matchexp;
 1858: }
 1859: 
 1860: 
 1861: ######################################################################
 1862: ######################################################################
 1863: 
 1864: =pod 
 1865: 
 1866: =item &build_date_queries() 
 1867: 
 1868: Builds a SQL logic query to check time/date entries.
 1869: Also reports errors (check for /^Incorrect/).
 1870: 
 1871: =cut
 1872: 
 1873: ######################################################################
 1874: ######################################################################
 1875: sub build_date_queries {
 1876:     my ($cafter,$cbefore,$mafter,$mbefore) = @_;
 1877:     my ($result,$error,$pretty_string);
 1878:     #
 1879:     # Verify the input
 1880:     if (! defined($cafter) && ! defined($cbefore) &&
 1881:         ! defined($mafter) && ! defined($mbefore)) {
 1882:         # This is an okay situation, so return undef for the error
 1883:         return (undef,undef,undef);
 1884:     }
 1885:     if ((defined($cafter)  && ! defined($cbefore)) ||
 1886:         (defined($cbefore) && ! defined($cafter))) {
 1887:         # This is bad, so let them know
 1888:         $error = &mt('Incorrect entry for the creation date.  '.
 1889:                     'You must specify both the beginning and ending dates.');
 1890:     }
 1891:     if (! defined($error) && 
 1892:         ((defined($mafter)  && ! defined($mbefore)) ||
 1893:         (defined($mbefore) && ! defined($mafter)))) {
 1894:         # This is also bad, so let them know
 1895:         $error = &mt('Incorrect entry for the last revision date.  '.
 1896:                      'You must specify both the beginning and ending dates.');
 1897:     }
 1898:     if (! defined($error)) {
 1899:         #
 1900:         # Build the queries
 1901:         my @queries;
 1902:         if (defined($cbefore) && defined($cafter)) {
 1903:             my (undef,undef,undef,$caday,$camon,$cayear) = localtime($cafter);
 1904:             my (undef,undef,undef,$cbday,$cbmon,$cbyear) = localtime($cbefore);
 1905:             # Correct for year being relative to 1900
 1906:             $cayear+=1900; $cbyear+=1900;
 1907:             my $cquery=
 1908:                 '(creationdate BETWEEN '.
 1909:                 "'".$cayear.'-'.$camon.'-'.$caday."'".
 1910:                 ' AND '.
 1911:                 "'".$cbyear.'-'.$cbmon.'-'.$cbday." 23:59:59')";
 1912:             $pretty_string .= '<br />' if (defined($pretty_string));
 1913:             $pretty_string .= 
 1914:                 &mt('created between [_1] and [_2]',
 1915:                     &Apache::lonlocal::locallocaltime($cafter),
 1916:                     &Apache::lonlocal::locallocaltime($cbefore+24*60*60-1));
 1917:             push(@queries,$cquery);
 1918:             $pretty_string =~ s/ 00:00:00//g;
 1919:         }
 1920:         if (defined($mbefore) && defined($mafter)) {
 1921:             my (undef,undef,undef,$maday,$mamon,$mayear) = localtime($mafter);
 1922:             my (undef,undef,undef,$mbday,$mbmon,$mbyear) = localtime($mbefore);
 1923:             # Correct for year being relative to 1900
 1924:             $mayear+=1900; $mbyear+=1900;
 1925:             my $mquery=
 1926:                 '(lastrevisiondate BETWEEN '.
 1927:                 "'".$mayear.'-'.$mamon.'-'.$maday."'".
 1928:                 ' AND '.
 1929:                 "'".$mbyear.'-'.$mbmon.'-'.$mbday." 23:59:59')";
 1930:             push(@queries,$mquery);
 1931:             $pretty_string .= '<br />' if (defined($pretty_string));
 1932:             $pretty_string .= 
 1933:                 &mt('last revised between [_1] and [_2]',
 1934:                     &Apache::lonlocal::locallocaltime($mafter),
 1935:                     &Apache::lonlocal::locallocaltime($mbefore+24*60*60-1));
 1936:             $pretty_string =~ s/ 00:00:00//g;
 1937:         }
 1938:         if (@queries) {
 1939:             $result .= join(" AND ",@queries);
 1940:         }
 1941:     }
 1942:     return ($result,$error,$pretty_string);
 1943: }
 1944: 
 1945: ######################################################################
 1946: ######################################################################
 1947: 
 1948: =pod
 1949: 
 1950: =item &copyright_check()
 1951: 
 1952: Inputs: $Metadata, a hash pointer of metadata for a resource.
 1953: 
 1954: Returns: 1 if the resource is available to the user making the query, 
 1955:          0 otherwise.
 1956: 
 1957: =cut
 1958: 
 1959: ######################################################################
 1960: ######################################################################
 1961: sub copyright_check {
 1962:     my $Metadata = shift;
 1963:     # Check copyright tags and skip results the user cannot use
 1964:     my (undef,undef,$resdom,$resname) = split('/',
 1965:                                               $Metadata->{'url'});
 1966:     # Check for priv
 1967:     if (($Metadata->{'copyright'} eq 'priv') && 
 1968:         (($ENV{'user.name'} ne $resname) &&
 1969:          ($ENV{'user.domain'} ne $resdom))) {
 1970:         return 0;
 1971:     }
 1972:     # Check for domain
 1973:     if (($Metadata->{'copyright'} eq 'domain') &&
 1974:         ($ENV{'user.domain'} ne $resdom)) {
 1975:         return 0;
 1976:     }
 1977:     return 1;
 1978: }
 1979: 
 1980: ######################################################################
 1981: ######################################################################
 1982: 
 1983: =pod
 1984: 
 1985: =item &ensure_db_and_table()
 1986: 
 1987: Ensure we can get lonmysql to connect to the database and the table we
 1988: need exists.
 1989: 
 1990: Inputs: $r, table id
 1991: 
 1992: Returns: undef on error, 1 if the table exists.
 1993: 
 1994: =cut
 1995: 
 1996: ######################################################################
 1997: ######################################################################
 1998: sub ensure_db_and_table {
 1999:     my ($r,$table) = @_;
 2000:     ##
 2001:     ## Sanity check the table id.
 2002:     ##
 2003:     if (! defined($table) || $table eq '' || $table =~ /\D/ ) {
 2004:         $r->print("Unable to retrieve search results.  ".
 2005:                   "Unable to determine the table results were stored in.  ".
 2006:                   "</body></html>");
 2007:         return undef;
 2008:     }
 2009:     ##
 2010:     ## Make sure we can connect and the table exists.
 2011:     ##
 2012:     my $connection_result = &Apache::lonmysql::connect_to_db();
 2013:     if (!defined($connection_result)) {
 2014:         $r->print("Unable to connect to the MySQL database where your results".
 2015:                   " are stored. </body></html>");
 2016:         &Apache::lonnet::logthis("lonsearchcat: unable to get lonmysql to".
 2017:                                  " connect to database.");
 2018:         &Apache::lonnet::logthis(&Apache::lonmysql::get_error());
 2019:         return undef;
 2020:     }
 2021:     my $table_check = &Apache::lonmysql::check_table($table);
 2022:     if (! defined($table_check)) {
 2023:         $r->print("A MySQL error has occurred.</form></body></html>");
 2024:         &Apache::lonnet::logthis("lonmysql was unable to determine the status".
 2025:                                  " of table ".$table);
 2026:         return undef;
 2027:     } elsif (! $table_check) {
 2028:         $r->print("The table of results could not be found.");
 2029:         &Apache::lonnet::logthis("The user requested a table, ".$table.
 2030:                                  ", that could not be found.");
 2031:         return undef;
 2032:     }
 2033:     return 1;
 2034: }
 2035: 
 2036: ######################################################################
 2037: ######################################################################
 2038: 
 2039: =pod
 2040: 
 2041: =item &print_sort_form()
 2042: 
 2043: The sort feature is not implemented at this time.  This form just prints 
 2044: a link to change the search query.
 2045: 
 2046: =cut
 2047: 
 2048: ######################################################################
 2049: ######################################################################
 2050: sub print_sort_form {
 2051:     my ($r,$pretty_query_string) = @_;
 2052:     my $bodytag=&Apache::loncommon::bodytag(undef,undef,undef,1).
 2053:         &Apache::lonhtmlcommon::breadcrumbs
 2054:         (undef,'Searching','Searching',undef,undef,
 2055:          $ENV{'form.catalogmode'} ne 'groupsearch');
 2056: 
 2057:     ##
 2058:     my %SortableFields=&Apache::lonlocal::texthash( 
 2059:          id        => 'Default',
 2060:          title     => 'Title',
 2061:          author    => 'Author',
 2062:          subject   => 'Subject',
 2063:          url       => 'URL',
 2064:          version   => 'Version Number',
 2065:          mime      => 'Mime type',
 2066:          lang      => 'Language',
 2067:          owner     => 'Owner/Publisher',
 2068:          copyright => 'Copyright',
 2069:          hostname  => 'Host',
 2070:          creationdate     => 'Creation Date',
 2071:          lastrevisiondate => 'Revision Date'
 2072:      );
 2073:     ##
 2074:     my $table = $ENV{'form.table'};
 2075:     return if (! &ensure_db_and_table($r,$table));
 2076:     ##
 2077:     ## Get the number of results 
 2078:     ##
 2079:     my $total_results = &Apache::lonmysql::number_of_rows($table);
 2080:     if (! defined($total_results)) {
 2081:         $r->print("A MySQL error has occurred.</form></body></html>");
 2082:         &Apache::lonnet::logthis("lonmysql was unable to determine the number".
 2083:                                  " of rows in table ".$table);
 2084:         &Apache::lonnet::logthis(&Apache::lonmysql::get_error());
 2085:         return;
 2086:     }
 2087:     my $result;
 2088:     $result.=<<END;
 2089: <html>
 2090: <head>
 2091: <script>
 2092:     function change_sort() {
 2093:         var newloc = "/adm/searchcat?phase=results";
 2094:         newloc += "&persistent_db_id=$ENV{'form.persistent_db_id'}";
 2095:         newloc += "&sortby=";
 2096:         newloc += document.forms.statusform.elements.sortby.value;
 2097:         parent.resultsframe.location= newloc;
 2098:     }
 2099: </script>
 2100: <title>Results</title>
 2101: </head>
 2102: $bodytag
 2103: <form name="statusform" action="" method="post">
 2104: <input type="hidden" name="Queue" value="" />
 2105: END
 2106: 
 2107: #<h2>Sort Results</h2>
 2108: #Sort by: <select size="1" name="sortby" onchange="javascript:change_sort();">
 2109: #    $ENV{'form.sortby'} = 'id' if (! defined($ENV{'form.sortby'}));
 2110: #    foreach (keys(%SortableFields)) {
 2111: #        $result.="<option name=\"$_\"";
 2112: #        if ($_ eq $ENV{'form.sortby'}) {
 2113: #            $result.=" selected ";
 2114: #        }
 2115: #        $result.=" >$SortableFields{$_}</option>\n";
 2116: #    }
 2117: #    $result.="</select>\n";
 2118:     my $revise = &revise_button();
 2119:     $result.=<<END;
 2120: <p>
 2121: There are $total_results matches to your query. $revise
 2122: </p><p>
 2123: Search:$pretty_query_string
 2124: </p>
 2125: </form>
 2126: </body>
 2127: </html>
 2128: END
 2129:     $r->print($result);
 2130:     return;
 2131: }
 2132: 
 2133: #####################################################################
 2134: #####################################################################
 2135: 
 2136: =pod
 2137: 
 2138: =item MySQL Table Description
 2139: 
 2140: MySQL table creation requires a precise description of the data to be
 2141: stored.  The use of the correct types to hold data is vital to efficient
 2142: storage and quick retrieval of records.  The columns must be described in
 2143: the following format:
 2144: 
 2145: =cut
 2146: 
 2147: #####################################################################
 2148: #####################################################################
 2149: #
 2150: # These should probably be scoped but I don't have time right now...
 2151: #
 2152: my @Datatypes;
 2153: my @Fullindicies;
 2154:     
 2155: ######################################################################
 2156: ######################################################################
 2157: 
 2158: =pod
 2159: 
 2160: =item &create_results_table()
 2161: 
 2162: Creates the table of search results by calling lonmysql.  Stores the
 2163: table id in $ENV{'form.table'}
 2164: 
 2165: Inputs: none.
 2166: 
 2167: Returns: the identifier of the table on success, undef on error.
 2168: 
 2169: =cut
 2170: 
 2171: ######################################################################
 2172: ######################################################################
 2173: sub set_up_table_structure {
 2174:     my ($datatypes,$fullindicies) = 
 2175:         &LONCAPA::lonmetadata::describe_metadata_storage();
 2176:     # Copy the table description before modifying it...
 2177:     @Datatypes = @{$datatypes};
 2178:     unshift(@Datatypes,{name => 'id',  
 2179:         type => 'MEDIUMINT',
 2180:         restrictions => 'UNSIGNED NOT NULL',
 2181:         primary_key  => 'yes',
 2182:         auto_inc     => 'yes' });
 2183:     @Fullindicies = @{$fullindicies};
 2184:     return;
 2185: }
 2186: 
 2187: sub create_results_table {
 2188:     &set_up_table_structure();
 2189:     my $table = &Apache::lonmysql::create_table
 2190:         ( { columns => \@Datatypes,
 2191:             FULLTEXT => [{'columns' => \@Fullindicies},],
 2192:         } );
 2193:     if (defined($table)) {
 2194:         $ENV{'form.table'} = $table;
 2195:         return $table;
 2196:     } 
 2197:     return undef; # Error...
 2198: }
 2199: 
 2200: ######################################################################
 2201: ######################################################################
 2202: 
 2203: =pod
 2204: 
 2205: =item Search Status update functions
 2206: 
 2207: Each of the following functions changes the values of one of the
 2208: input fields used to display the search status to the user.  The names
 2209: should be explanatory.
 2210: 
 2211: Inputs: Apache request handler ($r), text to display.
 2212: 
 2213: Returns: Nothing.
 2214: 
 2215: =over 4
 2216: 
 2217: =item &update_count_status()
 2218: 
 2219: =item &update_status()
 2220: 
 2221: =item &update_seconds()
 2222: 
 2223: =back
 2224: 
 2225: =cut
 2226: 
 2227: ######################################################################
 2228: ######################################################################
 2229: sub update_count_status {
 2230:     my ($r,$text) = @_;
 2231:     $text =~ s/\'/\\\'/g;
 2232:     $r->print
 2233:         ("<script>document.statusform.count.value = ' $text'</script>\n");
 2234:     $r->rflush();
 2235: }
 2236: 
 2237: sub update_status {
 2238:     my ($r,$text) = @_;
 2239:     $text =~ s/\'/\\\'/g;
 2240:     $r->print
 2241:         ("<script>document.statusform.status.value = ' $text'</script>\n");
 2242:     $r->rflush();
 2243: }
 2244: 
 2245: {
 2246:     my $max_time  = 40;  # seconds for the search to complete
 2247:     my $start_time = 0;
 2248:     my $last_time = 0;
 2249: 
 2250: sub reset_timing {
 2251:     $start_time = 0;
 2252:     $last_time = 0;
 2253: }
 2254: 
 2255: sub time_left {
 2256:     if ($start_time == 0) {
 2257:         $start_time = time;
 2258:     }
 2259:     my $time_left = $max_time - (time - $start_time);
 2260:     $time_left = 0 if ($time_left < 0);
 2261:     return $time_left;
 2262: }
 2263: 
 2264: sub update_seconds {
 2265:     my ($r) = @_;
 2266:     my $time = &time_left();
 2267:     if (($last_time-$time) > 0) {
 2268:         $r->print("<script>".
 2269:                   "document.statusform.seconds.value = '$time'".
 2270:                   "</script>\n");
 2271:         $r->rflush();
 2272:     }
 2273:     $last_time = $time;
 2274: }
 2275: 
 2276: }
 2277: 
 2278: ######################################################################
 2279: ######################################################################
 2280: 
 2281: =pod
 2282: 
 2283: =item &revise_button()
 2284: 
 2285: Inputs: None
 2286: 
 2287: Returns: html string for a 'revise search' button.
 2288: 
 2289: =cut
 2290: 
 2291: ######################################################################
 2292: ######################################################################
 2293: sub revise_button {
 2294:     my $revise_phase = 'disp_basic';
 2295:     $revise_phase = 'disp_adv' if ($ENV{'form.searchmode'} eq 'advanced');
 2296:     my $newloc = '/adm/searchcat'.
 2297:         '?persistent_db_id='.$ENV{'form.persistent_db_id'}.
 2298:             '&cleargroupsort=1'.
 2299:             '&phase='.$revise_phase;
 2300:     my $result = qq{<input type="button" value="Revise search" name="revise"} .
 2301:         qq{ onClick="parent.location='$newloc';" /> };
 2302:     return $result;
 2303: }
 2304: 
 2305: ######################################################################
 2306: ######################################################################
 2307: 
 2308: =pod
 2309: 
 2310: =item &run_search()
 2311: 
 2312: Executes a search query by sending it the the other servers and putting the
 2313: results into MySQL.
 2314: 
 2315: =cut
 2316: 
 2317: ######################################################################
 2318: ######################################################################
 2319: sub run_search {
 2320:     my ($r,$query,$customquery,$customshow,$serverlist,$pretty_string) = @_;
 2321:     my $bodytag=&Apache::loncommon::bodytag(undef,undef,undef,1);
 2322:     $bodytag.=&Apache::lonhtmlcommon::breadcrumbs
 2323:         (undef,'Searching','Searching',undef,undef,
 2324:          $ENV{'form.catalogmode'} ne 'groupsearch');
 2325:     my $connection = $r->connection;
 2326:     #
 2327:     # Print run_search header
 2328:     #
 2329:     $r->print(<<END);
 2330: <html>
 2331: <head><title>Search Status</title></head>
 2332: $bodytag
 2333: <form name="statusform" action="" method="post">
 2334: <input type="hidden" name="Queue" value="" />
 2335: END
 2336:     # Remove leading and trailing <br />
 2337:     $pretty_string =~ s:^\s*<br />::i;
 2338:     $pretty_string =~ s:(<br />)*\s*$::im;
 2339:     my @Lines = split("<br />",$pretty_string);
 2340:     # I keep getting blank items at the end of the list, hence the following:
 2341:     while ($Lines[-1] =~ /^\s*$/ && @Lines) {
 2342:         pop(@Lines);
 2343:     }
 2344:     if (@Lines > 2) {
 2345:         $pretty_string = join '<br />',(@Lines[0..2],'....<br />');
 2346:     }
 2347:     $r->print(&mt("Search: [_1]",$pretty_string));
 2348:     $r->rflush();
 2349:     #
 2350:     # Determine the servers we need to contact.
 2351:     my @Servers_to_contact;
 2352:     if (defined($serverlist)) {
 2353:         if (ref($serverlist) eq 'ARRAY') {
 2354:             @Servers_to_contact = @$serverlist;
 2355:         } else {
 2356:             @Servers_to_contact = ($serverlist);
 2357:         }
 2358:     } else {
 2359:         @Servers_to_contact = sort(keys(%Apache::lonnet::libserv));
 2360:     }
 2361:     my %Server_status;
 2362:     #
 2363:     # Check on the mysql table we will use to store results.
 2364:     my $table =$ENV{'form.table'};
 2365:     if (! defined($table) || $table eq '' || $table =~ /\D/ ) {
 2366:         $r->print("Unable to determine table id to store search results in.".
 2367:                   "The search has been aborted.</body></html>");
 2368:         return;
 2369:     }
 2370:     my $table_status = &Apache::lonmysql::check_table($table);
 2371:     if (! defined($table_status)) {
 2372:         $r->print("Unable to determine status of table.</body></html>");
 2373:         &Apache::lonnet::logthis("Bogus table id of $table for ".
 2374:                                  "$ENV{'user.name'} @ $ENV{'user.domain'}");
 2375:         &Apache::lonnet::logthis("lonmysql error = ".
 2376:                                  &Apache::lonmysql::get_error());
 2377:         return;
 2378:     }
 2379:     if (! $table_status) {
 2380:         &Apache::lonnet::logthis("lonmysql error = ".
 2381:                                  &Apache::lonmysql::get_error());
 2382:         &Apache::lonnet::logthis("lonmysql debug = ".
 2383:                                  &Apache::lonmysql::get_debug());
 2384:         &Apache::lonnet::logthis('table status = "'.$table_status.'"');
 2385:         $r->print("The table id,$table, we tried to use is invalid.".
 2386:                   "The search has been aborted.</body></html>");
 2387:         return;
 2388:     }
 2389:     ##
 2390:     ## Prepare for the big loop.
 2391:     my $hitcountsum;
 2392:     my $server; 
 2393:     my $status;
 2394:     my $revise = &revise_button();
 2395:     $r->print(<<END);
 2396: <table>
 2397: <tr><th>Status</th><th>Total Matches</th><th>Time Remaining</th><th></th></tr>
 2398: <tr>
 2399: <td><input type="text" name="status"  value="" size="30" /></td>
 2400: <td><input type="text" name="count"   value="" size="10" /></td>
 2401: <td><input type="text" name="seconds" value="" size="8" /></td>
 2402: <td>$revise</td>
 2403: </tr>
 2404: </table>
 2405: </form>
 2406: END
 2407:     $r->rflush();
 2408:     &reset_timing();
 2409:     &update_seconds($r);
 2410:     &update_status($r,&mt('contacting [_1]',$Servers_to_contact[0]));
 2411:     while (&time_left() &&
 2412:            ((@Servers_to_contact) || keys(%Server_status))) {
 2413:         &update_seconds($r);
 2414:         #
 2415:         # Send out a search request
 2416:         if (@Servers_to_contact) {
 2417:             # Contact one server
 2418:             my $server = shift(@Servers_to_contact);
 2419:             &update_status($r,&mt('contacting [_1]',$server));
 2420:             my $reply=&Apache::lonnet::metadata_query($query,$customquery,
 2421:                                                       $customshow,[$server]);
 2422:             ($server) = keys(%$reply);
 2423:             $Server_status{$server} = $reply->{$server};
 2424:         } else {
 2425:             # wait a sec. to give time for files to be written
 2426:             # This sleep statement is here instead of outside the else 
 2427:             # block because we do not want to pause if we have servers
 2428:             # left to contact.  
 2429:             if (scalar (keys(%Server_status))) {
 2430:                 &update_status($r,
 2431:                        &mt('waiting on [_1]',join(' ',keys(%Server_status))));
 2432:             }
 2433:             sleep(1); 
 2434:         }
 2435:         #
 2436:         # Loop through the servers we have contacted but do not
 2437:         # have results from yet, looking for results.
 2438:         foreach my $server (keys(%Server_status)) {
 2439:             last if ($connection->aborted());
 2440:             &update_seconds($r);
 2441:             my $status = $Server_status{$server};
 2442:             if ($status eq 'con_lost') {
 2443:                 delete ($Server_status{$server});
 2444:                 next;
 2445:             }
 2446:             $status=~/^([\.\w]+)$/; 
 2447:        	    my $datafile=$r->dir_config('lonDaemons').'/tmp/'.$1;
 2448:             if (-e $datafile && ! -e "$datafile.end") {
 2449:                 &update_status($r,&mt('Receiving results from [_1]',$server));
 2450:                 next;
 2451:             }
 2452:             last if ($connection->aborted());
 2453:             if (-e "$datafile.end") {
 2454:                 &update_status($r,&mt('Reading results from [_1]',$server));
 2455:                 if (-z "$datafile") {
 2456:                     delete($Server_status{$server});
 2457:                     next;
 2458:                 }
 2459:                 my $fh;
 2460:                 if (!($fh=Apache::File->new($datafile))) { 
 2461:                     $r->print("Unable to open search results file for ".
 2462:                                   "server $server.  Omitting from search");
 2463:                     delete($Server_status{$server}); 
 2464:                    next;
 2465:                 }
 2466:                 # Read in the whole file.
 2467:                 while (my $result = <$fh>) {
 2468:                     last if ($connection->aborted());
 2469:                     #
 2470:                     # Records are stored one per line
 2471:                     chomp($result);
 2472:                     next if (! $result);
 2473:                     #
 2474:                     # Parse the result.
 2475:                     my %Fields = &parse_raw_result($result,$server);
 2476:                     $Fields{'hostname'} = $server;
 2477:                     #
 2478:                     # Skip based on copyright
 2479:                     next if (! &copyright_check(\%Fields));
 2480:                     #
 2481:                     # Store the result in the mysql database
 2482:                     my $result = &Apache::lonmysql::store_row($table,\%Fields);
 2483:                     if (! defined($result)) {
 2484:                         $r->print(&Apache::lonmysql::get_error());
 2485:                     }
 2486:                     #
 2487:                     $hitcountsum ++;
 2488:                     &update_seconds($r);
 2489:                     if ($hitcountsum % 50 == 0) {
 2490:                         &update_count_status($r,$hitcountsum);
 2491:                     }
 2492:                 }
 2493:                 $fh->close();
 2494:                 # $server is only deleted if the results file has been 
 2495:                 # found and (successfully) opened.  This may be a bad idea.
 2496:                 delete($Server_status{$server});
 2497:             }
 2498:             last if ($connection->aborted());
 2499:             &update_count_status($r,$hitcountsum);
 2500:         }
 2501:         last if ($connection->aborted());
 2502:         &update_seconds($r);
 2503:     }
 2504:     &update_status($r,&mt('Search Complete [_1]',$server));
 2505:     &update_seconds($r);
 2506:     #
 2507:     &Apache::lonmysql::disconnect_from_db(); # This is unneccessary
 2508:     #
 2509:     # We have run out of time or run out of servers to talk to and
 2510:     # results to get, so let the client know the top frame needs to be
 2511:     # loaded from /adm/searchcat
 2512:     $r->print("</body></html>");
 2513: #    if ($ENV{'form.catalogmode'} ne 'groupsearch') {
 2514:         $r->print("<script>".
 2515:                       "window.location='/adm/searchcat?".
 2516:                       "phase=sort&".
 2517:                       "persistent_db_id=$ENV{'form.persistent_db_id'}';".
 2518:                   "</script>");
 2519: #    }
 2520:     return;
 2521: }
 2522: 
 2523: ######################################################################
 2524: ######################################################################
 2525: 
 2526: =pod
 2527: 
 2528: =item &prev_next_buttons()
 2529: 
 2530: Returns html for the previous and next buttons on the search results page.
 2531: 
 2532: =cut
 2533: 
 2534: ######################################################################
 2535: ######################################################################
 2536: sub prev_next_buttons {
 2537:     my ($current_min,$show,$total,$parms) = @_;
 2538:     return '' if ($show eq 'all'); # No links if you get them all at once.
 2539:     #
 2540:     # Create buttons
 2541:     my $buttons = '<input type="submit" name="prev" value="'.&mt('Prev').'" ';
 2542:     $buttons .= '/>';
 2543:     $buttons .= '&nbsp;'x3;
 2544:     $buttons .= '<input type="submit" name="reload" '.
 2545:         'value="'.&mt('Reload').'" />';
 2546:     $buttons .= '&nbsp;'x3;
 2547:     $buttons .= '<input type="submit" name="next" value="'.&mt('Next').'" ';
 2548:     $buttons .= '/>';
 2549:     return $buttons;
 2550: }
 2551: 
 2552: ######################################################################
 2553: ######################################################################
 2554: 
 2555: =pod
 2556: 
 2557: =item &display_results()
 2558: 
 2559: Prints the results out for selection and perusal.
 2560: 
 2561: =cut
 2562: 
 2563: ######################################################################
 2564: ######################################################################
 2565: sub display_results {
 2566:     my ($r,$importbutton,$closebutton,$diropendb) = @_;
 2567:     my $connection = $r->connection;
 2568:     $r->print(&search_results_header($importbutton,$closebutton));
 2569:     ##
 2570:     ## Set viewing function
 2571:     ##
 2572:     my $viewfunction = $Views{$ENV{'form.viewselect'}};
 2573:     if (!defined($viewfunction)) {
 2574:         $r->print("Internal Error - Bad view selected.\n");
 2575:         $r->rflush();
 2576:         return;
 2577:     }
 2578:     ##
 2579:     ## $checkbox_num is a count of the number of checkboxes output on the 
 2580:     ## page this is used only during catalogmode=groupsearch.
 2581:     my $checkbox_num = 0;
 2582:     ##
 2583:     ## Get the catalog controls setup
 2584:     ##
 2585:     my $action = "/adm/searchcat?phase=results";
 2586:     ##
 2587:     ## Deal with groupsearch by opening the groupsearch db file.
 2588:     if ($ENV{'form.catalogmode'} eq 'groupsearch') {
 2589:         if (! tie(%groupsearch_db,'GDBM_File',$diropendb,
 2590:                   &GDBM_WRCREAT(),0640)) {
 2591:             $r->print('Unable to store import results.</form></body></html>');
 2592:             $r->rflush();
 2593:             return;
 2594:         } 
 2595:     }
 2596:     ##
 2597:     ## Prepare the table for querying
 2598:     my $table = $ENV{'form.table'};
 2599:     return if (! &ensure_db_and_table($r,$table));
 2600:     ##
 2601:     ## Get the number of results 
 2602:     my $total_results = &Apache::lonmysql::number_of_rows($table);
 2603:     if (! defined($total_results)) {
 2604:         $r->print("A MySQL error has occurred.</form></body></html>");
 2605:         &Apache::lonnet::logthis("lonmysql was unable to determine the number".
 2606:                                  " of rows in table ".$table);
 2607:         &Apache::lonnet::logthis(&Apache::lonmysql::get_error());
 2608:         return;
 2609:     }
 2610:     ##
 2611:     ## Determine how many results we need to get
 2612:     $ENV{'form.start'} = 1  if (! exists($ENV{'form.start'}));
 2613:     $ENV{'form.show'}  = 20 if (! exists($ENV{'form.show'}));
 2614:     if (exists($ENV{'form.prev'})) {
 2615:         $ENV{'form.start'} -= $ENV{'form.show'};
 2616:     } elsif (exists($ENV{'form.next'})) {
 2617:         $ENV{'form.start'} += $ENV{'form.show'};
 2618:     }
 2619:     $ENV{'form.start'} = 1 if ($ENV{'form.start'}<1);
 2620:     $ENV{'form.start'} = $total_results if ($ENV{'form.start'}>$total_results);
 2621:     my $min = $ENV{'form.start'};
 2622:     my $max;
 2623:     if ($ENV{'form.show'} eq 'all') {
 2624:         $max = $total_results ;
 2625:     } else {
 2626:         $max = $min + $ENV{'form.show'} - 1;
 2627:         $max = $total_results if ($max > $total_results);
 2628:     }
 2629:     ##
 2630:     ## Output form elements
 2631:     $r->print(&hidden_field('table').
 2632:               &hidden_field('phase').
 2633:               &hidden_field('persistent_db_id').
 2634:               &hidden_field('start')
 2635:               );
 2636:     #
 2637:     # Build sorting selector
 2638:     my @field_order =  ('default',
 2639:                         'title',
 2640:                         'author',
 2641:                         'subject',
 2642:                         'url',
 2643:                         'keywords',
 2644:                         'version',
 2645:                         'language',
 2646:                         'creationdate'=>,
 2647:                         'lastrevisiondate',
 2648:                         'owner',
 2649:                         'copyright',
 2650:                         'authorspace',
 2651:                         'lowestgradeleve',
 2652:                         'highestgradelevel',
 2653:                         'standards',
 2654:                         'count',
 2655:                         'stdno',
 2656:                         'avetries',
 2657:                         'difficulty',
 2658:                         'disc',
 2659:                         'clear',
 2660:                         'technical',
 2661:                         'correct',
 2662:                         'helpful',
 2663:                         'depth',
 2664:                         );                                              
 2665:     my %sort_fields = ('default'     => 'Default',
 2666:                        'title'       => 'Title',
 2667:                        'author'      => 'Author',
 2668:                        'subject'     => 'Subject',
 2669:                        'url'         => 'URL',
 2670:                        'keywords'    => 'Keywords',
 2671:                        'version'     => 'Version',
 2672:                        'language'    => 'Language',
 2673:                        'creationdate'=> 'Creation Date',
 2674:                        'lastrevisiondate' => 'Last Revision Date',
 2675:                        'owner'       => 'Owner',
 2676:                        'copyright'   => 'Copyright',
 2677:                        'authorspace' => 'Authorspace',
 2678:                        'lowestgradeleve' => 'Lowest Grade Level',
 2679:                        'highestgradelevel' => 'Highest Grade Level',
 2680:                        'standards'   => 'Standards',
 2681:                        'count'       => 'Number of Accesses',
 2682:                        'stdno'       => 'Students Attempting',
 2683:                        'avetries'    => 'Average Number of Tries',
 2684:                        'difficulty'  => 'Mean Degree of Difficulty',
 2685:                        'disc'        => 'Mean Degree of Discrimination',
 2686:                        'clear'       => 'Evaluation: Clear',
 2687:                        'technical'   => 'Evaluation: Technically Correct',
 2688:                        'correct'     => 'Evaluation: Material is Correct',
 2689:                        'helpful'     => 'Evaluation: Material is Helpful',
 2690:                        'depth'       => 'Evaluation: Material has Depth',
 2691:                        'select_form_order' => \@field_order,
 2692:                        );
 2693: 
 2694:     my $sortform = &mt('Sort by [_1]',
 2695:                        &Apache::loncommon::select_form($ENV{'form.sortfield'},
 2696:                                                       'sortfield',
 2697:                                                       %sort_fields));
 2698:     ##
 2699:     ## Output links (if necessary) for 'prev' and 'next' pages.
 2700:     $r->print
 2701:         ('<table width="100%"><tr><td width="25%" align="right">'.
 2702:          $sortform.
 2703:          '</td><td width="25%" align="right">'.
 2704:          &prev_next_buttons($min,$ENV{'form.show'},$total_results).
 2705:          '</td><td align="right">'.
 2706:          &viewoptions().'</td></tr></table>'
 2707:          );
 2708:     if ($total_results == 0) {
 2709:         $r->print('<meta HTTP-EQUIV="Refresh" CONTENT="2">'.
 2710:                   '<h3>'.&mt('There are currently no results').'.</h3>'.
 2711:                   "</form></body></html>");
 2712:         return;
 2713:     } else {
 2714:         $r->print('<center>'.
 2715:                   mt('Results [_1] to [_2] out of [_3]',
 2716:                      $min,$max,$total_results).
 2717:                   "</center>\n");
 2718:     }
 2719:     ##
 2720:     ## Get results from MySQL table
 2721:     my $sort_command  = 'id>='.$min.' AND id<='.$max;
 2722:     if ($ENV{'form.sortfield'} ne 'default' && 
 2723:         exists($sort_fields{$ENV{'form.sortfield'}})) {
 2724:         $sort_command = $ENV{'form.sortfield'}.' IS NOT NULL '.
 2725:             'ORDER BY '.$ENV{'form.sortfield'}.
 2726:             '  LIMIT '.($min-1).','.($max-$min);
 2727:     }
 2728:     my @Results = &Apache::lonmysql::get_rows($table,$sort_command);
 2729:     ##
 2730:     ## Loop through the results and output them.
 2731:     foreach my $row (@Results) {
 2732:         if ($connection->aborted()) {
 2733:             &cleanup();
 2734:             return;
 2735:         }
 2736:         my %Fields = %{&parse_row(@$row)};
 2737:         my $output="<p>\n";
 2738:         if (! defined($Fields{'title'}) || $Fields{'title'} eq '') {
 2739:             $Fields{'title'} = 'Untitled';
 2740:         }
 2741:         my $prefix=&catalogmode_output($Fields{'title'},$Fields{'url'},
 2742:                                        $Fields{'id'},$checkbox_num++);
 2743:         # Render the result into html
 2744:         $output.= &$viewfunction($prefix,%Fields);
 2745:         # Print them out as they come in.
 2746:         $r->print($output);
 2747:         $r->rflush();
 2748:     }
 2749:     if (@Results < 1) {
 2750:         $r->print(&mt("There were no results matching your query"));
 2751:     } else {
 2752:         $r->print
 2753:             ('<center>'.
 2754:              &prev_next_buttons($min,$ENV{'form.show'},$total_results,
 2755:                                 "table=".$ENV{'form.table'}.
 2756:                                 "&phase=results".
 2757:                                 "&persistent_db_id=".
 2758:                                 $ENV{'form.persistent_db_id'})
 2759:              ."</center>\n"
 2760:              );
 2761:     }
 2762:     $r->print("</form></body></html>");
 2763:     $r->rflush();
 2764:     untie %groupsearch_db if (tied(%groupsearch_db));
 2765:     return;
 2766: }
 2767: 
 2768: ######################################################################
 2769: ######################################################################
 2770: 
 2771: =pod
 2772: 
 2773: =item &catalogmode_output($title,$url,$fnum,$checkbox_num)
 2774: 
 2775: Returns html needed for the various catalog modes.  Gets inputs from
 2776: $ENV{'form.catalogmode'}.  Stores data in %groupsearch_db.
 2777: 
 2778: =cut
 2779: 
 2780: ######################################################################
 2781: ######################################################################
 2782: sub catalogmode_output {
 2783:     my $output = '';
 2784:     my ($title,$url,$fnum,$checkbox_num) = @_;
 2785:     if ($ENV{'form.catalogmode'} eq 'interactive') {
 2786:         $title=~ s/\'/\\\'/g;
 2787:         if ($ENV{'form.catalogmode'} eq 'interactive') {
 2788:             $output.=<<END 
 2789: <font size='-1'><INPUT TYPE="button" NAME="returnvalues" VALUE="SELECT"
 2790: onClick="javascript:select_data('$title','$url')">
 2791: </font>
 2792: END
 2793:         }
 2794:     } elsif ($ENV{'form.catalogmode'} eq 'groupsearch') {
 2795:         $groupsearch_db{"pre_${fnum}_link"}=$url;
 2796:         $groupsearch_db{"pre_${fnum}_title"}=$title;
 2797:         $output.=<<END;
 2798: <font size='-1'>
 2799: <input type="checkbox" name="returnvalues" value="SELECT"
 2800: onClick="javascript:queue($checkbox_num,$fnum)" />
 2801: </font>
 2802: END
 2803:     }
 2804:     return $output;
 2805: }
 2806: ######################################################################
 2807: ######################################################################
 2808: 
 2809: =pod
 2810: 
 2811: =item &parse_row()
 2812: 
 2813: Parse a row returned from the database.
 2814: 
 2815: =cut
 2816: 
 2817: ######################################################################
 2818: ######################################################################
 2819: sub parse_row {
 2820:     my @Row = @_;
 2821:     my %Fields;
 2822:     if (! scalar(@Datatypes)) {
 2823:         &set_up_table_structure();
 2824:     }
 2825:     for (my $i=0;$i<=$#Row;$i++) {
 2826:         $Fields{$Datatypes[$i]->{'name'}}=&Apache::lonnet::unescape($Row[$i]);
 2827:     }
 2828:     $Fields{'language'} = 
 2829:         &Apache::loncommon::languagedescription($Fields{'language'});
 2830:     $Fields{'copyrighttag'} =
 2831:         &Apache::loncommon::copyrightdescription($Fields{'copyright'});
 2832:     $Fields{'mimetag'} =
 2833:         &Apache::loncommon::filedescription($Fields{'mime'});
 2834:     return \%Fields;
 2835: }
 2836: 
 2837: ###########################################################
 2838: ###########################################################
 2839: 
 2840: =pod
 2841: 
 2842: =item &parse_raw_result()
 2843: 
 2844: Takes a line from the file of results and parse it.  Returns a hash 
 2845: with keys according to column labels
 2846: 
 2847: In addition, the following tags are set by calling the appropriate 
 2848: lonnet function: 'language', 'copyrighttag', 'mimetag'.
 2849: 
 2850: The 'title' field is set to "Untitled" if the title field is blank.
 2851: 
 2852: 'abstract' and 'keywords' are truncated to 200 characters.
 2853: 
 2854: =cut
 2855: 
 2856: ###########################################################
 2857: ###########################################################
 2858: sub parse_raw_result {
 2859:     my ($result,$hostname) = @_;
 2860:     # conclude from self to others regarding fields
 2861:     my %Fields=&LONCAPA::lonmetadata::metadata_col_to_hash
 2862:         (map {
 2863:             &Apache::lonnet::unescape($_);
 2864:         } (split(/\,/,$result)) );
 2865:     return %Fields;
 2866: }
 2867: 
 2868: ###########################################################
 2869: ###########################################################
 2870: 
 2871: =pod
 2872: 
 2873: =item &handle_custom_fields()
 2874: 
 2875: =cut
 2876: 
 2877: ###########################################################
 2878: ###########################################################
 2879: sub handle_custom_fields {
 2880:     my @results = @{shift()};
 2881:     my $customshow='';
 2882:     my $extrashow='';
 2883:     my @customfields;
 2884:     if ($ENV{'form.customshow'}) {
 2885:         $customshow=$ENV{'form.customshow'};
 2886:         $customshow=~s/[^\w\s]//g;
 2887:         my @fields=map {
 2888:             "<font color=\"#008000\">$_:</font><!-- $_ -->";
 2889:         } split(/\s+/,$customshow);
 2890:         @customfields=split(/\s+/,$customshow);
 2891:         if ($customshow) {
 2892:             $extrashow="<ul><li>".join("</li><li>",@fields)."</li></ul>\n";
 2893:         }
 2894:     }
 2895:     my $customdata='';
 2896:     my %customhash;
 2897:     foreach my $result (@results) {
 2898:         if ($result=~/^(custom\=.*)$/) { # grab all custom metadata
 2899:             my $tmp=$result;
 2900:             $tmp=~s/^custom\=//;
 2901:             my ($k,$v)=map {&Apache::lonnet::unescape($_);
 2902:                         } split(/\,/,$tmp);
 2903:             $customhash{$k}=$v;
 2904:         }
 2905:     }
 2906:     return ($extrashow,\@customfields,\%customhash);
 2907: }
 2908: 
 2909: ######################################################################
 2910: ######################################################################
 2911: 
 2912: =pod
 2913: 
 2914: =item &search_results_header()
 2915: 
 2916: Output the proper html headers and javascript code to deal with different 
 2917: calling modes.
 2918: 
 2919: Takes most inputs directly from %ENV, except $mode.  
 2920: 
 2921: =over 4
 2922: 
 2923: =item $mode is either (at this writing) 'Basic' or 'Advanced'
 2924: 
 2925: =back
 2926: 
 2927: The following environment variables are checked:
 2928: 
 2929: =over 4
 2930: 
 2931: =item 'form.catalogmode' 
 2932: 
 2933: Checked for 'interactive' and 'groupsearch'.
 2934: 
 2935: =item 'form.mode'
 2936: 
 2937: Checked for existance & 'edit' mode.
 2938: 
 2939: =item 'form.form'
 2940: 
 2941: Contains the name of the form that has the input fields to set
 2942: 
 2943: =item 'form.element'
 2944: 
 2945: the name of the input field to put the URL into
 2946: 
 2947: =item 'form.titleelement'
 2948: 
 2949: the name of the input field to put the title into
 2950: 
 2951: =back
 2952: 
 2953: =cut
 2954: 
 2955: ######################################################################
 2956: ######################################################################
 2957: sub search_results_header {
 2958:     my ($importbutton,$closebutton) = @_;
 2959:     my $bodytag=&Apache::loncommon::bodytag(undef,undef,undef,1);
 2960:     my $result = '';
 2961:     # output beginning of search page
 2962:     # conditional output of script functions dependent on the mode in
 2963:     # which the search was invoked
 2964:     if ($ENV{'form.catalogmode'} eq 'interactive'){
 2965: 	if (! exists($ENV{'form.mode'}) || $ENV{'form.mode'} ne 'edit') {
 2966:             $result.=<<SCRIPT;
 2967: <script type="text/javascript">
 2968:     function select_data(title,url) {
 2969: 	changeTitle(title);
 2970: 	changeURL(url);
 2971: 	parent.close();
 2972:     }
 2973:     function changeTitle(val) {
 2974: 	if (parent.opener.inf.document.forms.resinfo.elements.t) {
 2975: 	    parent.opener.inf.document.forms.resinfo.elements.t.value=val;
 2976: 	}
 2977:     }
 2978:     function changeURL(val) {
 2979: 	if (parent.opener.inf.document.forms.resinfo.elements.u) {
 2980: 	    parent.opener.inf.document.forms.resinfo.elements.u.value=val;
 2981: 	}
 2982:     }
 2983: </script>
 2984: SCRIPT
 2985:         } elsif ($ENV{'form.mode'} eq 'edit') {
 2986:             my $form = $ENV{'form.form'};
 2987:             my $element = $ENV{'form.element'};
 2988:             my $titleelement = $ENV{'form.titleelement'};
 2989: 	    my $changetitle;
 2990: 	    if (!$titleelement) {
 2991: 		$changetitle='function changeTitle(val) {}';
 2992: 	    } else {
 2993: 		    $changetitle=<<END;
 2994: function changeTitle(val) {
 2995:     if (parent.targetwin.document) {
 2996:         parent.targetwin.document.forms["$form"].elements["$titleelement"].value=val;
 2997:     } else {
 2998: 	var url = 'forms[\"$form\"].elements[\"$titleelement\"].value';
 2999:         alert("Unable to transfer data to "+url);
 3000:     }
 3001: }
 3002: END
 3003:             }
 3004: 
 3005:             $result.=<<SCRIPT;
 3006: <script type="text/javascript">
 3007: function select_data(title,url) {
 3008:     changeURL(url);
 3009:     changeTitle(title);
 3010:     parent.close();
 3011: }
 3012: $changetitle
 3013: function changeURL(val) {
 3014:     if (parent.targetwin.document) {
 3015:         parent.targetwin.document.forms["$form"].elements["$element"].value=val;
 3016:     } else {
 3017: 	var url = 'forms[\"$form\"].elements[\"$element\"].value';
 3018:         alert("Unable to transfer data to "+url);
 3019:     }
 3020: }
 3021: </script>
 3022: SCRIPT
 3023:         }
 3024:     }
 3025:     $result.=<<SCRIPT if $ENV{'form.catalogmode'} eq 'groupsearch';
 3026: <script type="text/javascript">
 3027:     function queue(checkbox_num,val) {
 3028:         if (document.forms.results.returnvalues.length != "undefined" &&
 3029:             typeof(document.forms.results.returnvalues.length) == "number") {
 3030:             if (document.forms.results.returnvalues[checkbox_num].checked) {
 3031:                 parent.statusframe.document.forms.statusform.elements.Queue.value +='1a'+val+'b';
 3032:             } else {
 3033:                 parent.statusframe.document.forms.statusform.elements.Queue.value +='0a'+val+'b';
 3034:             }
 3035:         } else {
 3036:             if (document.forms.results.returnvalues.checked) {
 3037:                 parent.statusframe.document.forms.statusform.elements.Queue.value +='1a'+val+'b';
 3038:             } else {
 3039:                 parent.statusframe.document.forms.statusform.elements.Queue.value +='0a'+val+'b';
 3040:             }
 3041:         }
 3042:     }
 3043:     function select_group() {
 3044: 	parent.window.location=
 3045:     "/adm/groupsort?mode=$ENV{'form.mode'}&catalogmode=groupsearch&acts="+
 3046: 	    parent.statusframe.document.forms.statusform.elements.Queue.value;
 3047:     }
 3048: </script>
 3049: SCRIPT
 3050:     $result.=<<END;
 3051: </head>
 3052: $bodytag
 3053: <form name="results" method="post" action="/adm/searchcat" >
 3054: <input type="hidden" name="Queue" value="" />
 3055: $importbutton
 3056: END
 3057:     return $result;
 3058: }
 3059: 
 3060: ######################################################################
 3061: ######################################################################
 3062: sub search_status_header {
 3063:     my $bodytag=&Apache::loncommon::bodytag(undef,undef,undef,1);
 3064:     return <<ENDSTATUS;
 3065: <html><head><title>Search Status</title></head>
 3066: $bodytag
 3067: <h3>Search Status</h3>
 3068: Sending search request to LON-CAPA servers.<br />
 3069: ENDSTATUS
 3070: }
 3071: 
 3072: sub results_link {
 3073:     my $basic_link   = "/adm/searchcat?"."&table=".$ENV{'form.table'}.
 3074:         "&persistent_db_id=".$ENV{'form.persistent_db_id'};
 3075:     my $results_link = $basic_link."&phase=results".
 3076:         "&pause=1"."&start=1";
 3077:     return $results_link;
 3078: }
 3079: 
 3080: ######################################################################
 3081: ######################################################################
 3082: sub print_frames_interface {
 3083:     my $r = shift;
 3084:     my $basic_link = "/adm/searchcat?"."&table=".$ENV{'form.table'}.
 3085:         "&persistent_db_id=".$ENV{'form.persistent_db_id'};
 3086:     my $run_search_link = $basic_link."&phase=run_search";
 3087:     my $results_link = &results_link();
 3088:     my $result = <<"ENDFRAMES";
 3089: <html>
 3090: <head>
 3091: <script>
 3092: var targetwin = opener;
 3093: var queue = '';
 3094: </script>
 3095: <title>LON-CAPA Digital Library Search Results</title>
 3096: </head>
 3097: <frameset rows="150,*">
 3098:     <frame name="statusframe"  src="$run_search_link">
 3099:     <frame name="resultsframe" src="$results_link">
 3100: </frameset>
 3101: </html>
 3102: ENDFRAMES
 3103: 
 3104:     $r->print($result);
 3105:     return;
 3106: }
 3107: 
 3108: ######################################################################
 3109: ######################################################################
 3110: 
 3111: sub has_stat_data {
 3112:     my ($values) = @_;
 3113:     if ( (defined($values->{'count'})      && $values->{'count'}      ne '') ||
 3114:          (defined($values->{'stdno'})      && $values->{'stdno'}      ne '') ||
 3115:          (defined($values->{'disc'})       && $values->{'disc'}       ne '') ||
 3116:          (defined($values->{'avetries'})   && $values->{'avetries'}   ne '') ||
 3117:          (defined($values->{'difficulty'}) && $values->{'difficulty'} ne '')) {
 3118:         return 1;
 3119:     }
 3120:     return 0;
 3121: }
 3122: 
 3123: sub statfields {
 3124:     return ('count','stdno','disc','avetries','difficulty');
 3125: }
 3126: 
 3127: sub has_eval_data {
 3128:     my ($values) = @_;
 3129:     if ( (defined($values->{'clear'})     && $values->{'clear'}     ne '') ||
 3130:          (defined($values->{'technical'}) && $values->{'technical'} ne '') ||
 3131:          (defined($values->{'correct'})   && $values->{'correct'}   ne '') ||
 3132:          (defined($values->{'helpful'})   && $values->{'helpful'}   ne '') ||
 3133:          (defined($values->{'depth'})     && $values->{'depth'}     ne '')) {
 3134:         return 1;
 3135:     }
 3136:     return 0;
 3137: }
 3138: 
 3139: sub evalfields { 
 3140:     return ('clear','technical','correct','helpful','depth');
 3141: }
 3142: 
 3143: ######################################################################
 3144: ######################################################################
 3145: 
 3146: =pod 
 3147: 
 3148: =item Metadata Viewing Functions
 3149: 
 3150: Output is a HTML-ified string.
 3151: 
 3152: Input arguments are title, author, subject, url, keywords, version,
 3153: notes, short abstract, mime, language, creation date,
 3154: last revision date, owner, copyright, hostname, and
 3155: extra custom metadata to show.
 3156: 
 3157: =over 4
 3158: 
 3159: =item &detailed_citation_view() 
 3160: 
 3161: =cut
 3162: 
 3163: ######################################################################
 3164: ######################################################################
 3165: sub detailed_citation_view {
 3166:     my ($prefix,%values) = @_;
 3167:     my $result;
 3168:     $result .= '<b>'.$prefix.
 3169:         '<img src="'.&Apache::loncommon::icon($values{'url'}).' " />'.'&nbsp;'.
 3170:         '<a href="http://'.$ENV{'HTTP_HOST'}.$values{'url'}.'" '.
 3171:         'target="search_preview">'.$values{'title'}."</a></b>\n";
 3172:     $result .= "<p>\n";
 3173:     $result .= '<b>'.$values{'author'}.'</b>,'.
 3174:         ' <i>'.$values{'owner'}.'</i><br />';
 3175:     foreach my $field 
 3176:         (
 3177:          { name=>'url',
 3178:            translate => '<b>URL:</b>&nbsp;[_1]',
 3179:            special => 'url link',},
 3180:          { name=>'subject',
 3181:            translate => '<b>Subject:</b>&nbsp;[_1]',},
 3182:          { name=>'keywords',
 3183:            translate => '<b>Keywords:</b>&nbsp;[_1]',},
 3184:          { name=>'notes',
 3185:            translate => '<b>Notes:</b>&nbsp;[_1]',},
 3186:          { name=>'mimetag',
 3187:            translate => '<b>MIME Type:</b>&nbsp;[_1]',},
 3188:          { name=>'standards',
 3189:            translate => '<b>Standards:</b>[_1]',},
 3190:          { name=>'copyrighttag',
 3191:            translate => '<b>Copyright/Distribution:</b>&nbsp;[_1]',},
 3192:          { name=>'count',
 3193:            format => "%d",
 3194:            translate => '<b>Access Count:</b>&nbsp;[_1]',},
 3195:          { name=>'stdno',
 3196:            format => "%d",
 3197:            translate => '<b>Number of Students:</b>&nbsp;[_1]',},
 3198:          { name=>'avetries',
 3199:            format => "%.2f",
 3200:            translate => '<b>Average Tries:</b>&nbsp;[_1]',},
 3201:          { name=>'disc',
 3202:            format => "%.2f",
 3203:            translate => '<b>Degree of Discrimination:</b>&nbsp;[_1]',},
 3204:          { name=>'difficulty',
 3205:            format => "%.2f",
 3206:            translate => '<b>Degree of Difficulty:</b>&nbsp;[_1]',},
 3207:          { name=>'clear',
 3208:            format => "%.2f",
 3209:            translate => '<b>Clear:</b>&nbsp;[_1]',},
 3210:          { name=>'depth',
 3211:            format => "%.2f",
 3212:            translate => '<b>Depth:</b>&nbsp;[_1]',},
 3213:          { name=>'helpful',
 3214:            format => "%.2f",
 3215:            translate => '<b>Helpful:</b>&nbsp;[_1]',},
 3216:          { name=>'correct',
 3217:            format => "%.2f",
 3218:            translate => '<b>Correct:</b>&nbsp;[_1]',},
 3219:          { name=>'technical',
 3220:            format => "%.2f",
 3221:            translate => '<b>Technical:</b>&nbsp;[_1]',},
 3222:          { name=>'comefrom_list',
 3223:            type => 'list',
 3224:            translate => 'Resources that lead up to this resource in maps',},
 3225:          { name=>'goto_list',
 3226:            type => 'list',
 3227:            translate => 'Resources that follow this resource in maps',},
 3228:          { name=>'sequsage_list',
 3229:            type => 'list',
 3230:            translate => 'Resources using or importing resource',},
 3231:          ) {
 3232:         next if (! exists($values{$field->{'name'}}) ||
 3233:                  $values{$field->{'name'}} eq '');
 3234:         if (exists($field->{'type'}) && $field->{'type'} eq 'list') {
 3235:             $result .= '<b>'.&mt($field->{'translate'}).'</b><ul>';
 3236:             foreach my $item (split(',',$values{$field->{'name'}})){
 3237:                 $result .= '<li>'.
 3238:                     '<a target="search_preview" '.
 3239:                     'href="/res/'.$item.'">'.$item.'</a></li>';
 3240:             }
 3241:             $result .= '</ul>';
 3242:         } elsif (exists($field->{'format'}) && $field->{'format'} ne ''){
 3243:             $result.= &mt($field->{'translate'},
 3244:                           sprintf($field->{'format'},
 3245:                                   $values{$field->{'name'}}))."<br />\n";
 3246:         } else {
 3247:             if ($field->{'special'} eq 'url link') {
 3248:                 $result.= 
 3249:                      &mt($field->{'translate'},
 3250:                          '<a href="'.$values{'url'}.'" '.
 3251:                          'target="search_preview">'.
 3252:                          $values{$field->{'name'}}.
 3253:                          '</a>');
 3254:             } else {
 3255:                 $result.= &mt($field->{'translate'},
 3256:                               $values{$field->{'name'}});
 3257:             }
 3258:             $result .= "<br />\n";
 3259:         }
 3260:     }
 3261:     $result .= "</p>";
 3262:     if (exists($values{'extrashow'}) && $values{'extrashow'} ne '') {
 3263:         $result .= '<p>'.$values{'extrashow'}.'</p>';
 3264:     }
 3265:     if (exists($values{'shortabstract'}) && $values{'shortabstract'} ne '') {
 3266:         $result .= '<p>'.$values{'shortabstract'}.'</p>';
 3267:     }
 3268:     $result .= '<hr align="left" width="200" noshade />'."\n";
 3269:     return $result;
 3270: }
 3271: 
 3272: ######################################################################
 3273: ######################################################################
 3274: 
 3275: =pod 
 3276: 
 3277: =item &summary_view() 
 3278: 
 3279: =cut
 3280: ######################################################################
 3281: ######################################################################
 3282: sub summary_view {
 3283:     my ($prefix,%values) = @_;
 3284:     my $icon=&Apache::loncommon::icon($values{'url'});
 3285:     my $result=<<END;
 3286: $prefix<img src="$icon" />&nbsp;
 3287: <a href="http://$ENV{'HTTP_HOST'}$values{'url'}" 
 3288:    target='search_preview'>$values{'author'}</a><br />
 3289: $values{'title'}<br />
 3290: $values{'owner'} -- $values{'lastrevisiondate'}<br />
 3291: $values{'copyrighttag'}<br />
 3292: $values{'extrashow'}
 3293: </p>
 3294: <hr align='left' width='200' noshade />
 3295: END
 3296:     return $result;
 3297: }
 3298: 
 3299: ######################################################################
 3300: ######################################################################
 3301: 
 3302: =pod 
 3303: 
 3304: =item &compact_view() 
 3305: 
 3306: =cut
 3307: 
 3308: ######################################################################
 3309: ######################################################################
 3310: sub compact_view {
 3311:     my ($prefix,%values) = @_;
 3312:     my $result = 
 3313:         $prefix.'<img src="'.&Apache::loncommon::icon($values{'url'}).
 3314:         '">&nbsp;<a href="'.$values{'url'}.'" target="search_preview">'.
 3315:         $values{'title'}.'</a>'.('&nbsp;'x2).
 3316:         '<b>'.$values{'author'}.'</b><br />';
 3317:     return $result;
 3318: }
 3319: 
 3320: 
 3321: ######################################################################
 3322: ######################################################################
 3323: 
 3324: =pod 
 3325: 
 3326: =item &fielded_format_view() 
 3327: 
 3328: =cut
 3329: 
 3330: ######################################################################
 3331: ######################################################################
 3332: sub fielded_format_view {
 3333:     my ($prefix,%values) = @_;
 3334:     my $icon=&Apache::loncommon::icon($values{'url'});
 3335:     my %Translated = &Apache::lonmeta::fieldnames();
 3336:     my $result=<<END;
 3337: $prefix <img src="$icon" />
 3338: <dl>
 3339: <dt>URL:</dt>
 3340:     <dd><a href="http://$ENV{'HTTP_HOST'}$values{'url'}" 
 3341:          target='search_preview'>$values{'url'}</a></dd>
 3342: END
 3343:     foreach my $field ('title','author','subject','keywords','notes',
 3344:                        'mimetag','language','creationdate','lastrevisiondate',
 3345:                        'owner','copyrighttag','hostname','abstract') {
 3346:         $result .= (' 'x4).'<dt>'.$Translated{$field}.'</dt>'."\n".
 3347:             (' 'x8).'<dd>'.$values{$field}.'</dd>'."\n";
 3348:     }
 3349:     if (&has_stat_data(\%values)) {
 3350:         foreach my $field (&statfields()) {
 3351:             $result .= (' 'x4).'<dt>'.$Translated{$field}.'</dt>'."\n".
 3352:                 (' 'x8).'<dd>'.$values{$field}.'</dd>'."\n";
 3353:         }
 3354:     }
 3355:     if (&has_eval_data(\%values)) {
 3356:         foreach my $field (&evalfields()) {
 3357:             $result .= (' 'x4).'<dt>'.$Translated{$field}.'</dt>'."\n".
 3358:                 (' 'x8).'<dd>'.$values{$field}.'</dd>'."\n";
 3359:         }
 3360:     }
 3361:     $result .= "</dl>\n";
 3362:     $result .= $values{'extrashow'};
 3363:     $result .= '<hr align="left" width="200" noshade />'."\n";
 3364:     return $result;
 3365: }
 3366: 
 3367: ######################################################################
 3368: ######################################################################
 3369: 
 3370: =pod 
 3371: 
 3372: =item &xml_sgml_view() 
 3373: 
 3374: =back 
 3375: 
 3376: =cut
 3377: 
 3378: ######################################################################
 3379: ######################################################################
 3380: sub xml_sgml_view {
 3381:     my ($prefix,%values) = @_;
 3382:     my $xml = '<LonCapaResource>'."\n";
 3383:     # The usual suspects
 3384:     foreach my $field ('url','title','author','subject','keywords','notes') {
 3385:         $xml .= qq{<$field>$values{$field}</$field>}."\n";
 3386:     }
 3387:     #
 3388:     $xml .= "<mimeInfo>\n";
 3389:     foreach my $field ('mime','mimetag') {
 3390:         $xml .= qq{<$field>$values{$field}</$field>}."\n";
 3391:     }
 3392:     $xml .= "</mimeInfo>\n";
 3393:     #
 3394:     $xml .= "<languageInfo>\n";
 3395:     foreach my $field ('language','languagetag') {
 3396:         $xml .= qq{<$field>$values{$field}</$field>}."\n";
 3397:     }
 3398:     $xml .= "</languageInfo>\n";
 3399:     #
 3400:     foreach my $field ('creationdate','lastrevisiondate','owner') {
 3401:         $xml .= qq{<$field>$values{$field}</$field>}."\n";
 3402:     }
 3403:     #
 3404:     $xml .= "<copyrightInfo>\n";
 3405:     foreach my $field ('copyright','copyrighttag') {
 3406:         $xml .= qq{<$field>$values{$field}</$field>}."\n";
 3407:     }
 3408:     $xml .= "</copyrightInfo>\n";
 3409:     $xml .= qq{<repositoryLocation>$values{'hostname'}</repositoryLocation>}.
 3410:         "\n";
 3411:     $xml .= qq{<shortabstract>$values{'shortabstract'}</shortabstract>}."\n";
 3412:     #
 3413:     if (&has_stat_data(\%values)){
 3414:         $xml .= "<problemstatistics>\n";
 3415:         foreach my $field (&statfields()) {
 3416:             $xml .= qq{<$field>$values{$field}</$field>}."\n";            
 3417:         }
 3418:         $xml .= "</problemstatistics>\n";
 3419:     }
 3420:     #
 3421:     if (&has_eval_data(\%values)) {
 3422:         $xml .= "<evaluation>\n";
 3423:         foreach my $field (&evalfields) {
 3424:             $xml .= qq{<$field>$values{$field}</$field>}."\n";            
 3425:         }
 3426:         $xml .= "</evaluation>\n";
 3427:     }    
 3428:     #
 3429:     $xml .= "</LonCapaResource>\n";
 3430:     $xml = &HTML::Entities::encode($xml,'<>&');
 3431:     my $result=<<END;
 3432: $prefix
 3433: <pre>
 3434: $xml
 3435: </pre>
 3436: $values{'extrashow'}
 3437: <hr align='left' width='200' noshade />
 3438: END
 3439:     return $result;
 3440: }
 3441: 
 3442: ######################################################################
 3443: ######################################################################
 3444: 
 3445: =pod 
 3446: 
 3447: =item &filled() see if field is filled.
 3448: 
 3449: =cut
 3450: 
 3451: ######################################################################
 3452: ######################################################################
 3453: sub filled {
 3454:     my ($field)=@_;
 3455:     if ($field=~/\S/ && $field ne 'any') {
 3456:         return 1;
 3457:     } else {
 3458:         return 0;
 3459:     }
 3460: }
 3461: 
 3462: ######################################################################
 3463: ######################################################################
 3464: 
 3465: =pod 
 3466: 
 3467: =item &output_unparsed_phrase_error()
 3468: 
 3469: =cut
 3470: 
 3471: ######################################################################
 3472: ######################################################################
 3473: sub output_unparsed_phrase_error {
 3474:     my ($r,$closebutton,$parms,$hidden_fields,$field)=@_;
 3475:     my $errorstring;
 3476:     if ($field eq 'basicexp') {
 3477:         $errorstring = &mt('Unable to understand the search phrase <i>[_1]</i>.  Please modify your search.',$ENV{'form.basicexp'});
 3478:     } else {
 3479:         $errorstring = &mt('Unable to understand the search phrase <b>[_1]</b>:<i>[_2]</i>.',$field,$ENV{'form.'.$field});
 3480:     }
 3481:     my $bodytag = &Apache::loncommon::bodytag('Search');
 3482:     my $heading = &mt('Unparsed Field');
 3483:     my $revise  = &mt('Revise search request');
 3484:     # make query information persistent to allow for subsequent revision
 3485:     $r->print(<<ENDPAGE);
 3486: <html>
 3487: <head>
 3488: <title>The LearningOnline Network with CAPA</title>
 3489: </head>
 3490: $bodytag
 3491: <form method="post" action="/adm/searchcat">
 3492: $hidden_fields
 3493: $closebutton
 3494: <hr />
 3495: <h2>$heading</h2>
 3496: <p>
 3497: $errorstring
 3498: </p>
 3499: <p>
 3500: <a href="/adm/searchcat?$parms&persistent_db_id=$ENV{'form.persistent_db_id'}">$revise</a>
 3501: </p>
 3502: </body>
 3503: </html>
 3504: ENDPAGE
 3505: }
 3506: 
 3507: ######################################################################
 3508: ######################################################################
 3509: 
 3510: =pod 
 3511: 
 3512: =item &output_blank_field_error()
 3513: 
 3514: Output a complete page that indicates the user has not filled in enough
 3515: information to do a search.
 3516: 
 3517: Inputs: $r (Apache request handle), $closebutton, $parms.
 3518: 
 3519: Returns: nothing
 3520: 
 3521: $parms is extra information to include in the 'Revise search request' link.
 3522: 
 3523: =cut
 3524: 
 3525: ######################################################################
 3526: ######################################################################
 3527: sub output_blank_field_error {
 3528:     my ($r,$closebutton,$parms,$hidden_fields)=@_;
 3529:     my $bodytag=&Apache::loncommon::bodytag('Search');
 3530:     my $errormsg = &mt('You did not fill in enough information for the search to be started.  You need to fill in relevant fields on the search page in order for a query to be processed.');
 3531:     my $revise = &mt('Revise Search Request');
 3532:     my $heading = &mt('Unactionable Search Queary');
 3533:     $r->print(<<ENDPAGE);
 3534: <html>
 3535: <head>
 3536: <title>The LearningOnline Network with CAPA</title>
 3537: </head>
 3538: $bodytag
 3539: <form method="post" action="/adm/searchcat">
 3540: $hidden_fields
 3541: $closebutton
 3542: <hr />
 3543: <h2>$heading</h2>
 3544: <p>
 3545: $errormsg
 3546: </p>
 3547: <p>
 3548: <a href="/adm/searchcat?$parms&persistent_db_id=$ENV{'form.persistent_db_id'}">$revise</a>&nbsp;
 3549: </p>
 3550: </body>
 3551: </html>
 3552: ENDPAGE
 3553:     return;
 3554: }
 3555: 
 3556: ######################################################################
 3557: ######################################################################
 3558: 
 3559: =pod 
 3560: 
 3561: =item &output_date_error()
 3562: 
 3563: Output a full html page with an error message.
 3564: 
 3565: Inputs: 
 3566: 
 3567:     $r, the request pointer.
 3568:     $message, the error message for the user.
 3569:     $closebutton, the specialized close button needed for groupsearch.
 3570: 
 3571: =cut
 3572: 
 3573: ######################################################################
 3574: ######################################################################
 3575: sub output_date_error {
 3576:     my ($r,$message,$closebutton,$hidden_fields)=@_;
 3577:     # make query information persistent to allow for subsequent revision
 3578:     my $bodytag=&Apache::loncommon::bodytag(undef,undef,undef,1);
 3579:     $r->print(<<RESULTS);
 3580: <html>
 3581: <head>
 3582: <title>The LearningOnline Network with CAPA</title>
 3583: </head>
 3584: $bodytag
 3585: <img align='right' src='/adm/lonIcons/lonlogos.gif' />
 3586: <h1>Search Catalog</h1>
 3587: <form method="post" action="/adm/searchcat">
 3588: $hidden_fields
 3589: <input type='button' value='Revise search request'
 3590: onClick='this.form.submit();' />
 3591: $closebutton
 3592: <hr />
 3593: <h3>Error</h3>
 3594: <p>
 3595: $message
 3596: </p>
 3597: </body>
 3598: </html>
 3599: RESULTS
 3600: }
 3601: 
 3602: ######################################################################
 3603: ######################################################################
 3604: 
 3605: =pod 
 3606: 
 3607: =item &start_fresh_session()
 3608: 
 3609: Cleans the global %groupsearch_db by removing all fields which begin with
 3610: 'pre_' or 'store'.
 3611: 
 3612: =cut
 3613: 
 3614: ######################################################################
 3615: ######################################################################
 3616: sub start_fresh_session {
 3617:     delete $groupsearch_db{'mode_catalog'};
 3618:     foreach (keys %groupsearch_db) {
 3619:         if ($_ =~ /^pre_/) {
 3620:             delete $groupsearch_db{$_};
 3621:         }
 3622:         if ($_ =~ /^store/) {
 3623: 	    delete $groupsearch_db{$_};
 3624: 	}
 3625:     }
 3626: }
 3627: 
 3628: 1;
 3629: 
 3630: sub cleanup {
 3631:     if (tied(%groupsearch_db)) {
 3632:         unless (untie(%groupsearch_db)) {
 3633: 	  &Apache::lonnet::logthis('Failed cleanup searchcat: groupsearch_db');
 3634:         }
 3635:     }
 3636:     &untiehash();
 3637:     &Apache::lonmysql::disconnect_from_db();
 3638: }
 3639: 
 3640: __END__
 3641: 
 3642: =pod
 3643: 
 3644: =back 
 3645: 
 3646: =cut

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