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

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

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