File:  [LON-CAPA] / loncom / interface / lonsearchcat.pm
Revision 1.157: download - view: text, annotated - select for diffs
Mon Sep 16 20:09:45 2002 UTC (21 years, 8 months ago) by www
Branches: MAIN
CVS tags: HEAD
Overload protection

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

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