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

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

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