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

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

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