File:  [LON-CAPA] / loncom / interface / lonsearchcat.pm
Revision 1.250: download - view: text, annotated - select for diffs
Thu Dec 29 19:45:19 2005 UTC (18 years, 4 months ago) by www
Branches: MAIN
CVS tags: version_2_1_2, version_2_1_1, HEAD
Bigger cluster, more time needed. Trying as work around for Bug #3377

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

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