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

1.98      harris41    1: # The LearningOnline Network with CAPA
1.108     harris41    2: # Search Catalog
                      3: #
1.231   ! raeburn     4: # $Id: lonsearchcat.pm,v 1.230 2004/06/28 15:55:09 matthew Exp $
1.108     harris41    5: #
                      6: # Copyright Michigan State University Board of Trustees
                      7: #
                      8: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
                      9: #
                     10: # LON-CAPA is free software; you can redistribute it and/or modify
                     11: # it under the terms of the GNU General Public License as published by
                     12: # the Free Software Foundation; either version 2 of the License, or
                     13: # (at your option) any later version.
1.98      harris41   14: #
1.108     harris41   15: # LON-CAPA is distributed in the hope that it will be useful,
                     16: # but WITHOUT ANY WARRANTY; without even the implied warranty of
                     17: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
                     18: # GNU General Public License for more details.
                     19: #
                     20: # You should have received a copy of the GNU General Public License
                     21: # along with LON-CAPA; if not, write to the Free Software
                     22: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
                     23: #
                     24: # /home/httpd/html/adm/gpl.txt
                     25: #
                     26: # http://www.lon-capa.org/
1.1       www        27: #
1.121     matthew    28: ###############################################################################
                     29: ###############################################################################
                     30: 
                     31: =pod 
                     32: 
                     33: =head1 NAME
                     34: 
1.140     matthew    35: lonsearchcat - LONCAPA Search Interface
1.121     matthew    36: 
                     37: =head1 SYNOPSIS
                     38: 
                     39: Search interface to LON-CAPAs digital library
                     40: 
                     41: =head1 DESCRIPTION
                     42: 
                     43: This module enables searching for a distributed browseable catalog.
1.104     harris41   44: 
1.121     matthew    45: This is part of the LearningOnline Network with CAPA project
                     46: described at http://www.lon-capa.org.
                     47: 
                     48: lonsearchcat presents the user with an interface to search the LON-CAPA
                     49: digital library.  lonsearchcat also initiates the execution of a search
                     50: by sending the search parameters to LON-CAPA servers.  The progress of 
1.205     www        51: search (on a server basis) is displayed to the user in a separate window.
1.121     matthew    52: 
                     53: =head1 Internals
                     54: 
                     55: =over 4
                     56: 
                     57: =cut
                     58: 
                     59: ###############################################################################
1.98      harris41   60: ###############################################################################
1.121     matthew    61: 
1.1       www        62: package Apache::lonsearchcat;
                     63: 
                     64: use strict;
1.167     www        65: use Apache::Constants qw(:common :http);
1.6       harris41   66: use Apache::lonnet();
                     67: use Apache::File();
1.7       harris41   68: use CGI qw(:standard);
1.41      harris41   69: use Text::Query;
1.101     harris41   70: use GDBM_File;
1.112     harris41   71: use Apache::loncommon();
1.144     matthew    72: use Apache::lonmysql();
1.200     www        73: use Apache::lonmeta;
                     74: use Apache::lonhtmlcommon;
1.186     www        75: use Apache::lonlocal;
1.204     matthew    76: use LONCAPA::lonmetadata();
1.212     matthew    77: use HTML::Entities();
1.228     matthew    78: use Parse::RecDescent;
1.231   ! raeburn    79: use Apache::lonnavmaps;
1.1       www        80: 
1.121     matthew    81: ######################################################################
                     82: ######################################################################
1.196     matthew    83: ##
                     84: ## Global variables
                     85: ##
1.121     matthew    86: ######################################################################
                     87: ######################################################################
1.196     matthew    88: my %groupsearch_db;  # Database hash used to save values for the 
                     89:                      # groupsearch RAT interface.
                     90: my %persistent_db;   # gdbm hash which holds data which is supposed to
                     91:                      # persist across calls to lonsearchcat.pm
1.121     matthew    92: 
1.200     www        93: # The different view modes and associated functions
                     94: 
                     95: my %Views = ("detailed" => \&detailed_citation_view,
                     96: 	     "summary"  => \&summary_view,
                     97: 	     "fielded"  => \&fielded_format_view,
                     98: 	     "xml"      => \&xml_sgml_view,
                     99: 	     "compact"  => \&compact_view);
1.101     harris41  100: 
1.121     matthew   101: ######################################################################
                    102: ######################################################################
1.98      harris41  103: sub handler {
                    104:     my $r = shift;
1.197     www       105: #    &set_defaults();
1.196     matthew   106:     #
                    107:     # set form defaults
1.145     matthew   108:     #
1.196     matthew   109:     my $hidden_fields;# Hold all the hidden fields used to keep track
                    110:                       # of the search system state
                    111:     my $importbutton; # button to take the selected results and go to group 
                    112:                       # sorting
                    113:     my $diropendb;    # The full path to the (temporary) search database file.
                    114:                       # This is set and used in &handler() and is also used in 
                    115:                       # &output_results().
                    116:     my $bodytag;  # LON-CAPA standard body tag, gotten from 
                    117:                   # &Apache::lonnet::bodytag. 
                    118:                   # No title, no table, just a <body> tag.
1.157     www       119: 
                    120:     my $loaderror=&Apache::lonnet::overloaderror($r);
                    121:     if ($loaderror) { return $loaderror; }
1.221     matthew   122:     #
1.145     matthew   123:     my $closebutton;  # button that closes the search window 
                    124:                       # This button is different for the RAT compared to
                    125:                       # normal invocation.
                    126:     #
1.186     www       127:     &Apache::loncommon::content_type($r,'text/html');
1.98      harris41  128:     $r->send_http_header;
                    129:     return OK if $r->header_only;
1.156     matthew   130:     ##
                    131:     ## Prevent caching of the search interface window.  Hopefully this means
                    132:     ## we will get the launch=1 passed in a little more.
                    133:     &Apache::loncommon::no_cache($r);
1.145     matthew   134:     ## 
                    135:     ## Pick up form fields passed in the links.
                    136:     ##
                    137:     &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
1.146     matthew   138:              ['catalogmode','launch','acts','mode','form','element','pause',
1.158     matthew   139:               'phase','persistent_db_id','table','start','show',
1.191     albertel  140:               'cleargroupsort','titleelement']);
1.146     matthew   141:     ##
                    142:     ## The following is a trick - we wait a few seconds if asked to so
                    143:     ##     the daemon running the search can get ahead of the daemon
                    144:     ##     printing the results.  We only need (theoretically) to do
                    145:     ##     this once, so the pause indicator is deleted
                    146:     ##
                    147:     if (exists($ENV{'form.pause'})) {
1.181     matthew   148:         sleep(1);
1.146     matthew   149:         delete($ENV{'form.pause'});
                    150:     }
1.143     matthew   151:     ##
                    152:     ## Initialize global variables
                    153:     ##
1.121     matthew   154:     my $domain  = $r->dir_config('lonDefDomain');
1.213     matthew   155:     $diropendb= "/home/httpd/perl/tmp/".
                    156:         "$ENV{'user.domain'}_$ENV{'user.name'}_searchcat.db";
1.145     matthew   157:     #
                    158:     # set the name of the persistent database
1.146     matthew   159:     #          $ENV{'form.persistent_db_id'} can only have digits in it.
1.145     matthew   160:     if (! exists($ENV{'form.persistent_db_id'}) ||
1.147     matthew   161:         ($ENV{'form.persistent_db_id'} =~ /\D/) ||
                    162:         ($ENV{'form.launch'} eq '1')) {
1.145     matthew   163:         $ENV{'form.persistent_db_id'} = time;
                    164:     }
1.155     matthew   165:     $bodytag=&Apache::loncommon::bodytag(undef,undef,undef,1);
1.146     matthew   166:     my $persistent_db_file = "/home/httpd/perl/tmp/".
1.145     matthew   167:         &Apache::lonnet::escape($domain).
                    168:             '_'.&Apache::lonnet::escape($ENV{'user.name'}).
                    169:                 '_'.$ENV{'form.persistent_db_id'}.'_persistent_search.db';
1.146     matthew   170:     ##
1.209     matthew   171:     &Apache::lonhtmlcommon::clear_breadcrumbs();
                    172:     if (exists($ENV{'request.course.id'}) && $ENV{'request.course.id'} ne '') {
                    173:         &Apache::lonhtmlcommon::add_breadcrumb
                    174:              ({href=>'/adm/searchcat?'.
                    175:                    'catalogmode='.$ENV{'form.catalogmode'}.
                    176:                    '&launch='.$ENV{'form.launch'}.
                    177:                    '&mode='.$ENV{'form.mode'},
                    178:               text=>"Course and Catalog Search",
1.227     matthew   179:               target=>'_top',
1.209     matthew   180:               bug=>'Searching',});
                    181:     } else {
                    182:         &Apache::lonhtmlcommon::add_breadcrumb
                    183:              ({href=>'/adm/searchcat?'.
                    184:                    'catalogmode='.$ENV{'form.catalogmode'}.
                    185:                    '&launch='.$ENV{'form.launch'}.
                    186:                    '&mode='.$ENV{'form.mode'},
                    187:               text=>"Catalog Search",
1.227     matthew   188:               target=>'_top',
1.209     matthew   189:               bug=>'Searching',});
                    190:     }
                    191:     #
1.221     matthew   192:     if ($ENV{'form.phase'} !~ m/(basic|adv|course)_search/) {
                    193:         if (! &get_persistent_form_data($persistent_db_file)) {
                    194:             if ($ENV{'form.phase'} =~ /(run_search|results)/) {
                    195:                 &Apache::lonnet::logthis('lonsearchcat:'.
                    196:                                          'Unable to recover data from '.
                    197:                                          $persistent_db_file);
                    198:                 $r->print(<<END);
1.150     matthew   199: <html>
                    200: <head><title>LON-CAPA Search Error</title></head>
1.155     matthew   201: $bodytag
1.150     matthew   202: We were unable to retrieve data describing your search.  This is a serious
                    203: error and has been logged.  Please alert your LON-CAPA administrator.
                    204: </body>
                    205: </html>
                    206: END
1.221     matthew   207:                 return OK;
                    208:             }
1.150     matthew   209:         }
1.221     matthew   210:     } else {
                    211:         &clean_up_environment();
1.147     matthew   212:     }
1.124     matthew   213:     ##
1.143     matthew   214:     ## Clear out old values from groupsearch database
1.124     matthew   215:     ##
1.146     matthew   216:     untie %groupsearch_db if (tied(%groupsearch_db));
1.158     matthew   217:     if (($ENV{'form.cleargroupsort'} eq '1') || 
                    218:         (($ENV{'form.launch'} eq '1') && 
                    219:          ($ENV{'form.catalogmode'} eq 'groupsearch'))) {
1.148     matthew   220: 	if (tie(%groupsearch_db,'GDBM_File',$diropendb,&GDBM_WRCREAT(),0640)) {
1.101     harris41  221: 	    &start_fresh_session();
1.142     matthew   222: 	    untie %groupsearch_db;
1.158     matthew   223:             delete($ENV{'form.cleargroupsort'});
1.122     matthew   224: 	} else {
1.155     matthew   225:             # This is a stupid error to give to the user.  
                    226:             # It really tells them nothing.
                    227: 	    $r->print('<html><head></head>'.$bodytag.
                    228:                       'Unable to tie hash to db file</body></html>');
1.101     harris41  229: 	    return OK;
                    230: 	}
                    231:     }
1.124     matthew   232:     ##
1.150     matthew   233:     ## Configure hidden fields
1.124     matthew   234:     ##
1.145     matthew   235:     $hidden_fields = '<input type="hidden" name="persistent_db_id" value="'.
1.150     matthew   236:         $ENV{'form.persistent_db_id'}.'" />'."\n";
                    237:     if (exists($ENV{'form.catalogmode'})) {
1.223     matthew   238:         $hidden_fields .= &hidden_field('catalogmode');
1.150     matthew   239:     }
                    240:     if (exists($ENV{'form.form'})) {
1.223     matthew   241:         $hidden_fields .= &hidden_field('form');
1.150     matthew   242:     }
                    243:     if (exists($ENV{'form.element'})) {
1.223     matthew   244:         $hidden_fields .= &hidden_field('element');
1.150     matthew   245:     }
1.191     albertel  246:     if (exists($ENV{'form.titleelement'})) {
1.223     matthew   247:         $hidden_fields .= &hidden_field('titleelement');
1.191     albertel  248:     }
1.150     matthew   249:     if (exists($ENV{'form.mode'})) {
1.223     matthew   250:         $hidden_fields .= &hidden_field('mode');
1.150     matthew   251:     }
                    252:     ##
                    253:     ## Configure dynamic components of interface
1.146     matthew   254:     ##
1.98      harris41  255:     if ($ENV{'form.catalogmode'} eq 'interactive') {
1.150     matthew   256:         $closebutton="<input type='button' name='close' value='CLOSE' ";
                    257:         if ($ENV{'form.phase'} =~ /(results|run_search)/) {
                    258: 	    $closebutton .="onClick='parent.close()'";
                    259:         } else {
                    260:             $closebutton .="onClick='self.close()'";
                    261:         }
                    262:         $closebutton .=">\n";
1.124     matthew   263:     } elsif ($ENV{'form.catalogmode'} eq 'groupsearch') {
1.150     matthew   264:         $closebutton="<input type='button' name='close' value='CLOSE' ";
                    265:         if ($ENV{'form.phase'} =~ /(results|run_search)/) {
                    266: 	    $closebutton .="onClick='parent.close()'";
                    267:         } else {
                    268:             $closebutton .="onClick='self.close()'";
                    269:         }
                    270:         $closebutton .= ">";
1.98      harris41  271:         $importbutton=<<END;
                    272: <input type='button' name='import' value='IMPORT'
                    273: onClick='javascript:select_group()'>
                    274: END
1.146     matthew   275:     } else {
                    276:         $closebutton = '';
                    277:         $importbutton = '';
1.98      harris41  278:     }
1.124     matthew   279:     ##
1.146     matthew   280:     ## Sanity checks on form elements
1.124     matthew   281:     ##
1.146     matthew   282:     if (!defined($ENV{'form.viewselect'})) {
1.150     matthew   283:         if (($ENV{'form.catalogmode'} eq 'groupsearch') ||
                    284:             ($ENV{'form.catalogmode'} eq 'interactive')) {
                    285:             $ENV{'form.viewselect'} ="Compact View";
                    286:         } else {
                    287:             $ENV{'form.viewselect'} ="Detailed Citation View";
                    288:         }
1.146     matthew   289:     }
1.149     matthew   290:     $ENV{'form.phase'} = 'disp_basic' if (! exists($ENV{'form.phase'}));
1.151     matthew   291:     $ENV{'form.show'} = 20 if (! exists($ENV{'form.show'}));
1.209     matthew   292:     #
1.219     matthew   293:     $ENV{'form.searchmode'} = 'basic' if (! exists($ENV{'form.searchmode'}));
1.209     matthew   294:     if ($ENV{'form.phase'} eq 'adv_search' ||
                    295:         $ENV{'form.phase'} eq 'disp_adv') {
                    296:         $ENV{'form.searchmode'} = 'advanced';
                    297:     } elsif ($ENV{'form.phase'} eq 'course_search') {
                    298:         $ENV{'form.searchmode'} = 'course_search';
                    299:     }
                    300:     #
                    301:     if ($ENV{'form.searchmode'} eq 'advanced') {
                    302:         &Apache::lonhtmlcommon::add_breadcrumb
                    303:             ({href=>'/adm/searchcat?phase=disp_adv&'.
                    304:                   'catalogmode='.$ENV{'form.catalogmode'}.
                    305:                   '&launch='.$ENV{'form.launch'}.
                    306:                   '&mode='.$ENV{'form.mode'},
                    307:                   text=>"Advanced Search",
                    308:                   bug=>'Searching',});
                    309:     } elsif ($ENV{'form.searchmode'} eq 'course search') {
                    310:         &Apache::lonhtmlcommon::add_breadcrumb
                    311:             ({href=>'/adm/searchcat?phase=disp_adv&'.
                    312:                   'catalogmode='.$ENV{'form.catalogmode'}.
                    313:                   '&launch='.$ENV{'form.launch'}.
                    314:                   '&mode='.$ENV{'form.mode'},
                    315:                   text=>"Course Search",
                    316:                   bug=>'Searching',});
                    317:     }
1.146     matthew   318:     ##
                    319:     ## Switch on the phase
                    320:     ##
                    321:     if ($ENV{'form.phase'} eq 'disp_basic') {
1.196     matthew   322:         &print_basic_search_form($r,$closebutton,$hidden_fields);
1.146     matthew   323:     } elsif ($ENV{'form.phase'} eq 'disp_adv') {
1.196     matthew   324:         &print_advanced_search_form($r,$closebutton,$hidden_fields);
1.146     matthew   325:     } elsif ($ENV{'form.phase'} eq 'results') {
1.196     matthew   326:         &display_results($r,$importbutton,$closebutton,$diropendb);
1.151     matthew   327:     } elsif ($ENV{'form.phase'} =~ /^(sort|run_search)$/) {
1.146     matthew   328:         my ($query,$customquery,$customshow,$libraries,$pretty_string) =
                    329:             &get_persistent_data($persistent_db_file,
                    330:                  ['query','customquery','customshow',
                    331:                   'libraries','pretty_string']);
1.151     matthew   332:         if ($ENV{'form.phase'} eq 'sort') {
                    333:             &print_sort_form($r,$pretty_string);
                    334:         } elsif ($ENV{'form.phase'} eq 'run_search') {
                    335:             &run_search($r,$query,$customquery,$customshow,
                    336:                         $libraries,$pretty_string);
                    337:         }
1.167     www       338:     } elsif ($ENV{'form.phase'} eq 'course_search') {
                    339:         &course_search($r);
1.146     matthew   340:     } elsif(($ENV{'form.phase'} eq 'basic_search') ||
                    341:             ($ENV{'form.phase'} eq 'adv_search')) {
1.228     matthew   342:         #
                    343:         # We are running a search, try to parse it
                    344:         my ($query,$customquery,$customshow,$libraries) = 
                    345:             (undef,undef,undef,undef);
                    346:         my $pretty_string;
                    347:         if ($ENV{'form.phase'} eq 'basic_search') {
                    348:             ($query,$pretty_string,$libraries) = 
                    349:                 &parse_basic_search($r,$closebutton,$hidden_fields);
                    350:             return OK if (! defined($query));
                    351:             &make_persistent({ basicexp => $ENV{'form.basicexp'}},
                    352:                              $persistent_db_file);
                    353:         } else {                      # Advanced search
                    354:             ($query,$customquery,$customshow,$libraries,$pretty_string) 
                    355:                 = &parse_advanced_search($r,$closebutton,$hidden_fields);
                    356:             return OK if (! defined($query));
                    357:         }
                    358:         &make_persistent({ query => $query,
                    359:                            customquery => $customquery,
                    360:                            customshow => $customshow,
                    361:                            libraries => $libraries,
                    362:                            pretty_string => $pretty_string },
                    363:                          $persistent_db_file);
                    364:         #
1.146     matthew   365:         # Set up table
                    366:         if (! defined(&create_results_table())) {
1.198     www       367: 	    my $errorstring=&Apache::lonmysql::get_error();
1.211     matthew   368:             &Apache::lonnet::logthis('lonsearchcat.pm: Unable to create '.
                    369:                                      'needed table.  lonmysql error:'.
                    370:                                      $errorstring);
1.147     matthew   371:             $r->print(<<END);
                    372: <html><head><title>Search Error</title></head>
1.155     matthew   373: $bodytag
1.147     matthew   374: Unable to create table in which to store search results.  
                    375: The search has been aborted.
                    376: </body>
                    377: </html>
                    378: END
                    379:             return OK;
1.146     matthew   380:         }
1.147     matthew   381:         delete($ENV{'form.launch'});
1.146     matthew   382:         if (! &make_form_data_persistent($r,$persistent_db_file)) {
1.147     matthew   383:             $r->print(<<END);
                    384: <html><head><title>Search Error</title></head>
1.155     matthew   385: $bodytag
1.147     matthew   386: Unable to properly store search information.  The search has been aborted.
                    387: </body>
                    388: </html>
                    389: END
                    390:             return OK;
1.146     matthew   391:         }
1.145     matthew   392:         ##
1.146     matthew   393:         ## Print out the frames interface
1.145     matthew   394:         ##
1.228     matthew   395:         if (defined($query)) {
                    396:             &print_frames_interface($r);
                    397:         }
1.124     matthew   398:     }
                    399:     return OK;
                    400: } 
1.98      harris41  401: 
1.221     matthew   402: #
                    403: # The mechanism used to store values away and retrieve them does not
                    404: # handle the case of missing environment variables being significant.
                    405: #
                    406: # This routine sets non existant checkbox form elements to ''.
                    407: #
                    408: sub clean_up_environment {
                    409:     if ($ENV{'form.phase'} eq 'basic_search') {
                    410:         if (! exists($ENV{'form.related'})) {
                    411:             $ENV{'form.related'} = '';
                    412:         }
                    413:         if (! exists($ENV{'form.domains'})) {
                    414:             $ENV{'form.domains'} = '';
                    415:         }
                    416:     } elsif ($ENV{'form.phase'} eq 'adv_search') {
                    417:         foreach my $field ('title','keywords','notes',
                    418:                            'abstract','standards','mime') {
                    419:             if (! exists($ENV{'form.'.$field.'_related'})) {
                    420:                 $ENV{'form.'.$field.'_related'} = '';
                    421:             }
                    422:         }
                    423:     } elsif ($ENV{'form.phase'} eq 'course_search') {
                    424:         if (! exists($ENV{'form.crsrelated'})) {
                    425:             $ENV{'form.crsrelated'} = '';
                    426:         }
                    427:     }
                    428: }
                    429: 
