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

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

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