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

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

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