File:  [LON-CAPA] / loncom / interface / lonsearchcat.pm
Revision 1.237.2.1: download - view: text, annotated - select for diffs
Fri Apr 1 20:01:32 2005 UTC (19 years, 2 months ago) by albertel
Branches: version_1_3_X
Diff to branchpoint 1.237: preferred, unified
- backport 1.242

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

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