File:  [LON-CAPA] / loncom / interface / lonsearchcat.pm
Revision 1.205: download - view: text, annotated - select for diffs
Mon Mar 8 17:31:37 2004 UTC (20 years, 2 months ago) by www
Branches: MAIN
CVS tags: HEAD
Typos: "separate"

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

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