File:  [LON-CAPA] / loncom / interface / lonsearchcat.pm
Revision 1.256: download - view: text, annotated - select for diffs
Wed Mar 15 20:56:16 2006 UTC (18 years, 2 months ago) by albertel
Branches: MAIN
CVS tags: HEAD
- converted to use the page start end helpers

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

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