File:  [LON-CAPA] / loncom / interface / lonsearchcat.pm
Revision 1.213: download - view: text, annotated - select for diffs
Wed Apr 21 15:48:34 2004 UTC (20 years, 1 month ago) by matthew
Branches: MAIN
CVS tags: HEAD
Reworked basic search interface.  No feature changes, it's just less un-pretty.

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

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