File:  [LON-CAPA] / loncom / interface / lonsearchcat.pm
Revision 1.216: download - view: text, annotated - select for diffs
Fri Apr 23 17:52:55 2004 UTC (20 years, 1 month ago) by matthew
Branches: MAIN
CVS tags: HEAD
Checked every current advanced search form and ensured the mysql query is
generated properly.  Reworked handling of date queries.

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

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