File:  [LON-CAPA] / loncom / interface / lonsearchcat.pm
Revision 1.255: download - view: text, annotated - select for diffs
Mon Mar 6 18:23:10 2006 UTC (18 years, 3 months ago) by www
Branches: MAIN
CVS tags: HEAD
Bug #563: show preview in Search

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

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