File:  [LON-CAPA] / loncom / interface / lonsearchcat.pm
Revision 1.159: download - view: text, annotated - select for diffs
Tue Oct 29 19:53:45 2002 UTC (21 years, 7 months ago) by matthew
Branches: MAIN
CVS tags: HEAD
Towards Bug 916.  Searching is a little smarter - no longer will we see
'waiting on BLANK'.   Also, the timer will count down only after all the
servers have been contacted.

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

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