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

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

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