File:  [LON-CAPA] / loncom / interface / lonsearchcat.pm
Revision 1.227: download - view: text, annotated - select for diffs
Mon May 10 18:59:18 2004 UTC (20 years, 2 months ago) by matthew
Branches: MAIN
CVS tags: HEAD
Include menu link in breadcrumbs when we are not doing a groupsearch.
Added 'authorspace' to the list of searchable fields.

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

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