File:  [LON-CAPA] / loncom / interface / lonsearchcat.pm
Revision 1.156: download - view: text, annotated - select for diffs
Mon Sep 16 12:52:33 2002 UTC (21 years, 8 months ago) by matthew
Branches: MAIN
CVS tags: HEAD
Changes to address at least part of bug 775.  Changed the logic which
determines when to clean out the groupsearch database file.  Previously it
only occurred if the results were about to be displayed.  This was unfortunate
because the parameter which triggered it is deleted before then.

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

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