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

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

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