File:  [LON-CAPA] / loncom / interface / lonsearchcat.pm
Revision 1.198: download - view: text, annotated - select for diffs
Sat Dec 27 23:04:28 2003 UTC (20 years, 5 months ago) by www
Branches: MAIN
CVS tags: HEAD
Bugs #789 and 1926: Trying to make new fields searchable, just saving my work.

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

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