File:  [LON-CAPA] / loncom / interface / lonsearchcat.pm
Revision 1.166: download - view: text, annotated - select for diffs
Mon Feb 10 21:25:43 2003 UTC (21 years, 3 months ago) by albertel
Branches: MAIN
CVS tags: HEAD
- Perl doesn't like the {} seems ambigious to it

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

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