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

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

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