File:  [LON-CAPA] / loncom / interface / lonsearchcat.pm
Revision 1.222: download - view: text, annotated - select for diffs
Wed May 5 14:14:10 2004 UTC (20 years, 1 month ago) by matthew
Branches: MAIN
CVS tags: HEAD
Made access count searchable.  Expanded output for xml and fielded search
result views.

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

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