File:  [LON-CAPA] / loncom / interface / lonsearchcat.pm
Revision 1.224: download - view: text, annotated - select for diffs
Fri May 7 18:50:14 2004 UTC (20 years, 1 month ago) by matthew
Branches: MAIN
CVS tags: HEAD
Bug 1030: Multiple words search always fails.
Now split whitespace separated words apart.  Quoted items are handled properly.
Added &process_phrase_input to do this.
Simplified &related_version since it gets more regular inputs now.
Modified &parse_basic_search and &parse_advanced_search to use this new
method.

Added breadcrumbs to search results output.
Corrected misspelling of 'Correct' in &detailed_citation_view.

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

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