File:  [LON-CAPA] / loncom / interface / lonsearchcat.pm
Revision 1.211: download - view: text, annotated - select for diffs
Mon Apr 19 17:44:47 2004 UTC (20 years, 2 months ago) by matthew
Branches: MAIN
CVS tags: HEAD
Log MySQL table creation error instead of abusing the user with them.

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

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