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

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

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