Annotation of loncom/interface/lonsearchcat.pm, revision 1.144

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

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