File:  [LON-CAPA] / loncom / interface / lonsearchcat.pm
Revision 1.208: download - view: text, annotated - select for diffs
Mon Apr 19 14:42:24 2004 UTC (20 years, 1 month ago) by matthew
Branches: MAIN
CVS tags: HEAD
Cosmetic interface changes.

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

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