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

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

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