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

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

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