File:  [LON-CAPA] / loncom / interface / lonsearchcat.pm
Revision 1.203: download - view: text, annotated - select for diffs
Thu Jan 15 03:18:19 2004 UTC (20 years, 4 months ago) by www
Branches: MAIN
CVS tags: HEAD
Help buttons

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

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