1.223     matthew   430: sub hidden_field {
                    431:     my ($name,$value) = @_;
                    432:     if (! defined($value)) {
                    433:         $value = $ENV{'form.'.$name};
                    434:     }
                    435:     return '<input type="hidden" name="'.$name.'" value="'.$value.'" />'.$/;
                    436: }
                    437: 
1.124     matthew   438: ######################################################################
                    439: ######################################################################
1.196     matthew   440: ##
                    441: ##   Course Search
                    442: ##
                    443: ######################################################################
                    444: ######################################################################
                    445: {   # Scope the course search to avoid global variables
                    446: #
                    447: # Variables For course search
                    448: my %alreadyseen;
                    449: my %hash;
                    450: my $totalfound;
1.124     matthew   451: 
1.167     www       452: sub course_search {
                    453:     my $r=shift;
1.217     matthew   454:     my $bodytag=&Apache::loncommon::bodytag('Course Search');
1.167     www       455:     my $pretty_search_string = '<b>'.$ENV{'form.courseexp'}.'</b>';
                    456:     my $search_string = $ENV{'form.courseexp'};
                    457:     my @New_Words;
                    458:     if ($ENV{'form.crsrelated'}) {
                    459:         ($search_string,@New_Words) = &related_version($ENV{'form.courseexp'});
                    460:         if (@New_Words) {
1.200     www       461:             $pretty_search_string .= ' '.&mt("with related words").": <b>@New_Words</b>.";
1.167     www       462:         } else {
1.200     www       463:             $pretty_search_string .= ' '.&mt('with no related words').".";
1.167     www       464:         }
                    465:     }
                    466:     my $fulltext=$ENV{'form.crsfulltext'};
1.231   ! raeburn   467:     my $discuss=$ENV{'form.crsdiscuss'};
1.167     www       468:     my @allwords=($search_string,@New_Words);
1.169     www       469:     $totalfound=0;
1.167     www       470:     $r->print('<html><head><title>LON-CAPA Course Search</title></head>'.
1.231   ! raeburn   471: 	      $bodytag.'<hr /><center><font size="+2" face="arial">'.$pretty_search_string.'</font></center><hr /><b>'.&mt('Course content').':</b><br />');
1.167     www       472:     $r->rflush();
                    473: # ======================================================= Go through the course
1.196     matthew   474:     undef %alreadyseen;
                    475:     %alreadyseen=();
1.169     www       476:     my $c=$r->connection;
1.196     matthew   477:     if (tie(%hash,'GDBM_File',$ENV{'request.course.fn'}.".db",
                    478:             &GDBM_READER(),0640)) {
                    479:         foreach (keys %hash) {
                    480:             if ($c->aborted()) { last; }
                    481:             if (($_=~/^src\_(.+)$/) && (!$alreadyseen{$hash{$_}})) {
                    482:                 &checkonthis($r,$hash{$_},0,$hash{'title_'.$1},$fulltext,
                    483:                              @allwords);
                    484:             }
                    485:         }
                    486:         untie(%hash);
                    487:     }
1.169     www       488:     unless ($totalfound) {
1.231   ! raeburn   489: 	$r->print('<p>'.&mt('No matches found in resources').'.</p>');
1.169     www       490:     }
1.231   ! raeburn   491: 
        !           492: # Check discussions if requested
        !           493:     if ($discuss) {
        !           494:         my $totaldiscussions = 0;
        !           495:         $r->print('<br /><br /><b>'.&mt('Discussion postings').':</b><br />'); 
        !           496:         my $navmap = Apache::lonnavmaps::navmap->new();
        !           497:         my @allres=$navmap->retrieveResources();
        !           498:         my %discussiontime = &Apache::lonnet::dump('discussiontimes',
        !           499:                                $ENV{'course.'.$ENV{'request.course.id'}.'.domain'},
        !           500:                                $ENV{'course.'.$ENV{'request.course.id'}.'.num'});
        !           501:         foreach my $resource (@allres) {
        !           502:             my $result = '';
        !           503:             my $applies = 0;
        !           504:             my $symb = $resource->symb();
        !           505:             my $ressymb = $symb;
        !           506:             if ($symb =~ m#(___adm/\w+/\w+)/(\d+)/bulletinboard$#) {
        !           507:                 $ressymb = 'bulletin___'.$2.$1.'/'.$2.'/bulletinboard';
        !           508:                 unless ($ressymb =~ m#bulletin___\d+___adm/wrapper#) {
        !           509:                     $ressymb=~s#(bulletin___\d+___)#$1adm/wrapper/#;
        !           510:                 }
        !           511:             }
        !           512:             if (defined($discussiontime{$ressymb})) { 
        !           513:                 my %contrib = &Apache::lonnet::restore($ressymb,$ENV{'request.course.id'},
        !           514:                      $ENV{'course.'.$ENV{'request.course.id'}.'.domain'},
        !           515:                      $ENV{'course.'.$ENV{'request.course.id'}.'.num'});
        !           516:                 if ($contrib{'version'}) {
        !           517:                     for (my $id=1;$id<=$contrib{'version'};$id++) {
        !           518:                         unless (($contrib{'hidden'}=~/\.$id\./) || ($contrib{'deleted'}=~/\.$id\./)) { 
        !           519:                             if ($contrib{$id.':subject'}) {
        !           520:                                 $result .= $contrib{$id.':subject'};
        !           521:                             }
        !           522:                             if ($contrib{$id.':message'}) {
        !           523:                                 $result .= $contrib{$id.':message'};
        !           524:                             }
        !           525:                             if ($contrib{$id,':attachmenturl'}) {
        !           526:                                 if ($contrib{$id,':attachmenturl'} =~ m-/([^/]+)$-) {
        !           527:                                     $result .= $1;
        !           528:                                 }
        !           529:                             }
        !           530:                             $applies = &checkwords($result,$applies,@allwords);
        !           531:                         }
        !           532:                     }
        !           533:                 }
        !           534:             }
        !           535: # Does this discussion apply?
        !           536:             if ($applies) {
        !           537:                 my ($map,$ind,$url)=&Apache::lonnet::decode_symb($ressymb);
        !           538:                 my $disctype = &mt('resource');
        !           539:                 if ($url =~ m#/bulletinboard$#) {
        !           540:                     if ($url =~m#^adm/wrapper/adm/.*/bulletinboard$#) {
        !           541:                         $url =~s#^adm/wrapper##;
        !           542:                     }
        !           543:                     $disctype = &mt('bulletin board');
        !           544:                 } else {
        !           545:                     $url = '/res/'.$url;
        !           546:                 }
        !           547:                 if ($url =~ /\?/) {
        !           548:                     $url .= '&symb=';
        !           549:                 } else {
        !           550:                     $url .= '?symb=';
        !           551:                 }
        !           552:                 $url .= &Apache::lonnet::escape($resource->symb());
        !           553:                 my $title = $resource->compTitle();
        !           554:                 $r->print('<br /><a href="'.$url.'" target="cat">'.
        !           555:                      ($title?$title:$url).'</a>&nbsp;&nbsp;-&nbsp;'.$disctype.'<br />');
        !           556:                 $totaldiscussions++;
        !           557:             } else {
        !           558:                 $r->print(' .');
        !           559:             }
        !           560:         }
        !           561:         unless ($totaldiscussions) {
        !           562:             $r->print('<p>'.&mt('No matches found in postings').'.</p>');
        !           563:         }
        !           564:     }
        !           565:  
1.167     www       566: # =================================================== Done going through course
                    567:     $r->print('</body></html>');
                    568: }
                    569: 
                    570: # =============================== This pulls up a resource and its dependencies
                    571: 
                    572: sub checkonthis {
1.168     www       573:     my ($r,$url,$level,$title,$fulltext,@allwords)=@_;
1.167     www       574:     $alreadyseen{$url}=1;
                    575:     $r->rflush();
                    576:     my $result=&Apache::lonnet::metadata($url,'title').' '.
                    577:                &Apache::lonnet::metadata($url,'subject').' '.
                    578:                &Apache::lonnet::metadata($url,'abstract').' '.
                    579:                &Apache::lonnet::metadata($url,'keywords');
                    580:     if (($url) && ($fulltext)) {
1.168     www       581: 	$result.=&Apache::lonnet::ssi_body($url);
1.167     www       582:     }
                    583:     $result=~s/\s+/ /gs;
1.231   ! raeburn   584:     my $applies = 0;
        !           585:     $applies = &checkwords($result,$applies,@allwords);
1.167     www       586: # Does this resource apply?
                    587:     if ($applies) {
                    588:        $r->print('<br />');
                    589:        for (my $i=0;$i<=$level*5;$i++) {
                    590:            $r->print('&nbsp;');
                    591:        }
                    592:        $r->print('<a href="'.$url.'" target="cat">'.
1.169     www       593: 		 ($title?$title:$url).'</a><br />');
                    594:        $totalfound++;
                    595:     } elsif ($fulltext) {
                    596:        $r->print(' .');
1.167     www       597:     }
1.169     www       598:     $r->rflush();
1.167     www       599: # Check also the dependencies of this one
                    600:     my $dependencies=
                    601:                 &Apache::lonnet::metadata($url,'dependencies');
                    602:     foreach (split(/\,/,$dependencies)) {
                    603:        if (($_=~/^\/res\//) && (!$alreadyseen{$_})) {
1.168     www       604:           &checkonthis($r,$_,$level+1,'',$fulltext,@allwords);
1.167     www       605:        }
                    606:     }
                    607: }
                    608: 
1.231   ! raeburn   609: sub checkwords {
        !           610:     my ($result,$applies,@allwords) = @_;
        !           611:     foreach (@allwords) {
        !           612:         if ($_=~/\w/) {
        !           613:             if ($result=~/$_/si) {
        !           614:                 $applies++;
        !           615:             }
        !           616:         }
        !           617:     }
        !           618:     return $applies;
        !           619: }
        !           620: 
1.196     matthew   621: sub untiehash {
                    622:     if (tied(%hash)) {
                    623:         untie(%hash);
                    624:     }
                    625: }
                    626: 
                    627: } # End of course search scoping
                    628: 
1.207     matthew   629: sub search_html_header {
                    630:     my $Str = <<ENDHEADER;
                    631: <html>
                    632: <head>
                    633: <title>The LearningOnline Network with CAPA</title>
                    634: </head>
                    635: ENDHEADER
                    636:     return $Str;
                    637: }
                    638: 
1.167     www       639: ######################################################################
                    640: ######################################################################
                    641: 
1.124     matthew   642: =pod 
                    643: 
1.146     matthew   644: =item &print_basic_search_form() 
1.124     matthew   645: 
1.204     matthew   646: Prints the form for the basic search.  Sorry the name is so cryptic.
1.124     matthew   647: 
                    648: =cut
                    649: 
                    650: ######################################################################
                    651: ######################################################################
1.204     matthew   652: sub print_basic_search_form {
1.196     matthew   653:     my ($r,$closebutton,$hidden_fields) = @_;
1.227     matthew   654:     my $result = ($ENV{'form.catalogmode'} ne 'groupsearch');
1.203     www       655:     my $bodytag=&Apache::loncommon::bodytag('Search').
1.229     matthew   656:         &Apache::lonhtmlcommon::breadcrumbs(undef,'Searching','Search_Basic',
1.227     matthew   657:                                    undef,undef,
                    658:                                    $ENV{'form.catalogmode'} ne 'groupsearch');
1.207     matthew   659:     my $scrout = &search_html_header().$bodytag;
                    660:     if (&Apache::lonnet::allowed('bre',$ENV{'request.role.domain'})) {
1.213     matthew   661:         # Define interface components
                    662:         my $userelatedwords=
                    663:             &mt('[_1] use related words',
                    664:                 &Apache::lonhtmlcommon::checkbox
1.221     matthew   665:                 ('related',$ENV{'form.related'},'related'));
1.213     matthew   666:         my $onlysearchdomain=
                    667:             &mt('[_1] only search domain [_2]',
1.221     matthew   668:                 &Apache::lonhtmlcommon::checkbox('domains',
                    669:                                                  $ENV{'form.domains'},
                    670:                                                  $r->dir_config('lonDefDomain')
                    671:                                                  ),
                    672:                 $r->dir_config('lonDefDomain')
                    673:                 );
1.213     matthew   674:         my $adv_search_link = 
                    675:             '<a href="/adm/searchcat?'.
                    676:             'phase=disp_adv&'.
                    677:             'catalogmode='.$ENV{'form.catalogmode'}.
                    678:             '&launch='.$ENV{'form.launch'}.
                    679:             '&mode='.$ENV{'form.mode'}.
                    680:             '">'.&mt('Advanced Search').'</a>';
                    681:         #
                    682:         $scrout.='<form name="loncapa_search" method="post" '.
                    683:             'action="/adm/searchcat">'.
                    684:             '<input type="hidden" name="phase" value="basic_search" />'.
                    685:             $hidden_fields;
                    686:         #
                    687:         $scrout .= '<center>'.$/;
                    688:         if ($ENV{'request.course.id'}) {
                    689:             $scrout .= '<h1>'.&mt('LON-CAPA Catalog Search').'</h1>';
                    690:         } else {
                    691:             # No need to tell them they are searching
                    692:             $scrout.= ('<br />'x2);
                    693:         }
                    694:         $scrout.='<table>'.
                    695:             '<tr><td align="center" valign="top">'.
1.228     matthew   696:             &Apache::lonhtmlcommon::textbox
                    697:             ('basicexp',
                    698:              &HTML::Entities::encode($ENV{'form.basicexp'},'<>&"'),50
                    699:              ).
                    700:              '<br />'.
1.213     matthew   701:             '<font size="-1">'.&searchhelp().'</font>'.'</td>'.
                    702:             '<td><font size="-1">'.
                    703:             '<nobr>'.('&nbsp;'x3).$adv_search_link.'</nobr>'.'<br />'.
                    704:             '<nobr>'.('&nbsp;'x1).$userelatedwords.'</nobr>'.'<br />'.
                    705:             '<nobr>'.('&nbsp;'x1).$onlysearchdomain.'</nobr>'.'<br />'.
                    706:             '</font></td>'.
                    707:             '</tr>'.$/;
                    708:         #
                    709:         $scrout .= '<tr><td align="center" colspan="2">'.
                    710:             '<font size="-1">'.
                    711:             '<input type="submit" name="basicsubmit" '.
                    712:             'value="'.&mt('Search').'" />'.
1.223     matthew   713:             ('&nbsp;'x2).$closebutton.('&nbsp;'x2).
                    714:             &viewoptions().
1.213     matthew   715:             '</font>'.
                    716:             '</td></tr>'.$/;
                    717:         $scrout .= '</table>'.$/.'</center>'.'</form>';
1.180     matthew   718:     }
                    719:     if ($ENV{'request.course.id'}) {
1.213     matthew   720: 	my %lt=&Apache::lonlocal::texthash('srch' => 'Search',
1.187     www       721:                                            'header' => 'Course Search',
                    722: 	 'note' => 'Enter terms or phrases, then press "Search" below',
1.200     www       723: 	 'use' => 'use related words',
1.231   ! raeburn   724: 	 'full' =>'fulltext search (time consuming)',
        !           725:          'disc' => 'search discussion postings (resources and bulletin boards)',
1.187     www       726: 					   );
1.180     matthew   727:         $scrout.=(<<ENDCOURSESEARCH);
1.213     matthew   728: <form name="loncapa_search" method="post" action="/adm/searchcat">
                    729: <center>
1.180     matthew   730: <hr />
1.187     www       731: <h1>$lt{'header'}</h1>    
1.167     www       732: <input type="hidden" name="phase" value="course_search" />
                    733: $hidden_fields
                    734: <p>
1.187     www       735: $lt{'note'}.
1.167     www       736: </p>
                    737: <p>
                    738: <table>
                    739: <tr><td>
                    740: ENDCOURSESEARCH
1.180     matthew   741:         $scrout.='&nbsp;'.
1.200     www       742:             &Apache::lonhtmlcommon::textbox('courseexp',
                    743:                                   $ENV{'form.courseexp'},40);
1.180     matthew   744:         my $crscheckbox = 
1.200     www       745:             &Apache::lonhtmlcommon::checkbox('crsfulltext',
                    746:                                    $ENV{'form.crsfulltext'});
1.180     matthew   747:         my $relcheckbox = 
1.200     www       748:             &Apache::lonhtmlcommon::checkbox('crsrelated',
                    749: 				   $ENV{'form.crsrelated'});
1.231   ! raeburn   750:         my $discheckbox = 
        !           751:             &Apache::lonhtmlcommon::checkbox('crsdiscuss',
        !           752:                                    $ENV{'form.crsrelated'});
1.180     matthew   753:         $scrout.=(<<ENDENDCOURSE);
1.167     www       754: </td></tr>
1.200     www       755: <tr><td>$relcheckbox $lt{'use'}</td><td></td></tr>
                    756: <tr><td>$crscheckbox $lt{'full'}</td><td></td></tr>
1.231   ! raeburn   757: <tr><td>$discheckbox $lt{'disc'}</td><td></td></tr>
1.167     www       758: </table><p>
1.187     www       759: &nbsp;<input type="submit" name="coursesubmit" value='$lt{'srch'}' />
1.167     www       760: </p>
1.213     matthew   761: </center>
                    762: </form>
1.167     www       763: ENDENDCOURSE
1.180     matthew   764:     }
1.167     www       765:     $scrout.=(<<ENDDOCUMENT);
1.124     matthew   766: </body>
                    767: </html>
                    768: ENDDOCUMENT
1.146     matthew   769:     $r->print($scrout);
                    770:     return;
1.124     matthew   771: }
                    772: ######################################################################
                    773: ######################################################################
                    774: 
                    775: =pod 
                    776: 
                    777: =item &advanced_search_form() 
                    778: 
1.204     matthew   779: Prints the advanced search form.
1.124     matthew   780: 
                    781: =cut
                    782: 
                    783: ######################################################################
                    784: ######################################################################
1.146     matthew   785: sub print_advanced_search_form{
1.196     matthew   786:     my ($r,$closebutton,$hidden_fields) = @_;
1.217     matthew   787:     my $bodytag=&Apache::loncommon::bodytag('Advanced Catalog Search').
1.229     matthew   788:         &Apache::lonhtmlcommon::breadcrumbs(undef,'Searching',
                    789:                                             'Search_Advanced',
                    790:                                             undef,undef,
1.227     matthew   791:                                   $ENV{'form.catalogmode'} ne 'groupsearch');
1.200     www       792:     my %lt=&Apache::lonlocal::texthash('srch' => 'Search',
                    793: 				       'reset' => 'Reset',
                    794: 				       'help' => 'Help');
1.217     matthew   795:     my $advanced_buttons=<<"END";
1.200     www       796: <input type="submit" name="advancedsubmit" value='$lt{"srch"}' />
                    797: <input type="reset" name="reset" value='$lt{"reset"}' />
1.129     matthew   798: $closebutton
                    799: END
1.207     matthew   800:     my $scrout=&search_html_header();
                    801:     $scrout .= <<"ENDHEADER";
1.154     www       802: $bodytag
1.200     www       803: <form method="post" action="/adm/searchcat" name="advsearch">
1.217     matthew   804: <p>
1.129     matthew   805: $advanced_buttons
1.124     matthew   806: ENDHEADER
1.208     matthew   807:     $scrout.=('&nbsp;'x2).&viewoptions().'</p>'.$hidden_fields. 
                    808:         '<input type="hidden" name="phase" value="adv_search" />';
1.200     www       809:     my %fields=&Apache::lonmeta::fieldnames();
1.208     matthew   810:     #
1.217     matthew   811:     $scrout .= '<h3>'.&mt('Standard Metadata').'</h3>';
                    812:     $scrout .= "<table>\n";
                    813:     $scrout .= '<tr><td>&nbsp;</td><td colspan="2"><font size="-1">'.
                    814:         ('&nbsp;'x2).&searchhelp()."</font></td></tr>\n";
1.208     matthew   815:     my %related_word_search = 
1.217     matthew   816:         ('title'    => 1,
                    817:          'author'   => 0,
                    818:          'owner'    => 0,
                    819:          'authorspace'  => 0,
                    820:          'modifyinguser'=> 0,
                    821:          'keywords' => 1,
                    822:          'notes'    => 1,
                    823:          'abstract' => 1,
                    824:          'standards'=> 1,
                    825:          'mime'     => 1,
1.208     matthew   826:          );
1.209     matthew   827:     #
1.208     matthew   828:     foreach my $field ('title','author','owner','authorspace','modifyinguser',
                    829: 	     'keywords','notes','abstract','standards','mime') {
                    830: 	$scrout.='<tr><td align="right">'.&titlefield($fields{$field}).'</td><td>'.
                    831: 	    &Apache::lonmeta::prettyinput($field,
                    832:                                           $ENV{'form.'.$field},
                    833:                                           $field,
                    834:                                           'advsearch',
                    835: 					  $related_word_search{$field},
                    836:                                           '</td><td align="left">',
                    837:                                           $ENV{'form.'.$field.'_related'},
                    838:                                           50);
                    839:         if ($related_word_search{$field}) {
                    840:             $scrout .= 'related words';
                    841:         } else {
                    842:             $scrout .= '</td><td>&nbsp;';
                    843:         }
                    844:         $scrout .= '</td></tr>'.$/;
                    845:     }
                    846:     foreach my $field ('lowestgradelevel','highestgradelevel') {
                    847: 	$scrout.='<tr>'.
                    848:             '<td align="right">'.&titlefield($fields{$field}).'</td>'.
                    849:             '<td colspan="2">'.
                    850: 	    &Apache::lonmeta::prettyinput($field,
                    851:                                           $ENV{'form.'.$field},
                    852:                                           $field,
                    853:                                           'advsearch',
                    854: 					  0).
                    855:                                           '</td></tr>'.$/;
1.200     www       856:     }
1.208     matthew   857:     $scrout.='<tr><td align="right">'.
                    858: 	&titlefield(&mt('MIME Type Category')).'</td><td colspan="2">'. 
1.202     www       859: 	    &Apache::loncommon::filecategoryselect('category',
                    860: 						   $ENV{'form.category'}).
1.208     matthew   861: 	    '</td></tr>'.$/;
                    862:     $scrout.='<tr><td align="right" valign="top">'.
                    863: 	&titlefield(&mt('Domains')).'</td><td colspan="2">'. 
1.202     www       864: 	    &Apache::loncommon::domain_select('domains',
                    865: 						   $ENV{'form.domains'},1).
1.208     matthew   866: 	    '</td></tr>'.$/;
1.217     matthew   867:     #
                    868:     # Misc metadata
                    869:     $scrout.='<tr><td align="right" valign="top">'.
                    870: 	&titlefield(&mt('Copyright/Distribution')).'</td><td colspan="2">'.
                    871:         &Apache::lonmeta::selectbox('copyright',
1.230     matthew   872:                                     $ENV{'form.copyright'},
1.217     matthew   873:                                     \&Apache::loncommon::copyrightdescription,
                    874:                                     ( undef,
                    875:                                       &Apache::loncommon::copyrightids)
                    876:                                     ).'</td></tr>'.$/;
                    877:     $scrout.='<tr><td align="right" valign="top">'.
                    878: 	&titlefield(&mt('Language')).'</td><td colspan="2">'.
                    879:         &Apache::lonmeta::selectbox('language',
1.230     matthew   880:                                     $ENV{'form.language'},
1.217     matthew   881:                                     \&Apache::loncommon::languagedescription,
                    882:                                     ('any',&Apache::loncommon::languageids)
                    883:                                     ).'</td></tr>';
                    884:     $scrout .= "</table>\n";    
                    885:     #
                    886:     # Dynamic metadata
                    887:     $scrout .= '<h3>'.&mt('Problem Statistics').'</h3>';
                    888:     $scrout .= "<table>\n";
                    889:     $scrout .= '<tr><td>&nbsp;</td><td align="center">'.&mt('Minimum').'</td>'.
                    890:         '<td align="center">'.&mt('Maximum').'</td></tr>'."\n";
                    891:     foreach my $statistic 
1.222     matthew   892:         ({ name=>'count',
                    893:            description=>'Network-wide number of accesses (hits)',},
                    894:          { name=>'stdno',
                    895:            description=>
                    896:                'Total number of students who have worked on this problem',},
1.217     matthew   897:          { name => 'avetries',
1.222     matthew   898:            description=>'Average number of tries till solved',},
1.217     matthew   899:          { name => 'difficulty',
                    900:            description=>'Degree of difficulty',},
                    901:          { name => 'disc',
                    902:            description=>'Degree of discrimination'}) {
                    903:         $scrout .= '<tr><td align="right">'.
                    904:             &titlefield(&mt($statistic->{'description'})).
                    905:             '</td><td align="center">'.
                    906:             '<input type="text" name="'.$statistic->{'name'}.'_min" '.
                    907:             'value="" size="6" />'.
                    908:             '</td><td align="center">'.
                    909:             '<input type="text" name="'.$statistic->{'name'}.'_max" '.
                    910:             'value="" size="6" />'.
                    911:             '</td></tr>'.$/;
                    912:     }
                    913:     $scrout .= "</table>\n";
                    914:     $scrout .= '<h3>'.&mt('Evaluation Data').'</h3>';
                    915:     $scrout .= "<table>\n";
                    916:     $scrout .= '<tr><td>&nbsp;</td><td align="center">'.&mt('Minimum').'</td>'.
                    917:         '<td align="center">'.&mt('Maximum').'</td></tr>'."\n";
                    918:     foreach my $evaluation
                    919:         ( { name => 'clear',
                    920:             description => 'Material presented in clear way'},
                    921:           { name =>'depth',
                    922:             description => 'Material covered with sufficient depth'},
                    923:           { name => 'helpful',
                    924:             description => 'Material is helpful'},
                    925:           { name => 'correct',
                    926:             description => 'Material appears to be correct'},
                    927:           { name => 'technical',
                    928:             description => 'Resource is technically correct'}){
                    929:         $scrout .= '<tr><td align="right">'.
                    930:             &titlefield(&mt($evaluation->{'description'})).
                    931:             '</td><td align="center">'.
                    932:             '<input type="text" name="'.$evaluation->{'name'}.'_min" '.
                    933:             'value="" size="6" />'.
                    934:             '</td><td align="center">'.
                    935:             '<input type="text" name="'.$evaluation->{'name'}.'_max" '.
                    936:             'value="" size="6" />'.
                    937:             '</td></tr>'.$/;
                    938:     }
                    939:     $scrout .= "</table>\n";
1.216     matthew   940:     #
                    941:     # Creation/Modification date limits
1.217     matthew   942:     $scrout .= '<h3>'.&mt('Creation and Modification dates').'</h3>';
1.216     matthew   943:     $scrout .= "\n<table>\n";
                    944:     my $cafter = 
                    945:         &Apache::lonhtmlcommon::date_setter('advsearch',         # formname
                    946:                                             'creationdate1', # fieldname
                    947:                                             0,           # current value
                    948:                                             '',          # special 
                    949:                                             1,           # includeempty
                    950:                                             '',          # state
                    951:                                             1,           # no_hh_mm_ss
                    952:                                             );
                    953:     my $cbefore = 
                    954:         &Apache::lonhtmlcommon::date_setter('advsearch',         # formname
                    955:                                             'creationdate2', # fieldname
                    956:                                             0,           # current value
                    957:                                             '',          # special 
                    958:                                             1,           # includeempty
                    959:                                             '',          # state
                    960:                                             1,           # no_hh_mm_ss
                    961:                                             );
                    962:     $scrout .= &mt('<tr><td align="right">Created between</td>'.
                    963:                    '<td>[_1]</td></tr>'.
                    964:                    '<tr><td align="right">and </td>'.
                    965:                    '<td>[_2]</td></tr>',$cafter,$cbefore);
                    966:     my $lafter = 
                    967:         &Apache::lonhtmlcommon::date_setter('advsearch',
                    968:                                             'revisiondate1', 
                    969:                                             0,           # current value
                    970:                                             '',          # special 
                    971:                                             1,           # includeempty
                    972:                                             '',          # state
                    973:                                             1,           # no_hh_mm_ss
                    974:                                             );
                    975:     my $lbefore = 
                    976:         &Apache::lonhtmlcommon::date_setter('advsearch',
                    977:                                             'revisiondate2',
                    978:                                             0,           # current value
                    979:                                             '',          # special 
                    980:                                             1,           # includeempty
                    981:                                             '',          # state
                    982:                                             1,           # no_hh_mm_ss
                    983:                                             );
                    984:     $scrout .= &mt('<tr><td align="right">Last modified between </td>'.
                    985:                    '<td>[_1]</td></tr>'.
                    986:                    '<tr><td align="right">and</td>'.
                    987:                    '<td>[_2]</td></tr>',$lafter,$lbefore);
1.202     www       988:     $scrout.="</table>\n";
1.124     matthew   989:     $scrout.=<<ENDDOCUMENT;
1.129     matthew   990: $advanced_buttons
1.8       harris41  991: </form>
                    992: </body>
                    993: </html>
                    994: ENDDOCUMENT
1.146     matthew   995:     $r->print($scrout);
                    996:     return;
1.124     matthew   997: }
1.204     matthew   998: 
1.200     www       999: ######################################################################
                   1000: ######################################################################
                   1001: 
                   1002: =pod 
                   1003: 
1.204     matthew  1004: =item &titlefield()
1.200     www      1005: 
                   1006: Inputs: title text
                   1007: 
                   1008: Outputs: titletext with font wrapper
                   1009: 
                   1010: =cut
                   1011: 
                   1012: ######################################################################
                   1013: ######################################################################
                   1014: sub titlefield {
                   1015:     my $title=shift;
1.208     matthew  1016:     return $title;
1.200     www      1017: }
1.204     matthew  1018: 
1.200     www      1019: ######################################################################
                   1020: ######################################################################
                   1021: 
                   1022: =pod 
                   1023: 
1.204     matthew  1024: =item viewoptiontext()
1.200     www      1025: 
                   1026: Inputs: codename for view option
                   1027: 
                   1028: Outputs: displayed text
                   1029: 
                   1030: =cut
                   1031: 
                   1032: ######################################################################
                   1033: ######################################################################
                   1034: sub viewoptiontext {
                   1035:     my $code=shift;
1.204     matthew  1036:     my %desc=&Apache::lonlocal::texthash
                   1037:         ('detailed' => "Detailed Citation View",
                   1038:          'xml' => 'XML/SGML',
                   1039:          'compact' => 'Compact View',
                   1040:          'fielded' => 'Fielded Format',
                   1041:          'summary' => 'Summary View');
1.200     www      1042:     return $desc{$code};
                   1043: }
1.204     matthew  1044: 
                   1045: ######################################################################
1.200     www      1046: ######################################################################
                   1047: 
                   1048: =pod 
                   1049: 
1.204     matthew  1050: =item viewoptions()
1.200     www      1051: 
                   1052: Inputs: none
                   1053: 
                   1054: Outputs: text for box with view options
                   1055: 
                   1056: =cut
                   1057: 
                   1058: ######################################################################
                   1059: ######################################################################
                   1060: sub viewoptions {
1.223     matthew  1061:     my $scrout;
1.208     matthew  1062:     if (! defined($ENV{'form.viewselect'})) { 
                   1063:         $ENV{'form.viewselect'}='detailed'; 
                   1064:     }
1.200     www      1065:     $scrout.=&Apache::lonmeta::selectbox('viewselect',
                   1066: 			$ENV{'form.viewselect'},
                   1067: 			\&viewoptiontext,
                   1068: 			sort(keys(%Views)));
1.208     matthew  1069:     $scrout.= '&nbsp;&nbsp;';
1.214     matthew  1070:     my $countselect = &Apache::lonmeta::selectbox('show',
                   1071:                                                   $ENV{'form.show'},
                   1072:                                                   undef,
                   1073:                                                   (10,20,50,100,1000,10000));
                   1074:     $scrout .= ('&nbsp;'x2).&mt('[_1] Records per Page',$countselect).
                   1075:         '</nobr>'.$/;
1.200     www      1076:     return $scrout;
1.201     www      1077: }
                   1078: 
                   1079: ######################################################################
1.204     matthew  1080: ######################################################################
1.201     www      1081: 
                   1082: =pod 
                   1083: 
1.204     matthew  1084: =item searchhelp()
1.201     www      1085: 
                   1086: Inputs: none
                   1087: 
                   1088: Outputs: return little blurb on how to enter searches
                   1089: 
                   1090: =cut
                   1091: 
                   1092: ######################################################################
                   1093: ######################################################################
                   1094: sub searchhelp {
1.228     matthew  1095:     return &mt('Enter words and quoted phrases');
1.200     www      1096: }
1.8       harris41 1097: 
1.121     matthew  1098: ######################################################################
                   1099: ######################################################################
                   1100: 
                   1101: =pod 
                   1102: 
1.204     matthew  1103: =item &get_persistent_form_data()
1.145     matthew  1104: 
1.146     matthew  1105: Inputs: filename of database
                   1106: 
                   1107: Outputs: returns undef on database errors.
                   1108: 
                   1109: This function is the reverse of &make_persistent() for form data.
1.145     matthew  1110: Retrieve persistent data from %persistent_db.  Retrieved items will have their
1.146     matthew  1111: values unescaped.  If a form value already exists in $ENV, it will not be
                   1112: overwritten.  Form values that are array references may have values appended
                   1113: to them.
1.145     matthew  1114: 
                   1115: =cut
                   1116: 
                   1117: ######################################################################
                   1118: ######################################################################
1.146     matthew  1119: sub get_persistent_form_data {
                   1120:     my $filename = shift;
1.147     matthew  1121:     return 0 if (! -e $filename);
1.146     matthew  1122:     return undef if (! tie(%persistent_db,'GDBM_File',$filename,
1.148     matthew  1123:                            &GDBM_READER(),0640));
1.146     matthew  1124:     #
                   1125:     # These make sure we do not get array references printed out as 'values'.
1.161     matthew  1126:     my %arrays_allowed = ('form.domains'=>1);
1.146     matthew  1127:     #
                   1128:     # Loop through the keys, looking for 'form.'
                   1129:     foreach my $name (keys(%persistent_db)) {
                   1130:         next if ($name !~ /^form./);
1.182     matthew  1131:         # Kludgification begins!
                   1132:         if ($name eq 'form.domains' && 
                   1133:             $ENV{'form.searchmode'} eq 'basic' &&
                   1134:             $ENV{'form.phase'} ne 'disp_basic') {
                   1135:             next;
                   1136:         }
                   1137:         # End kludge (hopefully)
1.152     matthew  1138:         next if (exists($ENV{$name}));
1.146     matthew  1139:         my @values = map { 
                   1140:             &Apache::lonnet::unescape($_);
                   1141:         } split(',',$persistent_db{$name});
                   1142:         next if (@values <1);
1.152     matthew  1143:         if ($arrays_allowed{$name}) {
                   1144:             $ENV{$name} = [@values];
1.146     matthew  1145:         } else {
1.152     matthew  1146:             $ENV{$name} = $values[0] if ($values[0]);
1.146     matthew  1147:         }
                   1148:     }
                   1149:     untie (%persistent_db);
                   1150:     return 1;
                   1151: }
1.181     matthew  1152: 
1.146     matthew  1153: ######################################################################
                   1154: ######################################################################
                   1155: 
                   1156: =pod 
                   1157: 
1.204     matthew  1158: =item &get_persistent_data()
1.146     matthew  1159: 
                   1160: Inputs: filename of database, ref to array of values to recover.
                   1161: 
                   1162: Outputs: array of values.  Returns undef on error.
                   1163: 
                   1164: This function is the reverse of &make_persistent();
                   1165: Retrieve persistent data from %persistent_db.  Retrieved items will have their
                   1166: values unescaped.  If the item contains commas (before unescaping), the
                   1167: returned value will be an array pointer. 
                   1168: 
                   1169: =cut
                   1170: 
                   1171: ######################################################################
                   1172: ######################################################################
                   1173: sub get_persistent_data {
                   1174:     my $filename = shift;
                   1175:     my @Vars = @{shift()};
                   1176:     my @Values;   # Return array
                   1177:     return undef if (! -e $filename);
                   1178:     return undef if (! tie(%persistent_db,'GDBM_File',$filename,
1.148     matthew  1179:                            &GDBM_READER(),0640));
1.146     matthew  1180:     foreach my $name (@Vars) {
                   1181:         if (! exists($persistent_db{$name})) {
                   1182:             push @Values, undef;
                   1183:             next;
                   1184:         }
                   1185:         my @values = map { 
                   1186:             &Apache::lonnet::unescape($_);
                   1187:         } split(',',$persistent_db{$name});
1.152     matthew  1188:         if (@values <= 1) {
1.146     matthew  1189:             push @Values,$values[0];
1.145     matthew  1190:         } else {
1.146     matthew  1191:             push @Values,\@values;
1.145     matthew  1192:         }
                   1193:     }
1.146     matthew  1194:     untie (%persistent_db);
                   1195:     return @Values;
1.145     matthew  1196: }
                   1197: 
                   1198: ######################################################################
                   1199: ######################################################################
                   1200: 
                   1201: =pod 
                   1202: 
1.121     matthew  1203: =item &make_persistent() 
                   1204: 
1.146     matthew  1205: Inputs: Hash of values to save, filename of persistent database.
                   1206: 
                   1207: Store variables away to the %persistent_db.
1.145     matthew  1208: Values will be escaped.  Values that are array pointers will have their
1.205     www      1209: elements escaped and concatenated in a comma separated string.  
1.122     matthew  1210: 
1.121     matthew  1211: =cut
                   1212: 
                   1213: ######################################################################
                   1214: ######################################################################
1.98      harris41 1215: sub make_persistent {
1.133     matthew  1216:     my %save = %{shift()};
1.146     matthew  1217:     my $filename = shift;
                   1218:     return undef if (! tie(%persistent_db,'GDBM_File',
1.148     matthew  1219:                            $filename,&GDBM_WRCREAT(),0640));
1.146     matthew  1220:     foreach my $name (keys(%save)) {
1.145     matthew  1221:         my @values = (ref($save{$name}) ? @{$save{$name}} : ($save{$name}));
                   1222:         # We handle array references, but not recursively.
                   1223:         my $store = join(',', map { &Apache::lonnet::escape($_); } @values );
                   1224:         $persistent_db{$name} = $store;
1.109     harris41 1225:     }
1.146     matthew  1226:     untie(%persistent_db);
                   1227:     return 1;
                   1228: }
                   1229: 
                   1230: ######################################################################
                   1231: ######################################################################
                   1232: 
                   1233: =pod 
                   1234: 
                   1235: =item &make_form_data_persistent() 
                   1236: 
                   1237: Inputs: filename of persistent database.
                   1238: 
                   1239: Store most form variables away to the %persistent_db.
                   1240: Values will be escaped.  Values that are array pointers will have their
1.205     www      1241: elements escaped and concatenated in a comma separated string.  
1.146     matthew  1242: 
                   1243: =cut
                   1244: 
                   1245: ######################################################################
                   1246: ######################################################################
                   1247: sub make_form_data_persistent {
                   1248:     my $r = shift;
                   1249:     my $filename = shift;
                   1250:     my %save;
                   1251:     foreach (keys(%ENV)) {
1.150     matthew  1252:         next if (!/^form/ || /submit/);
1.146     matthew  1253:         $save{$_} = $ENV{$_};
                   1254:     }
1.152     matthew  1255:     return &make_persistent(\%save,$filename);
1.98      harris41 1256: }
                   1257: 
1.122     matthew  1258: ######################################################################
                   1259: ######################################################################
                   1260: 
                   1261: =pod 
                   1262: 
1.134     matthew  1263: =item &parse_advanced_search()
                   1264: 
                   1265: Parse advanced search form and return the following:
                   1266: 
                   1267: =over 4
                   1268: 
                   1269: =item $query Scalar containing an SQL query.
1.126     matthew  1270: 
1.134     matthew  1271: =item $customquery Scalar containing a custom query.
                   1272: 
                   1273: =item $customshow Scalar containing commands to show custom metadata.
                   1274: 
                   1275: =item $libraries_to_query Reference to array of domains to search.
                   1276: 
                   1277: =back
1.122     matthew  1278: 
                   1279: =cut
                   1280: 
                   1281: ######################################################################
                   1282: ######################################################################
1.134     matthew  1283: sub parse_advanced_search {
1.196     matthew  1284:     my ($r,$closebutton,$hidden_fields)=@_;
1.216     matthew  1285:     my @BasicFields = ('title','author','subject','keywords','url','version',
1.227     matthew  1286:                        'notes','abstract','extension','owner','authorspace',
1.216     matthew  1287: #                       'custommetadata','customshow',
                   1288:                        'modifyinguser','standards','mime');
1.222     matthew  1289:     my @StatsFields = &statfields();
                   1290:     my @EvalFields = &evalfields();
1.32      harris41 1291:     my $fillflag=0;
1.230     matthew  1292:     my $pretty_search_string = "";
1.64      harris41 1293:     # Clean up fields for safety
1.216     matthew  1294:     for my $field (@BasicFields,
                   1295:                    'creationdatestart_month','creationdatestart_day',
1.64      harris41 1296: 		   'creationdatestart_year','creationdateend_month',
                   1297: 		   'creationdateend_day','creationdateend_year',
                   1298: 		   'lastrevisiondatestart_month','lastrevisiondatestart_day',
                   1299: 		   'lastrevisiondatestart_year','lastrevisiondateend_month',
1.216     matthew  1300: 		   'lastrevisiondateend_day','lastrevisiondateend_year') {
                   1301: 	$ENV{'form.'.$field}=~s/[^\w\/\s\(\)\=\-\"\']//g;
1.64      harris41 1302:     }
1.117     matthew  1303:     foreach ('mode','form','element') {
                   1304: 	# is this required?  Hmmm.
1.216     matthew  1305: 	next if (! exists($ENV{'form.'.$_}));
                   1306: 	$ENV{'form.'.$_}=&Apache::lonnet::unescape($ENV{'form.'.$_});
                   1307: 	$ENV{'form.'.$_}=~s/[^\w\/\s\(\)\=\-\"\']//g;
1.117     matthew  1308:     }
1.131     matthew  1309:     # Preprocess the category form element.
1.161     matthew  1310:     $ENV{'form.category'} = 'any' if (! defined($ENV{'form.category'}) ||
                   1311:                                       ref($ENV{'form.category'}));
                   1312:     #
1.90      harris41 1313:     # Check to see if enough information was filled in
1.222     matthew  1314:     foreach my $field (@BasicFields) {
1.216     matthew  1315: 	if (&filled($ENV{'form.'.$field})) {
1.32      harris41 1316: 	    $fillflag++;
                   1317: 	}
                   1318:     }
1.222     matthew  1319:     foreach my $field (@StatsFields,@EvalFields) {
                   1320:         if (&filled($ENV{'form.'.$field.'_max'})) {
                   1321:             $fillflag++;
                   1322:         }
                   1323:         if (&filled($ENV{'form.'.$field.'_min'})) {
                   1324:             $fillflag++;
                   1325:         }
                   1326:     }
                   1327: 
1.216     matthew  1328:     for my $field ('lowestgradelevel','highestgradelevel') {
                   1329:         if ( $ENV{'form.'.$field} =~ /^\d+$/ &&
                   1330:              $ENV{'form.'.$field} > 0) {
                   1331:             $fillflag++;
                   1332:         }
                   1333:     }
1.212     matthew  1334:     if (! $fillflag) {
1.204     matthew  1335: 	&output_blank_field_error($r,$closebutton,
                   1336:                                   'phase=disp_adv',$hidden_fields);
1.134     matthew  1337: 	return ;
1.32      harris41 1338:     }
1.90      harris41 1339:     # Turn the form input into a SQL-based query
1.39      harris41 1340:     my $query='';
1.45      harris41 1341:     my @queries;
1.143     matthew  1342:     my $font = '<font color="#800000" face="helvetica">';
1.90      harris41 1343:     # Evaluate logical expression AND/OR/NOT phrase fields.
1.216     matthew  1344:     foreach my $field (@BasicFields) {
1.224     matthew  1345: 	next if (!defined($ENV{'form.'.$field}) || $ENV{'form.'.$field} eq '');
1.228     matthew  1346:         my ($error,$SQLQuery) = 
                   1347:             &process_phrase_input($ENV{'form.'.$field},
                   1348:                                   $ENV{'form.'.$field.'_related'},$field);
                   1349:         if (defined($error)) {
                   1350:             &output_unparsed_phrase_error($r,$closebutton,'phase=disp_adv',
                   1351:                                          $hidden_fields,$field);
                   1352:             return;
                   1353:         } else {
                   1354:             $pretty_search_string .= 
                   1355:                 $font.$field.'</font>: '.$ENV{'form.'.$field};
1.142     matthew  1356:             if ($ENV{'form.'.$field.'_related'}) {
1.228     matthew  1357:                 my @Words = 
                   1358:                     &Apache::loncommon::get_related_words
                   1359:                     ($ENV{'form.'.$field});
                   1360:                 if (@Words) {
                   1361:                     $pretty_search_string.= ' with related words: '.
                   1362:                         join(', ',@Words[0..4]);
1.143     matthew  1363:                 } else {
1.228     matthew  1364:                     $pretty_search_string.= ' with related words.';
1.143     matthew  1365:                 }
1.142     matthew  1366:             }
1.228     matthew  1367:             $pretty_search_string .= '<br />';
                   1368:             push (@queries,$SQLQuery);
1.131     matthew  1369:         }
1.44      harris41 1370:     }
1.161     matthew  1371:     #
                   1372:     # Make the 'mime' from 'form.category' and 'form.extension'
                   1373:     #
                   1374:     my $searchphrase;
                   1375:     if (exists($ENV{'form.category'})    && 
                   1376:         $ENV{'form.category'} !~ /^\s*$/ &&
                   1377:         $ENV{'form.category'} ne 'any')     {
                   1378:         my @extensions = &Apache::loncommon::filecategorytypes
                   1379:                                                    ($ENV{'form.category'});
                   1380:         if (scalar(@extensions) > 0) {
                   1381:             $searchphrase = join(' OR ',@extensions);
                   1382:         }
                   1383:     }
                   1384:     if (defined($searchphrase)) {
1.228     matthew  1385:         my ($error,$SQLsearch) = &process_phrase_input($searchphrase,0,'mime');
                   1386:         push @queries,$SQLsearch;
1.161     matthew  1387:         $pretty_search_string .=$font.'mime</font> contains <b>'.
                   1388:             $searchphrase.'</b><br />';
1.135     matthew  1389:     }
1.204     matthew  1390:     #
1.90      harris41 1391:     # Evaluate option lists
1.216     matthew  1392:     if ($ENV{'form.lowestgradelevel'}        &&
                   1393:         $ENV{'form.lowestgradelevel'} ne '0' &&
                   1394:         $ENV{'form.lowestgradelevel'} =~ /^\d+$/) {
                   1395: 	push(@queries,
                   1396:              '(lowestgradelevel>='.$ENV{'form.lowestgradelevel'}.')');
                   1397:         $pretty_search_string.="lowestgradelevel>=".
                   1398:             $ENV{'form.lowestgradelevel'}."<br />\n";
                   1399:     }
                   1400:     if ($ENV{'form.highestgradelevel'}        &&
                   1401:         $ENV{'form.highestgradelevel'} ne '0' &&
                   1402:         $ENV{'form.highestgradelevel'} =~ /^\d+$/) {
                   1403: 	push(@queries,
                   1404:              '(highestgradelevel<='.$ENV{'form.highestgradelevel'}.')');
                   1405:         $pretty_search_string.="highestgradelevel<=".
                   1406:             $ENV{'form.highestgradelevel'}."<br />\n";
                   1407:     }
1.58      harris41 1408:     if ($ENV{'form.language'} and $ENV{'form.language'} ne 'any') {
1.90      harris41 1409: 	push @queries,"(language like \"$ENV{'form.language'}\")";
1.143     matthew  1410:         $pretty_search_string.=$font."language</font>= ".
                   1411:             &Apache::loncommon::languagedescription($ENV{'form.language'}).
                   1412:                 "<br />\n";
1.58      harris41 1413:     }
                   1414:     if ($ENV{'form.copyright'} and $ENV{'form.copyright'} ne 'any') {
1.90      harris41 1415: 	push @queries,"(copyright like \"$ENV{'form.copyright'}\")";
1.143     matthew  1416:         $pretty_search_string.=$font."copyright</font> = ".
                   1417:             &Apache::loncommon::copyrightdescription($ENV{'form.copyright'}).
1.230     matthew  1418:                 "<br />\n";
1.58      harris41 1419:     }
1.143     matthew  1420:     #
1.217     matthew  1421:     # Statistics
                   1422:     foreach my $field (@StatsFields,@EvalFields) {
                   1423:         my ($min,$max);
                   1424:         if (exists($ENV{'form.'.$field.'_min'}) && 
                   1425:             $ENV{'form.'.$field.'_min'} ne '') {
                   1426:             $min = $ENV{'form.'.$field.'_min'};
                   1427:         }
                   1428:         if (exists($ENV{'form.'.$field.'_max'}) &&
                   1429:             $ENV{'form.'.$field.'_max'} ne '') {
                   1430:             $max = $ENV{'form.'.$field.'_max'};
                   1431:         }
                   1432:         next if (! defined($max) && ! defined($min));
                   1433:         if (defined($min) && defined($max)) {
                   1434:             ($min,$max) = sort {$a <=>$b} ($min,$max);
                   1435:         }
                   1436:         if (defined($min) && $min =~ /^(\d+\.\d+|\d+|\.\d+)$/) {
                   1437:             push(@queries,'('.$field.'>'.$min.')');
                   1438:             $pretty_search_string.=$font.$field.'</font>&gt;'.$min.'<br />';
                   1439:         }
                   1440:         if (defined($max) && $max =~ /^(\d+\.\d+|\d+|\.\d+)$/) {
                   1441:             push(@queries,'('.$field.'<'.$max.')');
                   1442:             $pretty_search_string.=$font.$field.'</font>&lt;'.$max.'<br />';
                   1443:         }
                   1444:     }
                   1445:     #
1.90      harris41 1446:     # Evaluate date windows
1.216     matthew  1447:     my $cafter =
                   1448:         &Apache::lonhtmlcommon::get_date_from_form('creationdate1');
                   1449:     my $cbefore = 
                   1450:         &Apache::lonhtmlcommon::get_date_from_form('creationdate2');
                   1451:     if ($cafter > $cbefore) {
                   1452:         my $tmp = $cafter;
                   1453:         $cafter = $cbefore;
                   1454:         $cbefore = $tmp;
                   1455:     }
                   1456:     my $mafter = 
                   1457:         &Apache::lonhtmlcommon::get_date_from_form('revisiondate1');
                   1458:     my $mbefore =
                   1459:         &Apache::lonhtmlcommon::get_date_from_form('revisiondate2');
                   1460:     if ($mafter > $mbefore) {
                   1461:         my $tmp = $mafter;
                   1462:         $mafter = $mbefore;
                   1463:         $mbefore = $tmp;
                   1464:     }
                   1465:     my ($datequery,$error,$prettydate)=&build_date_queries($cafter,$cbefore,
                   1466:                                                            $mafter,$mbefore);
                   1467:     if (defined($error)) {
                   1468:         &output_date_error($r,$error,$closebutton,$hidden_fields);
                   1469:     } elsif (defined($datequery)) {
1.143     matthew  1470:         # Here is where you would set up pretty_search_string to output
                   1471:         # date query information.
1.216     matthew  1472:         $pretty_search_string .= '<br />'.$prettydate.'<br />';
1.60      harris41 1473: 	push @queries,$datequery;
                   1474:     }
1.204     matthew  1475:     #
1.90      harris41 1476:     # Process form information for custom metadata querying
1.134     matthew  1477:     my $customquery=undef;
1.204     matthew  1478:     ##
                   1479:     ## The custom metadata search was removed q long time ago mostly 
                   1480:     ## because I was unable to figureout exactly how it worked and could
                   1481:     ## not imagine people actually using it.  MH
                   1482:     ##
                   1483:     # if ($ENV{'form.custommetadata'}) {
                   1484:     #    $pretty_search_string .=$font."Custom Metadata Search</font>: <b>".
                   1485:     #    $ENV{'form.custommetadata'}."</b><br />\n";
                   1486:     #    $customquery=&build_custommetadata_query('custommetadata',
                   1487:     #                                             $ENV{'form.custommetadata'});
                   1488:     # }
1.134     matthew  1489:     my $customshow=undef;
1.204     matthew  1490:     # if ($ENV{'form.customshow'}) {
                   1491:     # $pretty_search_string .=$font."Custom Metadata Display</font>: <b>".
                   1492:     #                         $ENV{'form.customshow'}."</b><br />\n";
                   1493:     #    $customshow=$ENV{'form.customshow'};
                   1494:     #    $customshow=~s/[^\w\s]//g;
                   1495:     #    my @fields=split(/\s+/,$customshow);
                   1496:     #    $customshow=join(" ",@fields);
                   1497:     # }
                   1498:     ##
1.132     matthew  1499:     ## Deal with restrictions to given domains
                   1500:     ## 
1.180     matthew  1501:     my ($libraries_to_query,$pretty_domains_string) = 
                   1502:         &parse_domain_restrictions();
                   1503:     $pretty_search_string .= $pretty_domains_string."<br />\n";
                   1504:     #
                   1505:     if (@queries) {
1.228     matthew  1506: 	$query="SELECT * FROM metadata WHERE (".join(") AND (",@queries).')';
1.180     matthew  1507:     } elsif ($customquery) {
                   1508:         $query = '';
                   1509:     }
1.228     matthew  1510:     # &Apache::lonnet::logthis('query = '.$/.$query);
1.180     matthew  1511:     return ($query,$customquery,$customshow,$libraries_to_query,
                   1512:             $pretty_search_string);
                   1513: }
                   1514: 
                   1515: sub parse_domain_restrictions {
1.132     matthew  1516:     my $libraries_to_query = undef;
                   1517:     # $ENV{'form.domains'} can be either a scalar or an array reference.
                   1518:     # We need an array.
1.221     matthew  1519:     if (! exists($ENV{'form.domains'}) || $ENV{'form.domains'} eq '') {
1.180     matthew  1520:         return (undef,'');
                   1521:     }
                   1522:     my @allowed_domains;
                   1523:     if (ref($ENV{'form.domains'})) {
                   1524:         @allowed_domains =  @{$ENV{'form.domains'}};
                   1525:     } else {
                   1526:         @allowed_domains = ($ENV{'form.domains'});
                   1527:     }
1.204     matthew  1528:     #
1.132     matthew  1529:     my %domain_hash = ();
1.143     matthew  1530:     my $pretty_domains_string;
1.132     matthew  1531:     foreach (@allowed_domains) {
                   1532:         $domain_hash{$_}++;
                   1533:     }
1.143     matthew  1534:     if ($domain_hash{'any'}) {
1.152     matthew  1535:         $pretty_domains_string = "In all LON-CAPA domains.";
1.143     matthew  1536:     } else {
                   1537:         if (@allowed_domains > 1) {
1.152     matthew  1538:             $pretty_domains_string = "In LON-CAPA domains:";
1.143     matthew  1539:         } else {
1.152     matthew  1540:             $pretty_domains_string = "In LON-CAPA domain ";
1.143     matthew  1541:         }
                   1542:         foreach (sort @allowed_domains) {
1.152     matthew  1543:             $pretty_domains_string .= "<b>".$_."</b> ";
1.132     matthew  1544:         }
1.143     matthew  1545:         foreach (keys(%Apache::lonnet::libserv)) {
                   1546:             if (exists($domain_hash{$Apache::lonnet::hostdom{$_}})) {
                   1547:                 push @$libraries_to_query,$_;
                   1548:             }
1.132     matthew  1549:         }
                   1550:     }
1.180     matthew  1551:     return ($libraries_to_query,$pretty_domains_string);
1.18      harris41 1552: }
                   1553: 
1.122     matthew  1554: ######################################################################
                   1555: ######################################################################
                   1556: 
                   1557: =pod 
                   1558: 
1.134     matthew  1559: =item &parse_basic_search() 
1.122     matthew  1560: 
1.134     matthew  1561: Parse the basic search form and return a scalar containing an sql query.
1.126     matthew  1562: 
1.122     matthew  1563: =cut
                   1564: 
                   1565: ######################################################################
                   1566: ######################################################################
1.134     matthew  1567: sub parse_basic_search {
1.145     matthew  1568:     my ($r,$closebutton)=@_;
1.204     matthew  1569:     #
1.64      harris41 1570:     # Clean up fields for safety
                   1571:     for my $field ('basicexp') {
1.228     matthew  1572: 	$ENV{"form.$field"}=~s/[^\w\s\'\"\!\(\)\-]//g;
1.64      harris41 1573:     }
1.117     matthew  1574:     foreach ('mode','form','element') {
                   1575: 	# is this required?  Hmmm.
                   1576: 	next unless (exists($ENV{"form.$_"}));
                   1577: 	$ENV{"form.$_"}=&Apache::lonnet::unescape($ENV{"form.$_"});
                   1578: 	$ENV{"form.$_"}=~s/[^\w\/\s\(\)\=\-\"\']//g;
                   1579:     }
1.180     matthew  1580:     my ($libraries_to_query,$pretty_domains_string) = 
                   1581:         &parse_domain_restrictions();
1.204     matthew  1582:     #
                   1583:     # Check to see if enough of a query is filled in
1.220     matthew  1584:     my $search_string = $ENV{'form.basicexp'};
                   1585:     if (! &filled($search_string)) {
1.151     matthew  1586: 	&output_blank_field_error($r,$closebutton,'phase=disp_basic');
1.24      harris41 1587: 	return OK;
                   1588:     }
1.228     matthew  1589:     my $pretty_search_string=$search_string;
1.224     matthew  1590:     my @Queries;
1.228     matthew  1591:     my $searchfield = 'concat_ws(" ",'.join(',',
                   1592:                                             ('title','author','subject',
                   1593:                                              'notes','abstract','keywords')
                   1594:                                             ).')';
                   1595:     my ($error,$SQLQuery) = &process_phrase_input($search_string,
                   1596:                                                     $ENV{'form.related'},
                   1597:                                                     $searchfield);
                   1598:     if ($error) {
                   1599:         &output_unparsed_phrase_error($r,$closebutton,'phase=disp_basic',
                   1600:                                       '','basicexp');
                   1601:         return;
1.141     matthew  1602:     }
1.228     matthew  1603:     push(@Queries,$SQLQuery);
                   1604:     #foreach my $q (@Queries) {
                   1605:     #    &Apache::lonnet::logthis('    '.$q);
                   1606:     #}
1.224     matthew  1607:     my $final_query = 'SELECT * FROM metadata WHERE '.join(" AND ",@Queries);
1.204     matthew  1608:     #
1.180     matthew  1609:     if (defined($pretty_domains_string) && $pretty_domains_string ne '') {
                   1610:         $pretty_search_string .= ' '.$pretty_domains_string;
                   1611:     }
1.143     matthew  1612:     $pretty_search_string .= "<br />\n";
1.225     matthew  1613:     $pretty_search_string =~ s:^<br /> and ::;
1.228     matthew  1614:     # &Apache::lonnet::logthis($final_query);
1.183     matthew  1615:     return ($final_query,$pretty_search_string,
1.180     matthew  1616:             $libraries_to_query);
1.22      harris41 1617: }
                   1618: 
1.228     matthew  1619: 
                   1620: ###############################################################
                   1621: ###############################################################
                   1622: 
                   1623: my @Phrases;
                   1624: 
                   1625: sub concat {
                   1626:     my ($item) = @_;
                   1627:     my $results = '';
                   1628:     foreach (@$item) {
                   1629:         if (ref($_) eq 'ARRAY') {
                   1630:             $results .= join(' ',@$_);
                   1631:         }
                   1632:     }
                   1633:     return $results;
                   1634: }
                   1635: 
1.224     matthew  1636: sub process_phrase_input {
1.228     matthew  1637:     my ($phrase,$related,$field)=@_;
                   1638:     #&Apache::lonnet::logthis('phrase = :'.$phrase.':');
                   1639:     my $grammar = <<'ENDGRAMMAR';
                   1640:     searchphrase:
                   1641:         expression /^\Z/ {
                   1642:             # &Apache::lonsearchcat::print_item(\@item,0);
                   1643:             [@item];
                   1644:         }
                   1645:     expression:
                   1646:         phrase(s)   {
                   1647:             [@item];
                   1648:         }
                   1649:     phrase:
                   1650:         orword {
                   1651:             [@item];
                   1652:         }
                   1653:       | andword {
                   1654:             [@item];
                   1655:         }
                   1656:       | minusword {
                   1657:             unshift(@::Phrases,$item[1]->[0]);
                   1658:             unshift(@::Phrases,$item[1]->[1]);
                   1659:             [@item];
                   1660:         }
                   1661:       | word {
                   1662:             unshift(@::Phrases,$item[1]);
                   1663:             [@item];
                   1664:         } 
                   1665:     #
                   1666:     orword:
                   1667:         word 'OR' phrase {
                   1668:             unshift(@::Phrases,'OR');
                   1669:             unshift(@::Phrases,$item[1]);
                   1670:             [@item];
                   1671:         }
                   1672:         | word 'or' phrase {
                   1673:             unshift(@::Phrases,'OR');
                   1674:             unshift(@::Phrases,$item[1]);
                   1675:             [@item];
                   1676:         }    
                   1677:         | minusword 'OR' phrase {
                   1678:             unshift(@::Phrases,'OR');
                   1679:             unshift(@::Phrases,$item[1]->[0]);
                   1680:             unshift(@::Phrases,$item[1]->[1]);
                   1681:             [@item];
                   1682:         }
                   1683:         | minusword 'or' phrase {
                   1684:             unshift(@::Phrases,'OR');
                   1685:             unshift(@::Phrases,$item[1]->[0]);
                   1686:             unshift(@::Phrases,$item[1]->[1]);
                   1687:             [@item];
                   1688:         }    
                   1689:     andword:
                   1690:         word phrase {
                   1691:             unshift(@::Phrases,'AND');
                   1692:             unshift(@::Phrases,$item[1]);
                   1693:             [@item];
                   1694:         }
                   1695:         | minusword phrase {
                   1696:             unshift(@::Phrases,'AND');
                   1697:             unshift(@::Phrases,$item[1]->[0]);
                   1698:             unshift(@::Phrases,$item[1]->[1]);
                   1699:             [@item];
                   1700:         }
                   1701:     #
                   1702:     minusword:
                   1703:         '-' word {
                   1704:             [$item[2],'NOT'];
                   1705:         }
                   1706:     word:
                   1707:         "'" term(s) "'" {
                   1708:           &Apache::lonsearchcat::concat(\@item);
                   1709:         }
                   1710:       | '"' term(s) '"' {
                   1711:           &Apache::lonsearchcat::concat(\@item);
                   1712:         }
                   1713:       | term {
                   1714:             $item[1];
                   1715:         }
                   1716:     term:
                   1717:         /[\w\Q:!@#$%^&*()+_=|{}<>,.;\\\/?\E]+/ {
                   1718:             $item[1];
                   1719:         }
                   1720: ENDGRAMMAR
                   1721:     #
                   1722:     # The end result of parsing the phrase with the grammar is an array
                   1723:     # @::Phrases.
                   1724:     # $phrase = "gene splicing" or cat -> "gene splicing","OR","cat"
                   1725:     # $phrase = "genetic engineering" -dna ->
                   1726:     #                      "genetic engineering","AND","NOT","dna"
                   1727:     # $phrase = cat or dog -poodle -> "cat","OR","dog","AND","NOT","poodle"
                   1728:     undef(@::Phrases);
                   1729:     my $p = new Parse::RecDescent($grammar);
                   1730:     if (! defined($p->searchphrase($phrase))) {
                   1731:         &Apache::lonnet::logthis('lonsearchcat:unable to process:'.$phrase);
                   1732:         return 'Unable to process phrase '.$phrase;
                   1733:     }
                   1734:     #
                   1735:     # Go through the phrases and make sense of them.  
                   1736:     # Apply modifiers NOT OR and AND to the phrases.
                   1737:     my @NewPhrases;
                   1738:     while(@::Phrases) {
                   1739:         my $phrase = shift(@::Phrases);
                   1740:         # &Apache::lonnet::logthis('phrase = '.$phrase);
                   1741:         my $phrasedata;
                   1742:         if ($phrase =~ /^(NOT|OR|AND)$/) {
                   1743:             if ($phrase eq 'OR') {
                   1744:                 $phrasedata->{'or'}++;
                   1745:                 if (! @::Phrases) { $phrasedata = undef; last; }
                   1746:                 $phrase = shift(@::Phrases);
                   1747:             } elsif ($phrase eq 'AND') {
                   1748:                 $phrasedata->{'and'}++;
                   1749:                 if (! @::Phrases) { $phrasedata = undef; last; }
                   1750:                 $phrase = shift(@::Phrases);
1.224     matthew  1751:             }
1.228     matthew  1752:             if ($phrase eq 'NOT') {
                   1753:                 $phrasedata->{'negate'}++;
                   1754:                 if (! @::Phrases) { $phrasedata = undef; last; }
                   1755:                 $phrase = shift(@::Phrases);
1.224     matthew  1756:             }
1.228     matthew  1757:         }
                   1758:         $phrasedata->{'phrase'} = $phrase;
                   1759:         if ($related) {
                   1760:             my @NewWords;
                   1761:             (undef,@NewWords) = &related_version($phrasedata->{'phrase'});
                   1762:             $phrasedata->{'related_words'} = \@NewWords;
                   1763:         }
                   1764:         push(@NewPhrases,$phrasedata);
                   1765:     }
                   1766:     #
                   1767:     # Actually build the sql query from the phrases
                   1768:     my $SQLQuery;
                   1769:     foreach my $phrase (@NewPhrases) {
                   1770:         my $query;
                   1771:         if ($phrase->{'negate'}) {
                   1772:             $query .= $field.' NOT LIKE "%'.$phrase->{'phrase'}.'%"';
1.224     matthew  1773:         } else {
1.228     matthew  1774:             $query .= $field.' LIKE "%'.$phrase->{'phrase'}.'%"';
                   1775:         }
                   1776:         foreach my $related (@{$phrase->{'related_words'}}) {
                   1777:             if ($phrase->{'negate'}) {
                   1778:                 $query .= ' AND '.$field.' NOT LIKE "%'.$related.'%"';
                   1779:             } else {
                   1780:                 $query .= ' OR '.$field.' LIKE "%'.$related.'%"';
                   1781:             }
                   1782:         }
                   1783:         if ($SQLQuery) {
                   1784:             if ($phrase->{'or'}) {
                   1785:                 $SQLQuery .= ' OR ('.$query.')';
                   1786:             } else {
                   1787:                 $SQLQuery .= ' AND ('.$query.')';
1.224     matthew  1788:             }
1.228     matthew  1789:         } else {
                   1790:             $SQLQuery = '('.$query.')';
1.224     matthew  1791:         }
                   1792:     }
                   1793:     #
1.228     matthew  1794:     # &Apache::lonnet::logthis("SQLQuery = $SQLQuery");
1.224     matthew  1795:     #
1.228     matthew  1796:     return undef,$SQLQuery;
1.224     matthew  1797: }
                   1798: 
1.122     matthew  1799: ######################################################################
                   1800: ######################################################################
                   1801: 
                   1802: =pod 
                   1803: 
1.204     matthew  1804: =item &related_version()
1.142     matthew  1805: 
                   1806: Modifies an input string to include related words.  Words in the string
                   1807: are replaced with parenthesized lists of 'OR'd words.  For example
                   1808: "torque" is replaced with "(torque OR word1 OR word2 OR ...)".  
                   1809: 
                   1810: Note: Using this twice on a string is probably silly.
                   1811: 
                   1812: =cut
                   1813: 
                   1814: ######################################################################
                   1815: ######################################################################
                   1816: sub related_version {
1.224     matthew  1817:     my ($word) = @_;
                   1818:     return (undef) if (lc($word) =~ /\b(or|and|not)\b/);
                   1819:     my @Words = &Apache::loncommon::get_related_words($word);
                   1820:     # Only use 4 related words
                   1821:     @Words = ($#Words>4? @Words[0..4] : @Words);
                   1822:     my $result = join " OR ", ($word,@Words);
                   1823:     return $result,sort(@Words);
1.142     matthew  1824: }
                   1825: 
1.98      harris41 1826: 
1.122     matthew  1827: ######################################################################
                   1828: ######################################################################
                   1829: 
                   1830: =pod 
                   1831: 
                   1832: =item &build_custommetadata_query() 
                   1833: 
1.126     matthew  1834: Constructs a custom metadata query using a rather heinous regular
                   1835: expression.
                   1836: 
1.122     matthew  1837: =cut
                   1838: 
                   1839: ######################################################################
                   1840: ######################################################################
1.98      harris41 1841: sub build_custommetadata_query {
                   1842:     my ($field_name,$logic_statement)=@_;
                   1843:     my $q=new Text::Query('abc',
                   1844: 			  -parse => 'Text::Query::ParseAdvanced',
                   1845: 			  -build => 'Text::Query::BuildAdvancedString');
                   1846:     $q->prepare($logic_statement);
                   1847:     my $matchexp=${$q}{'-parse'}{'-build'}{'matchstring'};
                   1848:     # quick fix to change literal into xml tag-matching
                   1849:     # will eventually have to write a separate builder module
1.122     matthew  1850:     # wordone=wordtwo becomes\<wordone\>[^\<] *wordtwo[^\<]*\<\/wordone\>
                   1851:     $matchexp =~ s/(\w+)\\=([\w\\\+]+)?# wordone=wordtwo is changed to 
                   1852:                  /\\<$1\\>?#           \<wordone\>
                   1853:                    \[\^\\<\]?#        [^\<]         
                   1854:                    \*$2\[\^\\<\]?#           *wordtwo[^\<]
                   1855:                    \*\\<\\\/$1\\>?#                        *\<\/wordone\>
                   1856:                    /g;
1.98      harris41 1857:     return $matchexp;
                   1858: }
                   1859: 
1.22      harris41 1860: 
1.122     matthew  1861: ######################################################################
                   1862: ######################################################################
                   1863: 
                   1864: =pod 
                   1865: 
                   1866: =item &build_date_queries() 
                   1867: 
1.126     matthew  1868: Builds a SQL logic query to check time/date entries.
                   1869: Also reports errors (check for /^Incorrect/).
                   1870: 
1.122     matthew  1871: =cut
                   1872: 
                   1873: ######################################################################
                   1874: ######################################################################
1.98      harris41 1875: sub build_date_queries {
1.216     matthew  1876:     my ($cafter,$cbefore,$mafter,$mbefore) = @_;
                   1877:     my ($result,$error,$pretty_string);
                   1878:     #
                   1879:     # Verify the input
                   1880:     if (! defined($cafter) && ! defined($cbefore) &&
                   1881:         ! defined($mafter) && ! defined($mbefore)) {
                   1882:         # This is an okay situation, so return undef for the error
                   1883:         return (undef,undef,undef);
                   1884:     }
                   1885:     if ((defined($cafter)  && ! defined($cbefore)) ||
                   1886:         (defined($cbefore) && ! defined($cafter))) {
                   1887:         # This is bad, so let them know
                   1888:         $error = &mt('Incorrect entry for the creation date.  '.
                   1889:                     'You must specify both the beginning and ending dates.');
                   1890:     }
                   1891:     if (! defined($error) && 
                   1892:         ((defined($mafter)  && ! defined($mbefore)) ||
                   1893:         (defined($mbefore) && ! defined($mafter)))) {
                   1894:         # This is also bad, so let them know
                   1895:         $error = &mt('Incorrect entry for the last revision date.  '.
                   1896:                      'You must specify both the beginning and ending dates.');
1.98      harris41 1897:     }
1.216     matthew  1898:     if (! defined($error)) {
                   1899:         #
                   1900:         # Build the queries
                   1901:         my @queries;
                   1902:         if (defined($cbefore) && defined($cafter)) {
                   1903:             my (undef,undef,undef,$caday,$camon,$cayear) = localtime($cafter);
                   1904:             my (undef,undef,undef,$cbday,$cbmon,$cbyear) = localtime($cbefore);
                   1905:             # Correct for year being relative to 1900
                   1906:             $cayear+=1900; $cbyear+=1900;
                   1907:             my $cquery=
                   1908:                 '(creationdate BETWEEN '.
                   1909:                 "'".$cayear.'-'.$camon.'-'.$caday."'".
                   1910:                 ' AND '.
                   1911:                 "'".$cbyear.'-'.$cbmon.'-'.$cbday." 23:59:59')";
                   1912:             $pretty_string .= '<br />' if (defined($pretty_string));
                   1913:             $pretty_string .= 
                   1914:                 &mt('created between [_1] and [_2]',
                   1915:                     &Apache::lonlocal::locallocaltime($cafter),
                   1916:                     &Apache::lonlocal::locallocaltime($cbefore+24*60*60-1));
                   1917:             push(@queries,$cquery);
                   1918:             $pretty_string =~ s/ 00:00:00//g;
                   1919:         }
                   1920:         if (defined($mbefore) && defined($mafter)) {
                   1921:             my (undef,undef,undef,$maday,$mamon,$mayear) = localtime($mafter);
                   1922:             my (undef,undef,undef,$mbday,$mbmon,$mbyear) = localtime($mbefore);
                   1923:             # Correct for year being relative to 1900
                   1924:             $mayear+=1900; $mbyear+=1900;
                   1925:             my $mquery=
                   1926:                 '(lastrevisiondate BETWEEN '.
                   1927:                 "'".$mayear.'-'.$mamon.'-'.$maday."'".
                   1928:                 ' AND '.
                   1929:                 "'".$mbyear.'-'.$mbmon.'-'.$mbday." 23:59:59')";
                   1930:             push(@queries,$mquery);
                   1931:             $pretty_string .= '<br />' if (defined($pretty_string));
                   1932:             $pretty_string .= 
                   1933:                 &mt('last revised between [_1] and [_2]',
                   1934:                     &Apache::lonlocal::locallocaltime($mafter),
                   1935:                     &Apache::lonlocal::locallocaltime($mbefore+24*60*60-1));
                   1936:             $pretty_string =~ s/ 00:00:00//g;
                   1937:         }
                   1938:         if (@queries) {
                   1939:             $result .= join(" AND ",@queries);
                   1940:         }
1.98      harris41 1941:     }
1.216     matthew  1942:     return ($result,$error,$pretty_string);
1.18      harris41 1943: }
1.6       harris41 1944: 
1.122     matthew  1945: ######################################################################
                   1946: ######################################################################
                   1947: 
1.144     matthew  1948: =pod
                   1949: 
                   1950: =item &copyright_check()
                   1951: 
1.204     matthew  1952: Inputs: $Metadata, a hash pointer of metadata for a resource.
                   1953: 
                   1954: Returns: 1 if the resource is available to the user making the query, 
                   1955:          0 otherwise.
                   1956: 
1.144     matthew  1957: =cut
                   1958: 
                   1959: ######################################################################
                   1960: ######################################################################
                   1961: sub copyright_check {
                   1962:     my $Metadata = shift;
                   1963:     # Check copyright tags and skip results the user cannot use
                   1964:     my (undef,undef,$resdom,$resname) = split('/',
                   1965:                                               $Metadata->{'url'});
                   1966:     # Check for priv
                   1967:     if (($Metadata->{'copyright'} eq 'priv') && 
                   1968:         (($ENV{'user.name'} ne $resname) &&
                   1969:          ($ENV{'user.domain'} ne $resdom))) {
                   1970:         return 0;
                   1971:     }
                   1972:     # Check for domain
                   1973:     if (($Metadata->{'copyright'} eq 'domain') &&
                   1974:         ($ENV{'user.domain'} ne $resdom)) {
                   1975:         return 0;
                   1976:     }
                   1977:     return 1;
                   1978: }
                   1979: 
1.151     matthew  1980: ######################################################################
                   1981: ######################################################################
                   1982: 
                   1983: =pod
                   1984: 
1.204     matthew  1985: =item &ensure_db_and_table()
1.151     matthew  1986: 
                   1987: Ensure we can get lonmysql to connect to the database and the table we
                   1988: need exists.
                   1989: 
                   1990: Inputs: $r, table id
                   1991: 
                   1992: Returns: undef on error, 1 if the table exists.
                   1993: 
                   1994: =cut
                   1995: 
                   1996: ######################################################################
                   1997: ######################################################################
                   1998: sub ensure_db_and_table {
                   1999:     my ($r,$table) = @_;
                   2000:     ##
                   2001:     ## Sanity check the table id.
                   2002:     ##
                   2003:     if (! defined($table) || $table eq '' || $table =~ /\D/ ) {
                   2004:         $r->print("Unable to retrieve search results.  ".
                   2005:                   "Unable to determine the table results were stored in.  ".
                   2006:                   "</body></html>");
                   2007:         return undef;
                   2008:     }
                   2009:     ##
                   2010:     ## Make sure we can connect and the table exists.
                   2011:     ##
                   2012:     my $connection_result = &Apache::lonmysql::connect_to_db();
                   2013:     if (!defined($connection_result)) {
                   2014:         $r->print("Unable to connect to the MySQL database where your results".
                   2015:                   " are stored. </body></html>");
                   2016:         &Apache::lonnet::logthis("lonsearchcat: unable to get lonmysql to".
                   2017:                                  " connect to database.");
                   2018:         &Apache::lonnet::logthis(&Apache::lonmysql::get_error());
                   2019:         return undef;
                   2020:     }
                   2021:     my $table_check = &Apache::lonmysql::check_table($table);
                   2022:     if (! defined($table_check)) {
                   2023:         $r->print("A MySQL error has occurred.</form></body></html>");
                   2024:         &Apache::lonnet::logthis("lonmysql was unable to determine the status".
                   2025:                                  " of table ".$table);
                   2026:         return undef;
                   2027:     } elsif (! $table_check) {
                   2028:         $r->print("The table of results could not be found.");
                   2029:         &Apache::lonnet::logthis("The user requested a table, ".$table.
                   2030:                                  ", that could not be found.");
                   2031:         return undef;
                   2032:     }
                   2033:     return 1;
                   2034: }
                   2035: 
                   2036: ######################################################################
                   2037: ######################################################################
                   2038: 
                   2039: =pod
                   2040: 
1.204     matthew  2041: =item &print_sort_form()
                   2042: 
                   2043: The sort feature is not implemented at this time.  This form just prints 
                   2044: a link to change the search query.
1.151     matthew  2045: 
                   2046: =cut
                   2047: 
                   2048: ######################################################################
                   2049: ######################################################################
                   2050: sub print_sort_form {
                   2051:     my ($r,$pretty_query_string) = @_;
1.224     matthew  2052:     my $bodytag=&Apache::loncommon::bodytag(undef,undef,undef,1).
                   2053:         &Apache::lonhtmlcommon::breadcrumbs
                   2054:         (undef,'Searching','Searching',undef,undef,
1.227     matthew  2055:          $ENV{'form.catalogmode'} ne 'groupsearch');
1.224     matthew  2056: 
1.151     matthew  2057:     ##
1.187     www      2058:     my %SortableFields=&Apache::lonlocal::texthash( 
                   2059:          id        => 'Default',
1.151     matthew  2060:          title     => 'Title',
                   2061:          author    => 'Author',
                   2062:          subject   => 'Subject',
                   2063:          url       => 'URL',
                   2064:          version   => 'Version Number',
                   2065:          mime      => 'Mime type',
                   2066:          lang      => 'Language',
                   2067:          owner     => 'Owner/Publisher',
                   2068:          copyright => 'Copyright',
                   2069:          hostname  => 'Host',
                   2070:          creationdate     => 'Creation Date',
1.187     www      2071:          lastrevisiondate => 'Revision Date'
1.151     matthew  2072:      );
                   2073:     ##
                   2074:     my $table = $ENV{'form.table'};
                   2075:     return if (! &ensure_db_and_table($r,$table));
                   2076:     ##
                   2077:     ## Get the number of results 
                   2078:     ##
                   2079:     my $total_results = &Apache::lonmysql::number_of_rows($table);
                   2080:     if (! defined($total_results)) {
                   2081:         $r->print("A MySQL error has occurred.</form></body></html>");
                   2082:         &Apache::lonnet::logthis("lonmysql was unable to determine the number".
                   2083:                                  " of rows in table ".$table);
                   2084:         &Apache::lonnet::logthis(&Apache::lonmysql::get_error());
                   2085:         return;
                   2086:     }
                   2087:     my $result;
                   2088:     $result.=<<END;
                   2089: <html>
                   2090: <head>
                   2091: <script>
                   2092:     function change_sort() {
                   2093:         var newloc = "/adm/searchcat?phase=results";
                   2094:         newloc += "&persistent_db_id=$ENV{'form.persistent_db_id'}";
                   2095:         newloc += "&sortby=";
                   2096:         newloc += document.forms.statusform.elements.sortby.value;
                   2097:         parent.resultsframe.location= newloc;
                   2098:     }
                   2099: </script>
                   2100: <title>Results</title>
                   2101: </head>
1.155     matthew  2102: $bodytag
1.151     matthew  2103: <form name="statusform" action="" method="post">
1.153     matthew  2104: <input type="hidden" name="Queue" value="" />
1.151     matthew  2105: END
                   2106: 
                   2107: #<h2>Sort Results</h2>
                   2108: #Sort by: <select size="1" name="sortby" onchange="javascript:change_sort();">
                   2109: #    $ENV{'form.sortby'} = 'id' if (! defined($ENV{'form.sortby'}));
                   2110: #    foreach (keys(%SortableFields)) {
                   2111: #        $result.="<option name=\"$_\"";
                   2112: #        if ($_ eq $ENV{'form.sortby'}) {
                   2113: #            $result.=" selected ";
                   2114: #        }
                   2115: #        $result.=" >$SortableFields{$_}</option>\n";
                   2116: #    }
                   2117: #    $result.="</select>\n";
                   2118:     my $revise = &revise_button();
                   2119:     $result.=<<END;
                   2120: <p>
                   2121: There are $total_results matches to your query. $revise
                   2122: </p><p>
                   2123: Search:$pretty_query_string
                   2124: </p>
                   2125: </form>
                   2126: </body>
                   2127: </html>
                   2128: END
                   2129:     $r->print($result);
                   2130:     return;
                   2131: }
                   2132: 
1.144     matthew  2133: #####################################################################
                   2134: #####################################################################
                   2135: 
                   2136: =pod
                   2137: 
                   2138: =item MySQL Table Description
                   2139: 
                   2140: MySQL table creation requires a precise description of the data to be
                   2141: stored.  The use of the correct types to hold data is vital to efficient
                   2142: storage and quick retrieval of records.  The columns must be described in
                   2143: the following format:
                   2144: 
                   2145: =cut
                   2146: 
1.170     matthew  2147: #####################################################################
                   2148: #####################################################################
1.204     matthew  2149: #
                   2150: # These should probably be scoped but I don't have time right now...
                   2151: #
                   2152: my @Datatypes;
                   2153: my @Fullindicies;
1.147     matthew  2154:     
1.144     matthew  2155: ######################################################################
                   2156: ######################################################################
                   2157: 
                   2158: =pod
                   2159: 
1.146     matthew  2160: =item &create_results_table()
                   2161: 
                   2162: Creates the table of search results by calling lonmysql.  Stores the
                   2163: table id in $ENV{'form.table'}
                   2164: 
                   2165: Inputs: none.
                   2166: 
                   2167: Returns: the identifier of the table on success, undef on error.
                   2168: 
                   2169: =cut
                   2170: 
                   2171: ######################################################################
                   2172: ######################################################################
1.204     matthew  2173: sub set_up_table_structure {
                   2174:     my ($datatypes,$fullindicies) = 
                   2175:         &LONCAPA::lonmetadata::describe_metadata_storage();
1.212     matthew  2176:     # Copy the table description before modifying it...
                   2177:     @Datatypes = @{$datatypes};
                   2178:     unshift(@Datatypes,{name => 'id',  
1.204     matthew  2179:         type => 'MEDIUMINT',
                   2180:         restrictions => 'UNSIGNED NOT NULL',
                   2181:         primary_key  => 'yes',
                   2182:         auto_inc     => 'yes' });
                   2183:     @Fullindicies = @{$fullindicies};
                   2184:     return;
                   2185: }
                   2186: 
1.146     matthew  2187: sub create_results_table {
1.204     matthew  2188:     &set_up_table_structure();
1.146     matthew  2189:     my $table = &Apache::lonmysql::create_table
1.170     matthew  2190:         ( { columns => \@Datatypes,
1.172     matthew  2191:             FULLTEXT => [{'columns' => \@Fullindicies},],
1.146     matthew  2192:         } );
                   2193:     if (defined($table)) {
                   2194:         $ENV{'form.table'} = $table;
                   2195:         return $table;
                   2196:     } 
                   2197:     return undef; # Error...
                   2198: }
1.148     matthew  2199: 
1.146     matthew  2200: ######################################################################
                   2201: ######################################################################
                   2202: 
                   2203: =pod
                   2204: 
1.150     matthew  2205: =item Search Status update functions
1.144     matthew  2206: 
1.150     matthew  2207: Each of the following functions changes the values of one of the
                   2208: input fields used to display the search status to the user.  The names
                   2209: should be explanatory.
1.144     matthew  2210: 
1.150     matthew  2211: Inputs: Apache request handler ($r), text to display.
1.148     matthew  2212: 
1.150     matthew  2213: Returns: Nothing.
1.148     matthew  2214: 
                   2215: =over 4
                   2216: 
                   2217: =item &update_count_status()
                   2218: 
1.150     matthew  2219: =item &update_status()
1.148     matthew  2220: 
1.150     matthew  2221: =item &update_seconds()
1.148     matthew  2222: 
                   2223: =back
                   2224: 
                   2225: =cut
                   2226: 
                   2227: ######################################################################
                   2228: ######################################################################
                   2229: sub update_count_status {
                   2230:     my ($r,$text) = @_;
                   2231:     $text =~ s/\'/\\\'/g;
                   2232:     $r->print
                   2233:         ("<script>document.statusform.count.value = ' $text'</script>\n");
                   2234:     $r->rflush();
                   2235: }
                   2236: 
1.150     matthew  2237: sub update_status {
1.148     matthew  2238:     my ($r,$text) = @_;
                   2239:     $text =~ s/\'/\\\'/g;
                   2240:     $r->print
1.150     matthew  2241:         ("<script>document.statusform.status.value = ' $text'</script>\n");
1.148     matthew  2242:     $r->rflush();
                   2243: }
                   2244: 
1.214     matthew  2245: {
                   2246:     my $max_time  = 40;  # seconds for the search to complete
                   2247:     my $start_time = 0;
                   2248:     my $last_time = 0;
                   2249: 
                   2250: sub reset_timing {
                   2251:     $start_time = 0;
                   2252:     $last_time = 0;
                   2253: }
                   2254: 
                   2255: sub time_left {
                   2256:     if ($start_time == 0) {
                   2257:         $start_time = time;
                   2258:     }
                   2259:     my $time_left = $max_time - (time - $start_time);
                   2260:     $time_left = 0 if ($time_left < 0);
                   2261:     return $time_left;
                   2262: }
                   2263: 
1.150     matthew  2264: sub update_seconds {
1.214     matthew  2265:     my ($r) = @_;
                   2266:     my $time = &time_left();
                   2267:     if (($last_time-$time) > 0) {
                   2268:         $r->print("<script>".
                   2269:                   "document.statusform.seconds.value = '$time'".
                   2270:                   "</script>\n");
                   2271:         $r->rflush();
                   2272:     }
                   2273:     $last_time = $time;
                   2274: }
                   2275: 
1.148     matthew  2276: }
                   2277: 
                   2278: ######################################################################
                   2279: ######################################################################
                   2280: 
                   2281: =pod
                   2282: 
1.204     matthew  2283: =item &revise_button()
1.151     matthew  2284: 
                   2285: Inputs: None
                   2286: 
                   2287: Returns: html string for a 'revise search' button.
                   2288: 
                   2289: =cut
                   2290: 
                   2291: ######################################################################
                   2292: ######################################################################
                   2293: sub revise_button {
                   2294:     my $revise_phase = 'disp_basic';
                   2295:     $revise_phase = 'disp_adv' if ($ENV{'form.searchmode'} eq 'advanced');
                   2296:     my $newloc = '/adm/searchcat'.
                   2297:         '?persistent_db_id='.$ENV{'form.persistent_db_id'}.
1.158     matthew  2298:             '&cleargroupsort=1'.
1.151     matthew  2299:             '&phase='.$revise_phase;
                   2300:     my $result = qq{<input type="button" value="Revise search" name="revise"} .
                   2301:         qq{ onClick="parent.location='$newloc';" /> };
                   2302:     return $result;
                   2303: }
                   2304: 
                   2305: ######################################################################
                   2306: ######################################################################
                   2307: 
                   2308: =pod
                   2309: 
1.204     matthew  2310: =item &run_search()
                   2311: 
                   2312: Executes a search query by sending it the the other servers and putting the
                   2313: results into MySQL.
1.144     matthew  2314: 
                   2315: =cut
                   2316: 
                   2317: ######################################################################
                   2318: ######################################################################
                   2319: sub run_search {
1.146     matthew  2320:     my ($r,$query,$customquery,$customshow,$serverlist,$pretty_string) = @_;
1.196     matthew  2321:     my $bodytag=&Apache::loncommon::bodytag(undef,undef,undef,1);
1.227     matthew  2322:     $bodytag.=&Apache::lonhtmlcommon::breadcrumbs
                   2323:         (undef,'Searching','Searching',undef,undef,
                   2324:          $ENV{'form.catalogmode'} ne 'groupsearch');
1.150     matthew  2325:     my $connection = $r->connection;
1.144     matthew  2326:     #
1.146     matthew  2327:     # Print run_search header
                   2328:     #
1.151     matthew  2329:     $r->print(<<END);
                   2330: <html>
                   2331: <head><title>Search Status</title></head>
1.155     matthew  2332: $bodytag
1.151     matthew  2333: <form name="statusform" action="" method="post">
                   2334: <input type="hidden" name="Queue" value="" />
                   2335: END
1.230     matthew  2336:     # Remove leading and trailing <br />
                   2337:     $pretty_string =~ s:^\s*<br />::i;
                   2338:     $pretty_string =~ s:(<br />)*\s*$::im;
                   2339:     my @Lines = split("<br />",$pretty_string);
                   2340:     # I keep getting blank items at the end of the list, hence the following:
                   2341:     while ($Lines[-1] =~ /^\s*$/ && @Lines) {
                   2342:         pop(@Lines);
                   2343:     }
1.152     matthew  2344:     if (@Lines > 2) {
1.230     matthew  2345:         $pretty_string = join '<br />',(@Lines[0..2],'....<br />');
1.151     matthew  2346:     }
1.214     matthew  2347:     $r->print(&mt("Search: [_1]",$pretty_string));
1.146     matthew  2348:     $r->rflush();
                   2349:     #
1.145     matthew  2350:     # Determine the servers we need to contact.
1.144     matthew  2351:     my @Servers_to_contact;
                   2352:     if (defined($serverlist)) {
1.152     matthew  2353:         if (ref($serverlist) eq 'ARRAY') {
                   2354:             @Servers_to_contact = @$serverlist;
                   2355:         } else {
                   2356:             @Servers_to_contact = ($serverlist);
                   2357:         }
1.144     matthew  2358:     } else {
                   2359:         @Servers_to_contact = sort(keys(%Apache::lonnet::libserv));
                   2360:     }
                   2361:     my %Server_status;
1.214     matthew  2362:     #
                   2363:     # Check on the mysql table we will use to store results.
1.146     matthew  2364:     my $table =$ENV{'form.table'};
1.150     matthew  2365:     if (! defined($table) || $table eq '' || $table =~ /\D/ ) {
1.147     matthew  2366:         $r->print("Unable to determine table id to store search results in.".
1.148     matthew  2367:                   "The search has been aborted.</body></html>");
1.147     matthew  2368:         return;
                   2369:     }
                   2370:     my $table_status = &Apache::lonmysql::check_table($table);
                   2371:     if (! defined($table_status)) {
                   2372:         $r->print("Unable to determine status of table.</body></html>");
                   2373:         &Apache::lonnet::logthis("Bogus table id of $table for ".
                   2374:                                  "$ENV{'user.name'} @ $ENV{'user.domain'}");
                   2375:         &Apache::lonnet::logthis("lonmysql error = ".
1.144     matthew  2376:                                  &Apache::lonmysql::get_error());
1.147     matthew  2377:         return;
                   2378:     }
                   2379:     if (! $table_status) {
1.204     matthew  2380:         &Apache::lonnet::logthis("lonmysql error = ".
                   2381:                                  &Apache::lonmysql::get_error());
                   2382:         &Apache::lonnet::logthis("lonmysql debug = ".
                   2383:                                  &Apache::lonmysql::get_debug());
                   2384:         &Apache::lonnet::logthis('table status = "'.$table_status.'"');
1.147     matthew  2385:         $r->print("The table id,$table, we tried to use is invalid.".
1.148     matthew  2386:                   "The search has been aborted.</body></html>");
1.144     matthew  2387:         return;
                   2388:     }
1.145     matthew  2389:     ##
1.146     matthew  2390:     ## Prepare for the big loop.
1.144     matthew  2391:     my $hitcountsum;
                   2392:     my $server; 
                   2393:     my $status;
1.151     matthew  2394:     my $revise = &revise_button();
1.148     matthew  2395:     $r->print(<<END);
                   2396: <table>
1.151     matthew  2397: <tr><th>Status</th><th>Total Matches</th><th>Time Remaining</th><th></th></tr>
1.148     matthew  2398: <tr>
1.150     matthew  2399: <td><input type="text" name="status"  value="" size="30" /></td>
                   2400: <td><input type="text" name="count"   value="" size="10" /></td>
                   2401: <td><input type="text" name="seconds" value="" size="8" /></td>
1.151     matthew  2402: <td>$revise</td>
1.148     matthew  2403: </tr>
                   2404: </table>
                   2405: </form>
                   2406: END
                   2407:     $r->rflush();
1.214     matthew  2408:     &reset_timing();
                   2409:     &update_seconds($r);
                   2410:     &update_status($r,&mt('contacting [_1]',$Servers_to_contact[0]));
                   2411:     while (&time_left() &&
1.144     matthew  2412:            ((@Servers_to_contact) || keys(%Server_status))) {
1.214     matthew  2413:         &update_seconds($r);
                   2414:         #
                   2415:         # Send out a search request
1.144     matthew  2416:         if (@Servers_to_contact) {
                   2417:             # Contact one server
                   2418:             my $server = shift(@Servers_to_contact);
1.214     matthew  2419:             &update_status($r,&mt('contacting [_1]',$server));
1.144     matthew  2420:             my $reply=&Apache::lonnet::metadata_query($query,$customquery,
                   2421:                                                       $customshow,[$server]);
                   2422:             ($server) = keys(%$reply);
                   2423:             $Server_status{$server} = $reply->{$server};
                   2424:         } else {
1.150     matthew  2425:             # wait a sec. to give time for files to be written
                   2426:             # This sleep statement is here instead of outside the else 
                   2427:             # block because we do not want to pause if we have servers
                   2428:             # left to contact.  
1.183     matthew  2429:             if (scalar (keys(%Server_status))) {
                   2430:                 &update_status($r,
1.214     matthew  2431:                        &mt('waiting on [_1]',join(' ',keys(%Server_status))));
1.183     matthew  2432:             }
1.150     matthew  2433:             sleep(1)1.144     matthew  2434:         }
1.159     matthew  2435:         #
                   2436:         # Loop through the servers we have contacted but do not
                   2437:         # have results from yet, looking for results.
1.228     matthew  2438:         foreach my $server (keys(%Server_status)) {
1.150     matthew  2439:             last if ($connection->aborted());
1.214     matthew  2440:             &update_seconds($r);
1.228     matthew  2441:             my $status = $Server_status{$server};
1.144     matthew  2442:             if ($status eq 'con_lost') {
                   2443:                 delete ($Server_status{$server});
                   2444:                 next;
                   2445:             }
                   2446:             $status=~/^([\.\w]+)$/; 
                   2447:        	    my $datafile=$r->dir_config('lonDaemons').'/tmp/'.$1;
                   2448:             if (-e $datafile && ! -e "$datafile.end") {
1.214     matthew  2449:                 &update_status($r,&mt('Receiving results from [_1]',$server));
1.144     matthew  2450:                 next;
                   2451:             }
1.150     matthew  2452:             last if ($connection->aborted());
1.144     matthew  2453:             if (-e "$datafile.end") {
1.214     matthew  2454:                 &update_status($r,&mt('Reading results from [_1]',$server));
1.144     matthew  2455:                 if (-z "$datafile") {
                   2456:                     delete($Server_status{$server});
                   2457:                     next;
                   2458:                 }
                   2459:                 my $fh;
                   2460:                 if (!($fh=Apache::File->new($datafile))) { 
1.146     matthew  2461:                     $r->print("Unable to open search results file for ".
1.145     matthew  2462:                                   "server $server.  Omitting from search");
1.150     matthew  2463:                     delete($Server_status{$server}); 
                   2464:                    next;
1.144     matthew  2465:                 }
                   2466:                 # Read in the whole file.
                   2467:                 while (my $result = <$fh>) {
1.150     matthew  2468:                     last if ($connection->aborted());
1.214     matthew  2469:                     #
                   2470:                     # Records are stored one per line
1.144     matthew  2471:                     chomp($result);
1.214     matthew  2472:                     next if (! $result);
                   2473:                     #
1.144     matthew  2474:                     # Parse the result.
                   2475:                     my %Fields = &parse_raw_result($result,$server);
                   2476:                     $Fields{'hostname'} = $server;
1.214     matthew  2477:                     #
                   2478:                     # Skip based on copyright
1.144     matthew  2479:                     next if (! &copyright_check(\%Fields));
1.214     matthew  2480:                     #
1.144     matthew  2481:                     # Store the result in the mysql database
                   2482:                     my $result = &Apache::lonmysql::store_row($table,\%Fields);
                   2483:                     if (! defined($result)) {
1.146     matthew  2484:                         $r->print(&Apache::lonmysql::get_error());
1.144     matthew  2485:                     }
1.214     matthew  2486:                     #
1.144     matthew  2487:                     $hitcountsum ++;
1.214     matthew  2488:                     &update_seconds($r);
1.150     matthew  2489:                     if ($hitcountsum % 50 == 0) {
                   2490:                         &update_count_status($r,$hitcountsum);
                   2491:                     }
1.214     matthew  2492:                 }
1.144     matthew  2493:                 $fh->close();
                   2494:                 # $server is only deleted if the results file has been 
                   2495:                 # found and (successfully) opened.  This may be a bad idea.
                   2496:                 delete($Server_status{$server});
                   2497:             }
1.150     matthew  2498:             last if ($connection->aborted());
1.148     matthew  2499:             &update_count_status($r,$hitcountsum);
1.144     matthew  2500:         }
1.150     matthew  2501:         last if ($connection->aborted());
1.214     matthew  2502:         &update_seconds($r);
1.144     matthew  2503:     }
1.214     matthew  2504:     &update_status($r,&mt('Search Complete [_1]',$server));
                   2505:     &update_seconds($r);
1.204     matthew  2506:     #
1.214     matthew  2507:     &Apache::lonmysql::disconnect_from_db(); # This is unneccessary
1.204     matthew  2508:     #
1.144     matthew  2509:     # We have run out of time or run out of servers to talk to and
1.214     matthew  2510:     # results to get, so let the client know the top frame needs to be
                   2511:     # loaded from /adm/searchcat
1.146     matthew  2512:     $r->print("</body></html>");
1.224     matthew  2513: #    if ($ENV{'form.catalogmode'} ne 'groupsearch') {
1.153     matthew  2514:         $r->print("<script>".
                   2515:                       "window.location='/adm/searchcat?".
                   2516:                       "phase=sort&".
                   2517:                       "persistent_db_id=$ENV{'form.persistent_db_id'}';".
                   2518:                   "</script>");
1.224     matthew  2519: #    }
1.144     matthew  2520:     return;
                   2521: }
                   2522: 
                   2523: ######################################################################
                   2524: ######################################################################
1.204     matthew  2525: 
1.144     matthew  2526: =pod
                   2527: 
1.204     matthew  2528: =item &prev_next_buttons()
                   2529: 
                   2530: Returns html for the previous and next buttons on the search results page.
1.144     matthew  2531: 
                   2532: =cut
                   2533: 
                   2534: ######################################################################
                   2535: ######################################################################
1.146     matthew  2536: sub prev_next_buttons {
1.145     matthew  2537:     my ($current_min,$show,$total,$parms) = @_;
                   2538:     return '' if ($show eq 'all'); # No links if you get them all at once.
1.214     matthew  2539:     #
1.223     matthew  2540:     # Create buttons
                   2541:     my $buttons = '<input type="submit" name="prev" value="'.&mt('Prev').'" ';
                   2542:     $buttons .= '/>';
                   2543:     $buttons .= '&nbsp;'x3;
                   2544:     $buttons .= '<input type="submit" name="reload" '.
                   2545:         'value="'.&mt('Reload').'" />';
                   2546:     $buttons .= '&nbsp;'x3;
                   2547:     $buttons .= '<input type="submit" name="next" value="'.&mt('Next').'" ';
                   2548:     $buttons .= '/>';
                   2549:     return $buttons;
1.144     matthew  2550: }
1.204     matthew  2551: 
1.144     matthew  2552: ######################################################################
                   2553: ######################################################################
                   2554: 
                   2555: =pod
                   2556: 
1.204     matthew  2557: =item &display_results()
                   2558: 
                   2559: Prints the results out for selection and perusal.
1.144     matthew  2560: 
                   2561: =cut
                   2562: 
                   2563: ######################################################################
                   2564: ######################################################################
                   2565: sub display_results {
1.196     matthew  2566:     my ($r,$importbutton,$closebutton,$diropendb) = @_;
1.150     matthew  2567:     my $connection = $r->connection;
                   2568:     $r->print(&search_results_header($importbutton,$closebutton));
1.144     matthew  2569:     ##
                   2570:     ## Set viewing function
                   2571:     ##
                   2572:     my $viewfunction = $Views{$ENV{'form.viewselect'}};
                   2573:     if (!defined($viewfunction)) {
                   2574:         $r->print("Internal Error - Bad view selected.\n");
                   2575:         $r->rflush();
                   2576:         return;
                   2577:     }
                   2578:     ##
1.158     matthew  2579:     ## $checkbox_num is a count of the number of checkboxes output on the 
                   2580:     ## page this is used only during catalogmode=groupsearch.
                   2581:     my $checkbox_num = 0;
                   2582:     ##
1.144     matthew  2583:     ## Get the catalog controls setup
                   2584:     ##
1.146     matthew  2585:     my $action = "/adm/searchcat?phase=results";
                   2586:     ##
1.204     matthew  2587:     ## Deal with groupsearch by opening the groupsearch db file.
1.146     matthew  2588:     if ($ENV{'form.catalogmode'} eq 'groupsearch') {
                   2589:         if (! tie(%groupsearch_db,'GDBM_File',$diropendb,
1.148     matthew  2590:                   &GDBM_WRCREAT(),0640)) {
1.150     matthew  2591:             $r->print('Unable to store import results.</form></body></html>');
1.146     matthew  2592:             $r->rflush();
                   2593:             return;
                   2594:         } 
1.144     matthew  2595:     }
1.145     matthew  2596:     ##
                   2597:     ## Prepare the table for querying
1.144     matthew  2598:     my $table = $ENV{'form.table'};
1.151     matthew  2599:     return if (! &ensure_db_and_table($r,$table));
1.145     matthew  2600:     ##
                   2601:     ## Get the number of results 
                   2602:     my $total_results = &Apache::lonmysql::number_of_rows($table);
                   2603:     if (! defined($total_results)) {
1.150     matthew  2604:         $r->print("A MySQL error has occurred.</form></body></html>");
1.145     matthew  2605:         &Apache::lonnet::logthis("lonmysql was unable to determine the number".
                   2606:                                  " of rows in table ".$table);
                   2607:         &Apache::lonnet::logthis(&Apache::lonmysql::get_error());
                   2608:         return;
                   2609:     }
                   2610:     ##
                   2611:     ## Determine how many results we need to get
1.223     matthew  2612:     $ENV{'form.start'} = 1  if (! exists($ENV{'form.start'}));
                   2613:     $ENV{'form.show'}  = 20 if (! exists($ENV{'form.show'}));
                   2614:     if (exists($ENV{'form.prev'})) {
                   2615:         $ENV{'form.start'} -= $ENV{'form.show'};
                   2616:     } elsif (exists($ENV{'form.next'})) {
                   2617:         $ENV{'form.start'} += $ENV{'form.show'};
                   2618:     }
                   2619:     $ENV{'form.start'} = 1 if ($ENV{'form.start'}<1);
                   2620:     $ENV{'form.start'} = $total_results if ($ENV{'form.start'}>$total_results);
1.146     matthew  2621:     my $min = $ENV{'form.start'};
1.145     matthew  2622:     my $max;
                   2623:     if ($ENV{'form.show'} eq 'all') {
                   2624:         $max = $total_results ;
                   2625:     } else {
1.151     matthew  2626:         $max = $min + $ENV{'form.show'} - 1;
1.146     matthew  2627:         $max = $total_results if ($max > $total_results);
1.145     matthew  2628:     }
                   2629:     ##
1.223     matthew  2630:     ## Output form elements
                   2631:     $r->print(&hidden_field('table').
                   2632:               &hidden_field('phase').
                   2633:               &hidden_field('persistent_db_id').
                   2634:               &hidden_field('start')
                   2635:               );
                   2636:     ##
1.145     matthew  2637:     ## Output links (if necessary) for 'prev' and 'next' pages.
1.146     matthew  2638:     $r->print
1.223     matthew  2639:         ('<table width="100%"><tr><td width="50%" align="right">'.
                   2640:          &prev_next_buttons($min,$ENV{'form.show'},$total_results).
                   2641:          '</td><td align="right">'.
                   2642:          &viewoptions().'</td></tr></table>'
1.146     matthew  2643:          );
1.150     matthew  2644:     if ($total_results == 0) {
1.214     matthew  2645:         $r->print('<meta HTTP-EQUIV="Refresh" CONTENT="2">'.
1.187     www      2646:                   '<h3>'.&mt('There are currently no results').'.</h3>'.
1.150     matthew  2647:                   "</form></body></html>");
                   2648:         return;
                   2649:     } else {
                   2650:         $r->print
                   2651:             ("<center>Results $min to $max out of $total_results</center>\n");
                   2652:     }
1.145     matthew  2653:     ##
                   2654:     ## Get results from MySQL table
                   2655:     my @Results = &Apache::lonmysql::get_rows($table,
1.151     matthew  2656:                                               'id>='.$min.' AND id<='.$max);
1.145     matthew  2657:     ##
                   2658:     ## Loop through the results and output them.
1.144     matthew  2659:     foreach my $row (@Results) {
1.150     matthew  2660:         if ($connection->aborted()) {
1.162     www      2661:             &cleanup();
1.150     matthew  2662:             return;
                   2663:         }
1.144     matthew  2664:         my %Fields = %{&parse_row(@$row)};
1.145     matthew  2665:         my $output="<p>\n";
1.210     matthew  2666:         if (! defined($Fields{'title'}) || $Fields{'title'} eq '') {
                   2667:             $Fields{'title'} = 'Untitled';
                   2668:         }
1.158     matthew  2669:         my $prefix=&catalogmode_output($Fields{'title'},$Fields{'url'},
                   2670:                                        $Fields{'id'},$checkbox_num++);
1.144     matthew  2671:         # Render the result into html
1.150     matthew  2672:         $output.= &$viewfunction($prefix,%Fields);
1.145     matthew  2673:         # Print them out as they come in.
1.144     matthew  2674:         $r->print($output);
                   2675:         $r->rflush();
                   2676:     }
                   2677:     if (@Results < 1) {
1.187     www      2678:         $r->print(&mt("There were no results matching your query"));
1.147     matthew  2679:     } else {
                   2680:         $r->print
1.148     matthew  2681:             ('<center>'.
1.147     matthew  2682:              &prev_next_buttons($min,$ENV{'form.show'},$total_results,
                   2683:                                 "table=".$ENV{'form.table'}.
                   2684:                                 "&phase=results".
                   2685:                                 "&persistent_db_id=".
                   2686:                                 $ENV{'form.persistent_db_id'})
1.148     matthew  2687:              ."</center>\n"
1.147     matthew  2688:              );
1.144     matthew  2689:     }
1.150     matthew  2690:     $r->print("</form></body></html>");
1.144     matthew  2691:     $r->rflush();
1.150     matthew  2692:     untie %groupsearch_db if (tied(%groupsearch_db));
1.144     matthew  2693:     return;
                   2694: }
                   2695: 
                   2696: ######################################################################
                   2697: ######################################################################
                   2698: 
                   2699: =pod
                   2700: 
1.158     matthew  2701: =item &catalogmode_output($title,$url,$fnum,$checkbox_num)
1.145     matthew  2702: 
                   2703: Returns html needed for the various catalog modes.  Gets inputs from
1.158     matthew  2704: $ENV{'form.catalogmode'}.  Stores data in %groupsearch_db.
1.145     matthew  2705: 
                   2706: =cut
                   2707: 
                   2708: ######################################################################
                   2709: ######################################################################
                   2710: sub catalogmode_output {
                   2711:     my $output = '';
1.158     matthew  2712:     my ($title,$url,$fnum,$checkbox_num) = @_;
1.145     matthew  2713:     if ($ENV{'form.catalogmode'} eq 'interactive') {
1.150     matthew  2714:         $title=~ s/\'/\\\'/g;
1.145     matthew  2715:         if ($ENV{'form.catalogmode'} eq 'interactive') {
                   2716:             $output.=<<END 
                   2717: <font size='-1'><INPUT TYPE="button" NAME="returnvalues" VALUE="SELECT"
                   2718: onClick="javascript:select_data('$title','$url')">
                   2719: </font>
                   2720: END
                   2721:         }
1.150     matthew  2722:     } elsif ($ENV{'form.catalogmode'} eq 'groupsearch') {
1.145     matthew  2723:         $groupsearch_db{"pre_${fnum}_link"}=$url;
                   2724:         $groupsearch_db{"pre_${fnum}_title"}=$title;
                   2725:         $output.=<<END;
                   2726: <font size='-1'>
                   2727: <input type="checkbox" name="returnvalues" value="SELECT"
1.158     matthew  2728: onClick="javascript:queue($checkbox_num,$fnum)" />
1.145     matthew  2729: </font>
                   2730: END
                   2731:     }
                   2732:     return $output;
                   2733: }
                   2734: ######################################################################
                   2735: ######################################################################
                   2736: 
                   2737: =pod
                   2738: 
1.204     matthew  2739: =item &parse_row()
1.144     matthew  2740: 
                   2741: Parse a row returned from the database.
                   2742: 
                   2743: =cut
                   2744: 
                   2745: ######################################################################
                   2746: ######################################################################
                   2747: sub parse_row {
                   2748:     my @Row = @_;
                   2749:     my %Fields;
1.204     matthew  2750:     if (! scalar(@Datatypes)) {
                   2751:         &set_up_table_structure();
                   2752:     }
1.144     matthew  2753:     for (my $i=0;$i<=$#Row;$i++) {
1.170     matthew  2754:         $Fields{$Datatypes[$i]->{'name'}}=&Apache::lonnet::unescape($Row[$i]);
1.144     matthew  2755:     }
                   2756:     $Fields{'language'} = 
1.198     www      2757:         &Apache::loncommon::languagedescription($Fields{'language'});
1.144     matthew  2758:     $Fields{'copyrighttag'} =
                   2759:         &Apache::loncommon::copyrightdescription($Fields{'copyright'});
                   2760:     $Fields{'mimetag'} =
                   2761:         &Apache::loncommon::filedescription($Fields{'mime'});
                   2762:     return \%Fields;
                   2763: }
1.126     matthew  2764: 
                   2765: ###########################################################
                   2766: ###########################################################
                   2767: 
                   2768: =pod
                   2769: 
                   2770: =item &parse_raw_result()
                   2771: 
                   2772: Takes a line from the file of results and parse it.  Returns a hash 
1.198     www      2773: with keys according to column labels
1.126     matthew  2774: 
                   2775: In addition, the following tags are set by calling the appropriate 
1.198     www      2776: lonnet function: 'language', 'copyrighttag', 'mimetag'.
1.126     matthew  2777: 
                   2778: The 'title' field is set to "Untitled" if the title field is blank.
                   2779: 
                   2780: 'abstract' and 'keywords' are truncated to 200 characters.
                   2781: 
                   2782: =cut
                   2783: 
                   2784: ###########################################################
                   2785: ###########################################################
                   2786: sub parse_raw_result {
                   2787:     my ($result,$hostname) = @_;
1.204     matthew  2788:     # conclude from self to others regarding fields
1.206     matthew  2789:     my %Fields=&LONCAPA::lonmetadata::metadata_col_to_hash
                   2790:         (map {
                   2791:             &Apache::lonnet::unescape($_);
                   2792:         } (split(/\,/,$result)) );
1.126     matthew  2793:     return %Fields;
                   2794: }
                   2795: 
                   2796: ###########################################################
                   2797: ###########################################################
                   2798: 
                   2799: =pod
                   2800: 
                   2801: =item &handle_custom_fields()
                   2802: 
                   2803: =cut
                   2804: 
                   2805: ###########################################################
                   2806: ###########################################################
                   2807: sub handle_custom_fields {
                   2808:     my @results = @{shift()};
                   2809:     my $customshow='';
                   2810:     my $extrashow='';
                   2811:     my @customfields;
                   2812:     if ($ENV{'form.customshow'}) {
                   2813:         $customshow=$ENV{'form.customshow'};
                   2814:         $customshow=~s/[^\w\s]//g;
                   2815:         my @fields=map {
                   2816:             "<font color=\"#008000\">$_:</font><!-- $_ -->";
                   2817:         } split(/\s+/,$customshow);
                   2818:         @customfields=split(/\s+/,$customshow);
                   2819:         if ($customshow) {
                   2820:             $extrashow="<ul><li>".join("</li><li>",@fields)."</li></ul>\n";
                   2821:         }
                   2822:     }
                   2823:     my $customdata='';
                   2824:     my %customhash;
                   2825:     foreach my $result (@results) {
                   2826:         if ($result=~/^(custom\=.*)$/) { # grab all custom metadata
                   2827:             my $tmp=$result;
                   2828:             $tmp=~s/^custom\=//;
                   2829:             my ($k,$v)=map {&Apache::lonnet::unescape($_);
                   2830:                         } split(/\,/,$tmp);
                   2831:             $customhash{$k}=$v;
                   2832:         }
                   2833:     }
                   2834:     return ($extrashow,\@customfields,\%customhash);
1.41      harris41 2835: }
                   2836: 
1.122     matthew  2837: ######################################################################
                   2838: ######################################################################
                   2839: 
1.125     matthew  2840: =pod
                   2841: 
1.204     matthew  2842: =item &search_results_header()
1.125     matthew  2843: 
1.130     matthew  2844: Output the proper html headers and javascript code to deal with different 
                   2845: calling modes.
                   2846: 
                   2847: Takes most inputs directly from %ENV, except $mode.  
                   2848: 
                   2849: =over 4
                   2850: 
                   2851: =item $mode is either (at this writing) 'Basic' or 'Advanced'
                   2852: 
                   2853: =back
1.126     matthew  2854: 
1.130     matthew  2855: The following environment variables are checked:
1.126     matthew  2856: 
                   2857: =over 4
                   2858: 
                   2859: =item 'form.catalogmode' 
                   2860: 
                   2861: Checked for 'interactive' and 'groupsearch'.
                   2862: 
                   2863: =item 'form.mode'
                   2864: 
                   2865: Checked for existance & 'edit' mode.
                   2866: 
                   2867: =item 'form.form'
                   2868: 
1.191     albertel 2869: Contains the name of the form that has the input fields to set
                   2870: 
1.126     matthew  2871: =item 'form.element'
                   2872: 
1.191     albertel 2873: the name of the input field to put the URL into
                   2874: 
                   2875: =item 'form.titleelement'
                   2876: 
                   2877: the name of the input field to put the title into
                   2878: 
1.126     matthew  2879: =back
                   2880: 
1.125     matthew  2881: =cut
                   2882: 
                   2883: ######################################################################
                   2884: ######################################################################
                   2885: sub search_results_header {
1.150     matthew  2886:     my ($importbutton,$closebutton) = @_;
1.196     matthew  2887:     my $bodytag=&Apache::loncommon::bodytag(undef,undef,undef,1);
1.125     matthew  2888:     my $result = '';
                   2889:     # output beginning of search page
                   2890:     # conditional output of script functions dependent on the mode in
                   2891:     # which the search was invoked
                   2892:     if ($ENV{'form.catalogmode'} eq 'interactive'){
                   2893: 	if (! exists($ENV{'form.mode'}) || $ENV{'form.mode'} ne 'edit') {
                   2894:             $result.=<<SCRIPT;
                   2895: <script type="text/javascript">
                   2896:     function select_data(title,url) {
                   2897: 	changeTitle(title);
                   2898: 	changeURL(url);
1.150     matthew  2899: 	parent.close();
1.125     matthew  2900:     }
                   2901:     function changeTitle(val) {
1.153     matthew  2902: 	if (parent.opener.inf.document.forms.resinfo.elements.t) {
                   2903: 	    parent.opener.inf.document.forms.resinfo.elements.t.value=val;
1.125     matthew  2904: 	}
                   2905:     }
                   2906:     function changeURL(val) {
1.153     matthew  2907: 	if (parent.opener.inf.document.forms.resinfo.elements.u) {
                   2908: 	    parent.opener.inf.document.forms.resinfo.elements.u.value=val;
1.125     matthew  2909: 	}
                   2910:     }
                   2911: </script>
                   2912: SCRIPT
                   2913:         } elsif ($ENV{'form.mode'} eq 'edit') {
                   2914:             my $form = $ENV{'form.form'};
                   2915:             my $element = $ENV{'form.element'};
1.191     albertel 2916:             my $titleelement = $ENV{'form.titleelement'};
                   2917: 	    my $changetitle;
                   2918: 	    if (!$titleelement) {
                   2919: 		$changetitle='function changeTitle(val) {}';
                   2920: 	    } else {
                   2921: 		    $changetitle=<<END;
                   2922: function changeTitle(val) {
                   2923:     if (parent.targetwin.document) {
                   2924:         parent.targetwin.document.forms["$form"].elements["$titleelement"].value=val;
                   2925:     } else {
                   2926: 	var url = 'forms[\"$form\"].elements[\"$titleelement\"].value';
                   2927:         alert("Unable to transfer data to "+url);
                   2928:     }
                   2929: }
                   2930: END
                   2931:             }
                   2932: 
1.125     matthew  2933:             $result.=<<SCRIPT;
                   2934: <script type="text/javascript">
                   2935: function select_data(title,url) {
                   2936:     changeURL(url);
1.191     albertel 2937:     changeTitle(title);
1.150     matthew  2938:     parent.close();
1.125     matthew  2939: }
1.191     albertel 2940: $changetitle
1.125     matthew  2941: function changeURL(val) {
1.150     matthew  2942:     if (parent.targetwin.document) {
                   2943:         parent.targetwin.document.forms["$form"].elements["$element"].value=val;
1.125     matthew  2944:     } else {
                   2945: 	var url = 'forms[\"$form\"].elements[\"$element\"].value';
                   2946:         alert("Unable to transfer data to "+url);
                   2947:     }
                   2948: }
                   2949: </script>
                   2950: SCRIPT
                   2951:         }
                   2952:     }
                   2953:     $result.=<<SCRIPT if $ENV{'form.catalogmode'} eq 'groupsearch';
                   2954: <script type="text/javascript">
1.158     matthew  2955:     function queue(checkbox_num,val) {
1.185     matthew  2956:         if (document.forms.results.returnvalues.length != "undefined" &&
                   2957:             typeof(document.forms.results.returnvalues.length) == "number") {
                   2958:             if (document.forms.results.returnvalues[checkbox_num].checked) {
                   2959:                 parent.statusframe.document.forms.statusform.elements.Queue.value +='1a'+val+'b';
                   2960:             } else {
                   2961:                 parent.statusframe.document.forms.statusform.elements.Queue.value +='0a'+val+'b';
                   2962:             }
1.150     matthew  2963:         } else {
1.185     matthew  2964:             if (document.forms.results.returnvalues.checked) {
                   2965:                 parent.statusframe.document.forms.statusform.elements.Queue.value +='1a'+val+'b';
                   2966:             } else {
                   2967:                 parent.statusframe.document.forms.statusform.elements.Queue.value +='0a'+val+'b';
                   2968:             }
1.150     matthew  2969:         }
1.125     matthew  2970:     }
                   2971:     function select_group() {
1.150     matthew  2972: 	parent.window.location=
1.125     matthew  2973:     "/adm/groupsort?mode=$ENV{'form.mode'}&catalogmode=groupsearch&acts="+
1.150     matthew  2974: 	    parent.statusframe.document.forms.statusform.elements.Queue.value;
1.125     matthew  2975:     }
                   2976: </script>
                   2977: SCRIPT
1.130     matthew  2978:     $result.=<<END;
                   2979: </head>
1.155     matthew  2980: $bodytag
1.223     matthew  2981: <form name="results" method="post" action="/adm/searchcat" >
1.150     matthew  2982: <input type="hidden" name="Queue" value="" />
                   2983: $importbutton
1.130     matthew  2984: END
1.125     matthew  2985:     return $result;
                   2986: }
                   2987: 
                   2988: ######################################################################
                   2989: ######################################################################
1.146     matthew  2990: sub search_status_header {
1.196     matthew  2991:     my $bodytag=&Apache::loncommon::bodytag(undef,undef,undef,1);
1.146     matthew  2992:     return <<ENDSTATUS;
                   2993: <html><head><title>Search Status</title></head>
1.155     matthew  2994: $bodytag
1.146     matthew  2995: <h3>Search Status</h3>
                   2996: Sending search request to LON-CAPA servers.<br />
                   2997: ENDSTATUS
                   2998: }
                   2999: 
1.150     matthew  3000: sub results_link {
                   3001:     my $basic_link   = "/adm/searchcat?"."&table=".$ENV{'form.table'}.
                   3002:         "&persistent_db_id=".$ENV{'form.persistent_db_id'};
                   3003:     my $results_link = $basic_link."&phase=results".
1.151     matthew  3004:         "&pause=1"."&start=1";
1.150     matthew  3005:     return $results_link;
                   3006: }
                   3007: 
1.146     matthew  3008: ######################################################################
                   3009: ######################################################################
                   3010: sub print_frames_interface {
                   3011:     my $r = shift;
                   3012:     my $basic_link = "/adm/searchcat?"."&table=".$ENV{'form.table'}.
                   3013:         "&persistent_db_id=".$ENV{'form.persistent_db_id'};
                   3014:     my $run_search_link = $basic_link."&phase=run_search";
1.150     matthew  3015:     my $results_link = &results_link();
1.146     matthew  3016:     my $result = <<"ENDFRAMES";
                   3017: <html>
                   3018: <head>
1.150     matthew  3019: <script>
                   3020: var targetwin = opener;
1.158     matthew  3021: var queue = '';
1.150     matthew  3022: </script>
1.146     matthew  3023: <title>LON-CAPA Digital Library Search Results</title>
                   3024: </head>
1.176     www      3025: <frameset rows="150,*">
1.146     matthew  3026:     <frame name="statusframe"  src="$run_search_link">
                   3027:     <frame name="resultsframe" src="$results_link">
                   3028: </frameset>
                   3029: </html>
                   3030: ENDFRAMES
                   3031: 
                   3032:     $r->print($result);
                   3033:     return;
                   3034: }
                   3035: 
                   3036: ######################################################################
                   3037: ######################################################################
1.125     matthew  3038: 
1.224     matthew  3039: sub has_stat_data {
                   3040:     my ($values) = @_;
                   3041:     if ( (defined($values->{'count'})      && $values->{'count'}      ne '') ||
                   3042:          (defined($values->{'stdno'})      && $values->{'stdno'}      ne '') ||
                   3043:          (defined($values->{'disc'})       && $values->{'disc'}       ne '') ||
                   3044:          (defined($values->{'avetries'})   && $values->{'avetries'}   ne '') ||
                   3045:          (defined($values->{'difficulty'}) && $values->{'difficulty'} ne '')) {
                   3046:         return 1;
                   3047:     }
                   3048:     return 0;
                   3049: }
                   3050: 
                   3051: sub statfields {
                   3052:     return ('count','stdno','disc','avetries','difficulty');
                   3053: }
                   3054: 
                   3055: sub has_eval_data {
                   3056:     my ($values) = @_;
                   3057:     if ( (defined($values->{'clear'})     && $values->{'clear'}     ne '') ||
                   3058:          (defined($values->{'technical'}) && $values->{'technical'} ne '') ||
                   3059:          (defined($values->{'correct'})   && $values->{'correct'}   ne '') ||
                   3060:          (defined($values->{'helpful'})   && $values->{'helpful'}   ne '') ||
                   3061:          (defined($values->{'depth'})     && $values->{'depth'}     ne '')) {
                   3062:         return 1;
                   3063:     }
                   3064:     return 0;
                   3065: }
                   3066: 
                   3067: sub evalfields { 
                   3068:     return ('clear','technical','correct','helpful','depth');
                   3069: }
                   3070: 
                   3071: ######################################################################
                   3072: ######################################################################
                   3073: 
1.122     matthew  3074: =pod 
                   3075: 
                   3076: =item Metadata Viewing Functions
                   3077: 
                   3078: Output is a HTML-ified string.
1.204     matthew  3079: 
1.122     matthew  3080: Input arguments are title, author, subject, url, keywords, version,
                   3081: notes, short abstract, mime, language, creation date,
1.126     matthew  3082: last revision date, owner, copyright, hostname, and
1.122     matthew  3083: extra custom metadata to show.
                   3084: 
                   3085: =over 4
                   3086: 
                   3087: =item &detailed_citation_view() 
                   3088: 
                   3089: =cut
                   3090: 
                   3091: ######################################################################
                   3092: ######################################################################
1.50      harris41 3093: sub detailed_citation_view {
1.150     matthew  3094:     my ($prefix,%values) = @_;
1.218     matthew  3095:     my $result;
                   3096:     $result .= '<b>'.$prefix.
1.223     matthew  3097:         '<img src="'.&Apache::loncommon::icon($values{'url'}).' " />'.'&nbsp;'.
1.218     matthew  3098:         '<a href="http://'.$ENV{'HTTP_HOST'}.$values{'url'}.'" '.
                   3099:         'target="search_preview">'.$values{'title'}."</a></b>\n";
                   3100:     $result .= "<p>\n";
                   3101:     $result .= '<b>'.$values{'author'}.'</b>,'.
                   3102:         ' <i>'.$values{'owner'}.'</i><br />';
                   3103:     foreach my $field 
                   3104:         (
1.223     matthew  3105:          { name=>'url',
                   3106:            translate => '<b>URL:</b>&nbsp;[_1]',
                   3107:            special => 'url link',},
1.218     matthew  3108:          { name=>'subject',
                   3109:            translate => '<b>Subject:</b>&nbsp;[_1]',},
                   3110:          { name=>'keywords',
                   3111:            translate => '<b>Keywords:</b>&nbsp;[_1]',},
                   3112:          { name=>'notes',
                   3113:            translate => '<b>Notes:</b>&nbsp;[_1]',},
                   3114:          { name=>'mimetag',
                   3115:            translate => '<b>MIME Type:</b>&nbsp;[_1]',},
                   3116:          { name=>'standards',
                   3117:            translate => '<b>Standards:</b>[_1]',},
                   3118:          { name=>'copyrighttag',
                   3119:            translate => '<b>Copyright/Distribution:</b>&nbsp;[_1]',},
1.223     matthew  3120:          { name=>'count',
1.225     matthew  3121:            format => "%d",
1.223     matthew  3122:            translate => '<b>Access Count:</b>&nbsp;[_1]',},
1.218     matthew  3123:          { name=>'stdno',
1.225     matthew  3124:            format => "%d",
1.218     matthew  3125:            translate => '<b>Number of Students:</b>&nbsp;[_1]',},
                   3126:          { name=>'avetries',
1.225     matthew  3127:            format => "%.2f",
1.218     matthew  3128:            translate => '<b>Average Tries:</b>&nbsp;[_1]',},
                   3129:          { name=>'disc',
1.225     matthew  3130:            format => "%.2f",
1.218     matthew  3131:            translate => '<b>Degree of Discrimination:</b>&nbsp;[_1]',},
                   3132:          { name=>'difficulty',
1.225     matthew  3133:            format => "%.2f",
1.218     matthew  3134:            translate => '<b>Degree of Difficulty:</b>&nbsp;[_1]',},
                   3135:          { name=>'clear',
1.225     matthew  3136:            format => "%.2f",
1.218     matthew  3137:            translate => '<b>Clear:</b>&nbsp;[_1]',},
                   3138:          { name=>'depth',
1.225     matthew  3139:            format => "%.2f",
1.218     matthew  3140:            translate => '<b>Depth:</b>&nbsp;[_1]',},
                   3141:          { name=>'helpful',
1.225     matthew  3142:            format => "%.2f",
1.218     matthew  3143:            translate => '<b>Helpful:</b>&nbsp;[_1]',},
                   3144:          { name=>'correct',
1.225     matthew  3145:            format => "%.2f",
1.224     matthew  3146:            translate => '<b>Correct:</b>&nbsp;[_1]',},
1.218     matthew  3147:          { name=>'technical',
1.225     matthew  3148:            format => "%.2f",
1.218     matthew  3149:            translate => '<b>Technical:</b>&nbsp;[_1]',},
1.225     matthew  3150:          { name=>'comefrom_list',
                   3151:            type => 'list',
                   3152:            translate => 'Resources that lead up to this resource in maps',},
                   3153:          { name=>'goto_list',
                   3154:            type => 'list',
                   3155:            translate => 'Resources that follow this resource in maps',},
1.226     matthew  3156:          { name=>'sequsage_list',
1.225     matthew  3157:            type => 'list',
                   3158:            translate => 'Resources using or importing resource',},
1.218     matthew  3159:          ) {
1.225     matthew  3160:         next if (! exists($values{$field->{'name'}}) ||
                   3161:                  $values{$field->{'name'}} eq '');
                   3162:         if (exists($field->{'type'}) && $field->{'type'} eq 'list') {
                   3163:             $result .= '<b>'.&mt($field->{'translate'}).'</b><ul>';
                   3164:             foreach my $item (split(',',$values{$field->{'name'}})){
                   3165:                 $result .= '<li>'.
                   3166:                     '<a target="search_preview" '.
                   3167:                     'href="/res/'.$item.'">'.$item.'</a></li>';
                   3168:             }
                   3169:             $result .= '</ul>';
                   3170:         } elsif (exists($field->{'format'}) && $field->{'format'} ne ''){
                   3171:             $result.= &mt($field->{'translate'},
                   3172:                           sprintf($field->{'format'},
1.230     matthew  3173:                                   $values{$field->{'name'}}))."<br />\n";
1.225     matthew  3174:         } else {
1.223     matthew  3175:             if ($field->{'special'} eq 'url link') {
                   3176:                 $result.= 
1.225     matthew  3177:                      &mt($field->{'translate'},
                   3178:                          '<a href="'.$values{'url'}.'" '.
                   3179:                          'target="search_preview">'.
                   3180:                          $values{$field->{'name'}}.
                   3181:                          '</a>');
1.223     matthew  3182:             } else {
                   3183:                 $result.= &mt($field->{'translate'},
                   3184:                               $values{$field->{'name'}});
                   3185:             }
                   3186:             $result .= "<br />\n";
1.225     matthew  3187:         }
1.223     matthew  3188:     }
                   3189:     $result .= "</p>";
                   3190:     if (exists($values{'extrashow'}) && $values{'extrashow'} ne '') {
                   3191:         $result .= '<p>'.$values{'extrashow'}.'</p>';
                   3192:     }
                   3193:     if (exists($values{'shortabstract'}) && $values{'shortabstract'} ne '') {
                   3194:         $result .= '<p>'.$values{'shortabstract'}.'</p>';
1.218     matthew  3195:     }
                   3196:     $result .= '<hr align="left" width="200" noshade />'."\n";
1.50      harris41 3197:     return $result;
1.222     matthew  3198: }
                   3199: 
                   3200: ######################################################################
                   3201: ######################################################################
                   3202: 
1.122     matthew  3203: =pod 
                   3204: 
                   3205: =item &summary_view() 
                   3206: 
                   3207: =cut
                   3208: ######################################################################
                   3209: ######################################################################
1.50      harris41 3210: sub summary_view {
1.150     matthew  3211:     my ($prefix,%values) = @_;
1.192     albertel 3212:     my $icon=&Apache::loncommon::icon($values{'url'});
1.50      harris41 3213:     my $result=<<END;
1.223     matthew  3214: $prefix<img src="$icon" />&nbsp;
                   3215: <a href="http://$ENV{'HTTP_HOST'}$values{'url'}" 
1.126     matthew  3216:    target='search_preview'>$values{'author'}</a><br />
                   3217: $values{'title'}<br />
                   3218: $values{'owner'} -- $values{'lastrevisiondate'}<br />
                   3219: $values{'copyrighttag'}<br />
                   3220: $values{'extrashow'}
1.50      harris41 3221: </p>
1.150     matthew  3222: <hr align='left' width='200' noshade />
1.50      harris41 3223: END
                   3224:     return $result;
                   3225: }
                   3226: 
1.122     matthew  3227: ######################################################################
                   3228: ######################################################################
                   3229: 
                   3230: =pod 
                   3231: 
1.150     matthew  3232: =item &compact_view() 
                   3233: 
                   3234: =cut
                   3235: 
                   3236: ######################################################################
                   3237: ######################################################################
                   3238: sub compact_view {
                   3239:     my ($prefix,%values) = @_;
1.223     matthew  3240:     my $result = 
                   3241:         $prefix.'<img src="'.&Apache::loncommon::icon($values{'url'}).
                   3242:         '">&nbsp;<a href="'.$values{'url'}.'" target="search_preview">'.
                   3243:         $values{'title'}.'</a>'.('&nbsp;'x2).
                   3244:         '<b>'.$values{'author'}.'</b><br />';
1.150     matthew  3245:     return $result;
                   3246: }
                   3247: 
                   3248: 
                   3249: ######################################################################
                   3250: ######################################################################
                   3251: 
                   3252: =pod 
                   3253: 
1.122     matthew  3254: =item &fielded_format_view() 
                   3255: 
                   3256: =cut
                   3257: 
                   3258: ######################################################################
                   3259: ######################################################################
1.50      harris41 3260: sub fielded_format_view {
1.150     matthew  3261:     my ($prefix,%values) = @_;
1.192     albertel 3262:     my $icon=&Apache::loncommon::icon($values{'url'});
1.222     matthew  3263:     my %Translated = &Apache::lonmeta::fieldnames();
1.50      harris41 3264:     my $result=<<END;
1.192     albertel 3265: $prefix <img src="$icon" />
1.222     matthew  3266: <dl>
                   3267: <dt>URL:</dt>
                   3268:     <dd><a href="http://$ENV{'HTTP_HOST'}$values{'url'}" 
                   3269:          target='search_preview'>$values{'url'}</a></dd>
1.50      harris41 3270: END
1.222     matthew  3271:     foreach my $field ('title','author','subject','keywords','notes',
                   3272:                        'mimetag','language','creationdate','lastrevisiondate',
                   3273:                        'owner','copyrighttag','hostname','abstract') {
                   3274:         $result .= (' 'x4).'<dt>'.$Translated{$field}.'</dt>'."\n".
                   3275:             (' 'x8).'<dd>'.$values{$field}.'</dd>'."\n";
                   3276:     }
                   3277:     if (&has_stat_data(\%values)) {
                   3278:         foreach my $field (&statfields()) {
                   3279:             $result .= (' 'x4).'<dt>'.$Translated{$field}.'</dt>'."\n".
                   3280:                 (' 'x8).'<dd>'.$values{$field}.'</dd>'."\n";
                   3281:         }
                   3282:     }
                   3283:     if (&has_eval_data(\%values)) {
                   3284:         foreach my $field (&evalfields()) {
                   3285:             $result .= (' 'x4).'<dt>'.$Translated{$field}.'</dt>'."\n".
                   3286:                 (' 'x8).'<dd>'.$values{$field}.'</dd>'."\n";
                   3287:         }
                   3288:     }
                   3289:     $result .= "</dl>\n";
                   3290:     $result .= $values{'extrashow'};
                   3291:     $result .= '<hr align="left" width="200" noshade />'."\n";
1.50      harris41 3292:     return $result;
                   3293: }
                   3294: 
1.122     matthew  3295: ######################################################################
                   3296: ######################################################################
                   3297: 
                   3298: =pod 
                   3299: 
                   3300: =item &xml_sgml_view() 
                   3301: 
                   3302: =back 
                   3303: 
                   3304: =cut
                   3305: 
                   3306: ######################################################################
                   3307: ######################################################################
1.50      harris41 3308: sub xml_sgml_view {
1.150     matthew  3309:     my ($prefix,%values) = @_;
1.222     matthew  3310:     my $xml = '<LonCapaResource>'."\n";
                   3311:     # The usual suspects
                   3312:     foreach my $field ('url','title','author','subject','keywords','notes') {
                   3313:         $xml .= qq{<$field>$values{$field}</$field>}."\n";
                   3314:     }
                   3315:     #
                   3316:     $xml .= "<mimeInfo>\n";
                   3317:     foreach my $field ('mime','mimetag') {
                   3318:         $xml .= qq{<$field>$values{$field}</$field>}."\n";
                   3319:     }
                   3320:     $xml .= "</mimeInfo>\n";
                   3321:     #
                   3322:     $xml .= "<languageInfo>\n";
                   3323:     foreach my $field ('language','languagetag') {
                   3324:         $xml .= qq{<$field>$values{$field}</$field>}."\n";
                   3325:     }
                   3326:     $xml .= "</languageInfo>\n";
                   3327:     #
                   3328:     foreach my $field ('creationdate','lastrevisiondate','owner') {
                   3329:         $xml .= qq{<$field>$values{$field}</$field>}."\n";
                   3330:     }
                   3331:     #
                   3332:     $xml .= "<copyrightInfo>\n";
                   3333:     foreach my $field ('copyright','copyrighttag') {
                   3334:         $xml .= qq{<$field>$values{$field}</$field>}."\n";
                   3335:     }
                   3336:     $xml .= "</copyrightInfo>\n";
                   3337:     $xml .= qq{<repositoryLocation>$values{'hostname'}</repositoryLocation>}.
                   3338:         "\n";
                   3339:     $xml .= qq{<shortabstract>$values{'shortabstract'}</shortabstract>}."\n";
                   3340:     #
                   3341:     if (&has_stat_data(\%values)){
                   3342:         $xml .= "<problemstatistics>\n";
                   3343:         foreach my $field (&statfields()) {
                   3344:             $xml .= qq{<$field>$values{$field}</$field>}."\n";            
                   3345:         }
                   3346:         $xml .= "</problemstatistics>\n";
                   3347:     }
                   3348:     #
                   3349:     if (&has_eval_data(\%values)) {
                   3350:         $xml .= "<evaluation>\n";
                   3351:         foreach my $field (&evalfields) {
                   3352:             $xml .= qq{<$field>$values{$field}</$field>}."\n";            
                   3353:         }
                   3354:         $xml .= "</evaluation>\n";
                   3355:     }    
                   3356:     #
                   3357:     $xml .= "</LonCapaResource>\n";
1.212     matthew  3358:     $xml = &HTML::Entities::encode($xml,'<>&');
1.50      harris41 3359:     my $result=<<END;
1.150     matthew  3360: $prefix
1.56      harris41 3361: <pre>
1.212     matthew  3362: $xml
1.56      harris41 3363: </pre>
1.126     matthew  3364: $values{'extrashow'}
1.150     matthew  3365: <hr align='left' width='200' noshade />
1.50      harris41 3366: END
                   3367:     return $result;
1.60      harris41 3368: }
                   3369: 
1.122     matthew  3370: ######################################################################
                   3371: ######################################################################
                   3372: 
                   3373: =pod 
                   3374: 
                   3375: =item &filled() see if field is filled.
                   3376: 
                   3377: =cut
                   3378: 
                   3379: ######################################################################
                   3380: ######################################################################
1.98      harris41 3381: sub filled {
                   3382:     my ($field)=@_;
                   3383:     if ($field=~/\S/ && $field ne 'any') {
1.204     matthew  3384:         return 1;
                   3385:     } else {
                   3386:         return 0;
1.61      harris41 3387:     }
1.60      harris41 3388: }
                   3389: 
1.122     matthew  3390: ######################################################################
                   3391: ######################################################################
                   3392: 
                   3393: =pod 
                   3394: 
1.228     matthew  3395: =item &output_unparsed_phrase_error()
                   3396: 
                   3397: =cut
                   3398: 
                   3399: ######################################################################
                   3400: ######################################################################
                   3401: sub output_unparsed_phrase_error {
                   3402:     my ($r,$closebutton,$parms,$hidden_fields,$field)=@_;
                   3403:     my $errorstring;
                   3404:     if ($field eq 'basicexp') {
                   3405:         $errorstring = &mt('Unable to understand the search phrase <i>[_1]</i>.  Please modify your search.',$ENV{'form.basicexp'});
                   3406:     } else {
                   3407:         $errorstring = &mt('Unable to understand the search phrase <b>[_1]</b>:<i>[_2]</i>.',$field,$ENV{'form.'.$field});
                   3408:     }
                   3409:     my $bodytag = &Apache::loncommon::bodytag('Search');
                   3410:     my $heading = &mt('Unparsed Field');
                   3411:     my $revise  = &mt('Revise search request');
                   3412:     # make query information persistent to allow for subsequent revision
                   3413:     $r->print(<<ENDPAGE);
                   3414: <html>
                   3415: <head>
                   3416: <title>The LearningOnline Network with CAPA</title>
                   3417: </head>
                   3418: $bodytag
                   3419: <form method="post" action="/adm/searchcat">
                   3420: $hidden_fields
                   3421: $closebutton
                   3422: <hr />
                   3423: <h2>$heading</h2>
                   3424: <p>
                   3425: $errorstring
                   3426: </p>
                   3427: <p>
                   3428: <a href="/adm/searchcat?$parms&persistent_db_id=$ENV{'form.persistent_db_id'}">$revise</a>
                   3429: </p>
                   3430: </body>
                   3431: </html>
                   3432: ENDPAGE
                   3433: }
                   3434: 
                   3435: ######################################################################
                   3436: ######################################################################
                   3437: 
                   3438: =pod 
                   3439: 
1.122     matthew  3440: =item &output_blank_field_error()
                   3441: 
1.151     matthew  3442: Output a complete page that indicates the user has not filled in enough
                   3443: information to do a search.
                   3444: 
                   3445: Inputs: $r (Apache request handle), $closebutton, $parms.
                   3446: 
                   3447: Returns: nothing
                   3448: 
                   3449: $parms is extra information to include in the 'Revise search request' link.
                   3450: 
1.122     matthew  3451: =cut
                   3452: 
                   3453: ######################################################################
                   3454: ######################################################################
1.98      harris41 3455: sub output_blank_field_error {
1.196     matthew  3456:     my ($r,$closebutton,$parms,$hidden_fields)=@_;
1.228     matthew  3457:     my $bodytag=&Apache::loncommon::bodytag('Search');
                   3458:     my $errormsg = &mt('You did not fill in enough information for the search to be started.  You need to fill in relevant fields on the search page in order for a query to be processed.');
                   3459:     my $revise = &mt('Revise Search Request');
                   3460:     my $heading = &mt('Unactionable Search Queary');
                   3461:     $r->print(<<ENDPAGE);
1.98      harris41 3462: <html>
                   3463: <head>
                   3464: <title>The LearningOnline Network with CAPA</title>
                   3465: </head>
1.155     matthew  3466: $bodytag
1.98      harris41 3467: <form method="post" action="/adm/searchcat">
1.145     matthew  3468: $hidden_fields
1.98      harris41 3469: $closebutton
                   3470: <hr />
1.228     matthew  3471: <h2>$heading</h2>
1.98      harris41 3472: <p>
1.228     matthew  3473: $errormsg
                   3474: </p>
                   3475: <p>
                   3476: <a href="/adm/searchcat?$parms&persistent_db_id=$ENV{'form.persistent_db_id'}">$revise</a>&nbsp;
1.98      harris41 3477: </p>
                   3478: </body>
                   3479: </html>
1.228     matthew  3480: ENDPAGE
                   3481:     return;
1.98      harris41 3482: }
                   3483: 
1.122     matthew  3484: ######################################################################
                   3485: ######################################################################
                   3486: 
                   3487: =pod 
                   3488: 
                   3489: =item &output_date_error()
                   3490: 
                   3491: Output a full html page with an error message.
                   3492: 
1.145     matthew  3493: Inputs: 
                   3494: 
                   3495:     $r, the request pointer.
                   3496:     $message, the error message for the user.
                   3497:     $closebutton, the specialized close button needed for groupsearch.
                   3498: 
1.122     matthew  3499: =cut
                   3500: 
                   3501: ######################################################################
                   3502: ######################################################################
1.60      harris41 3503: sub output_date_error {
1.196     matthew  3504:     my ($r,$message,$closebutton,$hidden_fields)=@_;
1.60      harris41 3505:     # make query information persistent to allow for subsequent revision
1.196     matthew  3506:     my $bodytag=&Apache::loncommon::bodytag(undef,undef,undef,1);
1.122     matthew  3507:     $r->print(<<RESULTS);
1.60      harris41 3508: <html>
                   3509: <head>
                   3510: <title>The LearningOnline Network with CAPA</title>
                   3511: </head>
1.155     matthew  3512: $bodytag
1.98      harris41 3513: <img align='right' src='/adm/lonIcons/lonlogos.gif' />
1.60      harris41 3514: <h1>Search Catalog</h1>
                   3515: <form method="post" action="/adm/searchcat">
1.145     matthew  3516: $hidden_fields
1.60      harris41 3517: <input type='button' value='Revise search request'
1.98      harris41 3518: onClick='this.form.submit();' />
1.60      harris41 3519: $closebutton
1.98      harris41 3520: <hr />
1.151     matthew  3521: <h3>Error</h3>
1.60      harris41 3522: <p>
                   3523: $message
                   3524: </p>
                   3525: </body>
                   3526: </html>
                   3527: RESULTS
1.101     harris41 3528: }
                   3529: 
1.122     matthew  3530: ######################################################################
                   3531: ######################################################################
                   3532: 
                   3533: =pod 
                   3534: 
                   3535: =item &start_fresh_session()
                   3536: 
1.142     matthew  3537: Cleans the global %groupsearch_db by removing all fields which begin with
1.122     matthew  3538: 'pre_' or 'store'.
                   3539: 
                   3540: =cut
                   3541: 
                   3542: ######################################################################
                   3543: ######################################################################
1.101     harris41 3544: sub start_fresh_session {
1.142     matthew  3545:     delete $groupsearch_db{'mode_catalog'};
                   3546:     foreach (keys %groupsearch_db) {
1.101     harris41 3547:         if ($_ =~ /^pre_/) {
1.142     matthew  3548:             delete $groupsearch_db{$_};
1.101     harris41 3549:         }
                   3550:         if ($_ =~ /^store/) {
1.142     matthew  3551: 	    delete $groupsearch_db{$_};
1.101     harris41 3552: 	}
1.109     harris41 3553:     }
1.3       harris41 3554: }
1.1       www      3555: 
                   3556: 1;
1.162     www      3557: 
                   3558: sub cleanup {
1.163     www      3559:     if (tied(%groupsearch_db)) {
                   3560:         unless (untie(%groupsearch_db)) {
                   3561: 	  &Apache::lonnet::logthis('Failed cleanup searchcat: groupsearch_db');
                   3562:         }
                   3563:     }
1.167     www      3564:     &untiehash();
1.162     www      3565:     &Apache::lonmysql::disconnect_from_db();
                   3566: }
1.98      harris41 3567: 
1.1       www      3568: __END__
1.105     harris41 3569: 
1.121     matthew  3570: =pod
1.105     harris41 3571: 
1.121     matthew  3572: =back 
1.105     harris41 3573: 
                   3574: =cut

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