File:  [LON-CAPA] / loncom / interface / lonsearchcat.pm
Revision 1.151: download - view: text, annotated - select for diffs
Sun Aug 4 18:28:01 2002 UTC (21 years, 10 months ago) by matthew
Branches: MAIN
CVS tags: HEAD
Added 'show', the number of results to show per page, as a form parameter -
Added 'show', the number of results to display per page, as a form parameter
   defaults to 20 but can be selected to be 10,20,50, or 100.
Added a 'sort' phase, which calls the new &print_sort_form function.
   The sort phase is automatically called after a search is run.
Added a 'revise search' button to run_search and the sort phase.
Added parameter to &output_blank_field_error so it can take you to the right
   search phase (disp_basic or disp_adv) after it chides you.
&ensure_db_and_table is a new function made up of code taken from run_search
   that was also needed for the sort form.  This function connects lonmysql
   to MySQL and makes sure our table is there.
&print_sort_form outputs a sorting form.  Or rather, it WILL do that someday.
   Currently just tells the user about their search and prints a
   'revise search' button.
Changed $Datatypes{'id'}->{'type'} and {'restrictions'} because I am learning
    more about MySQL every day.

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

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