File:  [LON-CAPA] / loncom / interface / lonsearchcat.pm
Revision 1.228: download - view: text, annotated - select for diffs
Thu Jun 3 19:23:08 2004 UTC (20 years ago) by matthew
Branches: MAIN
CVS tags: HEAD
Major changes to search phrase parsing.  Now use recursive descent parser
to make sense of phrases.  Multi-word (quoted) phrases, - (meaning not),
and 'or'd phrases are handled properly.
Added &process_phrase_input, which creates the SQL query for phrase inputs.
Removed &build_SQL_query and &recursive_SQL_query_build
Added &output_unparsed_phrase_error.
Localized &output_blank_field_error.
For basic search fixed bug where basic search phrase was not remembered
and filled in properly when the "revise search" button was hit.

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

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