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

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

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