File:  [LON-CAPA] / loncom / interface / lonsearchcat.pm
Revision 1.194: download - view: text, annotated - select for diffs
Thu Dec 11 20:59:54 2003 UTC (20 years, 5 months ago) by albertel
Branches: MAIN
CVS tags: HEAD
- removing some logfile spew

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

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