File:  [LON-CAPA] / loncom / interface / lonsearchcat.pm
Revision 1.160: download - view: text, annotated - select for diffs
Sun Nov 3 19:03:29 2002 UTC (21 years, 7 months ago) by www
Branches: MAIN
CVS tags: HEAD
Bug #928
Forward "catalogmode" to Advanced Search, making it possible to use
"Advanced" for "Group Search"

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

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