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

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

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