File:  [LON-CAPA] / loncom / interface / lonsearchcat.pm
Revision 1.235: download - view: text, annotated - select for diffs
Fri Dec 17 21:44:19 2004 UTC (19 years, 5 months ago) by albertel
Branches: MAIN
CVS tags: version_1_3_1, version_1_3_0, HEAD
BUG#3736

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

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