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

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

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