File:  [LON-CAPA] / loncom / interface / lonsearchcat.pm
Revision 1.154: download - view: text, annotated - select for diffs
Wed Aug 21 17:18:08 2002 UTC (21 years, 9 months ago) by www
Branches: MAIN
CVS tags: HEAD
Starting to implement common header and color scheme for LON-CAPA handlers
(non-content pages).

Instead of <body bgcolor="#...."><h1>... call

   &Apache::loncommon::bodytag(title,[role],[add_body_parms]);

title: what it says in the header
role (OPTIONAL): override role choice
                 ('admin','coordinator','student','author')
add_body_parms: additional parameters to be put into the body tag, for
                example 'onLoad="init();" or stuff

Colors and layout will likely change in the future, including domain
customization, help function calls, (css?)

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

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