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

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

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