File:  [LON-CAPA] / loncom / interface / lonsearchcat.pm
Revision 1.262: download - view: text, annotated - select for diffs
Tue Apr 11 19:53:11 2006 UTC (18 years, 1 month ago) by albertel
Branches: MAIN
CVS tags: HEAD

- start_page + frameset

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

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