File:  [LON-CAPA] / loncom / interface / lonsearchcat.pm
Revision 1.207: download - view: text, annotated - select for diffs
Mon Apr 19 13:51:36 2004 UTC (20 years, 1 month ago) by matthew
Branches: MAIN
CVS tags: HEAD
Added &search_html_header() to consolidate a little code.  Removed weird
background color in table.

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

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