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

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

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