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

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

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