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

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

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