File:  [LON-CAPA] / loncom / interface / lonsearchcat.pm
Revision 1.215: download - view: text, annotated - select for diffs
Thu Apr 22 20:05:18 2004 UTC (20 years, 1 month ago) by matthew
Branches: MAIN
CVS tags: HEAD
Remove debug spew.

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

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