File:  [LON-CAPA] / loncom / interface / lonsearchcat.pm
Revision 1.153.2.1: download - view: text, annotated - select for diffs
Mon Sep 16 13:05:54 2002 UTC (21 years, 8 months ago) by matthew
Branches: fixes_0_5
Diff to branchpoint 1.153: preferred, unified
Backport of initial fix for bug 775.

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

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