File:  [LON-CAPA] / loncom / interface / lonsearchcat.pm
Revision 1.268: download - view: text, annotated - select for diffs
Thu Jun 8 16:58:56 2006 UTC (17 years, 11 months ago) by www
Branches: MAIN
CVS tags: HEAD
Still trying to export the search results into IMPORT ...

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

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