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

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

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