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

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

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