File:  [LON-CAPA] / loncom / interface / lonsearchcat.pm
Revision 1.364: download - view: text, annotated - select for diffs
Wed Mar 19 15:44:44 2025 UTC (3 months, 1 week ago) by raeburn
Branches: MAIN
CVS tags: version_2_12_X, HEAD
- Fix quotes.

    1: # The LearningOnline Network with CAPA
    2: # Search Catalog
    3: #
    4: # $Id: lonsearchcat.pm,v 1.364 2025/03/19 15:44:44 raeburn Exp $
    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.
   14: #
   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/
   27: #
   28: ###############################################################################
   29: ###############################################################################
   30: 
   31: =pod 
   32: 
   33: =head1 NAME
   34: 
   35: lonsearchcat - LONCAPA Search Interface
   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.
   44: 
   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 
   51: search (on a server basis) is displayed to the user in a separate window.
   52: 
   53: =head1 Internals
   54: 
   55: =cut
   56: 
   57: ###############################################################################
   58: ###############################################################################
   59: 
   60: package Apache::lonsearchcat;
   61: 
   62: use strict;
   63: use Apache::Constants qw(:common :http);
   64: use Apache::lonnet;
   65: use Apache::File();
   66: use CGI qw(:standard);
   67: use Text::Query;
   68: use GDBM_File;
   69: use Apache::loncommon();
   70: use Apache::lonmysql();
   71: use Apache::lonmeta;
   72: use Apache::lonhtmlcommon;
   73: use Apache::lonlocal;
   74: use LONCAPA::lonmetadata();
   75: use HTML::Entities();
   76: use Parse::RecDescent;
   77: use Apache::lonnavmaps;
   78: use Apache::lonindexer();
   79: use Apache::lonwishlist();
   80: use LONCAPA;
   81: use Time::HiRes qw(sleep);
   82: 
   83: ######################################################################
   84: ######################################################################
   85: ##
   86: ## Global variables
   87: ##
   88: ######################################################################
   89: ######################################################################
   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
   94: 
   95: # The different view modes and associated functions
   96: 
   97: my %Views = ("detailed" => \&detailed_citation_view,
   98:              "detailedpreview" => \&detailed_citation_preview,
   99: 	     "summary"  => \&summary_view,
  100:              "summarypreview" => \&summary_preview,
  101: 	     "fielded"  => \&fielded_format_view,
  102: 	     "xml"      => \&xml_sgml_view,
  103: 	     "compact"  => \&compact_view);
  104: 
  105: ######################################################################
  106: ######################################################################
  107: sub handler {
  108:     my $r = shift;
  109: #    &set_defaults();
  110:     #
  111:     # set form defaults
  112:     #
  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().
  120: 
  121:     #
  122:     my $closebutton;  # button that closes the search window 
  123:                       # This button is different for the RAT compared to
  124:                       # normal invocation.
  125:     #
  126:     &Apache::loncommon::content_type($r,'text/html');
  127:     $r->send_http_header;
  128:     return OK if $r->header_only;
  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);
  133:     ## 
  134:     ## Pick up form fields passed in the links.
  135:     ##
  136:     &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
  137:              ['catalogmode','launch','acts','mode','form','element','pause',
  138:               'phase','persistent_db_id','table','start','show',
  139:               'cleargroupsort','titleelement','area','inhibitmenu']);
  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:     ##
  146:     if (exists($env{'form.pause'})) {
  147:         sleep(0.1);
  148:         delete($env{'form.pause'});
  149:     }
  150:     ##
  151:     ## Initialize global variables
  152:     ##
  153:     my $domain  = $r->dir_config('lonDefDomain');
  154:     my $temp_file_dir = LONCAPA::tempdir();
  155:     $diropendb= $temp_file_dir .
  156:         "$env{'user.domain'}_$env{'user.name'}_sel_res.db";
  157:     #
  158:     # set the name of the persistent database
  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;
  164:     }
  165: 
  166:     my $persistent_db_file = $temp_file_dir .
  167:         &escape($domain).
  168:             '_'.&escape($env{'user.name'}).
  169:                 '_'.$env{'form.persistent_db_id'}.'_persistent_search.db';
  170:     ##
  171:     &Apache::lonhtmlcommon::clear_breadcrumbs();
  172: 
  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:     }
  181:     if (&Apache::lonnet::allowed('bre',$env{'request.role.domain'}) eq 'F') {
  182:         push(@allowed_searches,'res');
  183:     } else {
  184:         unless ($env{'form.catalogmode'} eq 'import') {
  185:             $env{'form.area'} = 'portfolio';
  186:             $crumb_text = 'Portfolio Search';
  187:         }
  188:     }
  189:     if (@allowed_searches ==2) {
  190:        unless (($env{'form.area'} eq 'portfolio') || ($env{'form.area'} eq 'res')) {
  191:            delete($env{'form.area'});
  192:        }
  193:        $crumb_text = 'Portfolio and Content Library Search'; 
  194:     }
  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 {
  201:             $target = '_self';
  202:         }
  203:     }
  204:     &Apache::lonhtmlcommon::add_breadcrumb
  205:        ({href=>'/adm/searchcat?'.
  206: 	       &Apache::loncommon::inhibit_menu_check().
  207:                '&catalogmode='.$env{'form.catalogmode'}.
  208:                '&launch='.$env{'form.launch'}.
  209:                '&mode='.$env{'form.mode'}.
  210:                '&area='.$env{'form.area'},
  211:               text=>"$crumb_text",
  212:               target=>$target,
  213:               bug=>'Searching',});
  214:     #
  215:     if ($env{'form.phase'} !~ m/(basic|adv|course)_search/) {
  216:         if (! &get_persistent_form_data($persistent_db_file)) {
  217:             if ($env{'form.phase'} =~ /(run_search|results)/) {
  218:                 &Apache::lonnet::logthis('lonsearchcat:'.
  219:                                          'Unable to recover data from '.
  220:                                          $persistent_db_file);
  221:                 my $msg =
  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});
  230: 		return OK;
  231:             }
  232:         }
  233:     } else {
  234:         &clean_up_environment();
  235:     }
  236:     ##
  237:     ## Clear out old values from groupsearch database
  238:     ##
  239:     untie %groupsearch_db if (tied(%groupsearch_db));
  240:     if (($env{'form.cleargroupsort'} eq '1') || 
  241:         (($env{'form.launch'} eq '1') && 
  242:          ($env{'form.catalogmode'} eq 'import'))) {
  243: 	if (tie(%groupsearch_db,'GDBM_File',$diropendb,&GDBM_WRCREAT(),0640)) {
  244: 	    &start_fresh_session();
  245: 	    untie %groupsearch_db;
  246:             delete($env{'form.cleargroupsort'});
  247: 	} else {
  248:             # This is a stupid error to give to the user.  
  249:             # It really tells them nothing.
  250: 	    my $msg = 'Unable to tie hash to db file.';
  251: 	    &Apache::loncommon::simple_error_page($r,'Search Error',
  252: 						  $msg);
  253: 	    return OK;
  254: 	}
  255:     }
  256:     ##
  257:     ## Configure hidden fields
  258:     ##
  259:     $hidden_fields = '<input type="hidden" name="persistent_db_id" value="'.
  260:         $env{'form.persistent_db_id'}.'" />'."\n";
  261:     if (exists($env{'form.catalogmode'})) {
  262:         $hidden_fields .= &hidden_field('catalogmode');
  263:     }
  264:     if (exists($env{'form.form'})) {
  265:         $hidden_fields .= &hidden_field('form');
  266:     }
  267:     if (exists($env{'form.element'})) {
  268:         $hidden_fields .= &hidden_field('element');
  269:     }
  270:     if (exists($env{'form.titleelement'})) {
  271:         $hidden_fields .= &hidden_field('titleelement');
  272:     }
  273:     if (exists($env{'form.mode'})) {
  274:         $hidden_fields .= &hidden_field('mode');
  275:     }
  276:     if (exists($env{'form.area'})) {
  277:         $hidden_fields .= &hidden_field('area');
  278:     }
  279:     if (exists($env{'form.inhibitmenu'})) {
  280:         $hidden_fields .= &hidden_field('inhibitmenu');
  281:     }
  282:     ##
  283:     ## Configure dynamic components of interface
  284:     ##
  285:     if ($env{'form.catalogmode'} eq 'interactive') {
  286:         $closebutton="<input type='button' name='close' value='".&mt('Close')."' ";
  287:         if ($env{'form.phase'} =~ /(results|run_search)/) {
  288:             $closebutton .="onclick='parent.close()'";
  289:         } else {
  290:             $closebutton .="onclick='self.close()'";
  291:         }
  292:         $closebutton .=" />\n";
  293:     } elsif ($env{'form.catalogmode'} eq 'import') {
  294:         $closebutton="<input type='button' name='close' value='".&mt('Close')."' ";
  295:         if ($env{'form.phase'} =~ /(results|run_search)/) {
  296:             $closebutton .="onclick='parent.close()'";
  297:         } else {
  298:             $closebutton .="onclick='self.close()'";
  299:         }
  300:         $closebutton .= " />";
  301:         my $txt_import = &mt('IMPORT');
  302:         $importbutton=<<END;
  303: <input type='button' name='import' value='$txt_import'
  304: onclick='javascript:select_group()' />
  305: END
  306:     } else {
  307:         $closebutton = '';
  308:         $importbutton = '';
  309:     }
  310:     ##
  311:     ## Sanity checks on form elements
  312:     ##
  313:     if (!defined($env{'form.viewselect'})) {
  314: 	$env{'form.viewselect'} ="summary";
  315:     }
  316:     $env{'form.phase'} = 'disp_basic' if (! exists($env{'form.phase'}));
  317:     $env{'form.show'} = 20 if (! exists($env{'form.show'}));
  318:     #
  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';
  323:     }
  324:     #
  325:     if ($env{'form.searchmode'} eq 'advanced') {
  326:         my $srchtype = 'Content Library';
  327:         if ($env{'form.area'} eq 'portfolio') {
  328:             $srchtype = 'Portfolio';
  329:         }
  330:         &Apache::lonhtmlcommon::add_breadcrumb
  331:             ({href=>'/adm/searchcat?'.&Apache::loncommon::inhibit_menu_check().
  332:                   '&amp;phase=disp_adv'.
  333:                   '&amp;catalogmode='.$env{'form.catalogmode'}.
  334:                   '&amp;launch='.$env{'form.launch'}.
  335:                   '&amp;mode='.$env{'form.mode'}.
  336:                   '&amp;area='.$env{'form.area'},
  337:                   text=>"Advanced $srchtype Search",
  338:                   bug=>'Searching',});
  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:     }
  352:     ##
  353:     ## Switch on the phase
  354:     ##
  355:     if ($env{'form.phase'} eq 'disp_basic') {
  356:         &print_basic_search_form($r,$closebutton,$hidden_fields);
  357:     } elsif ($env{'form.phase'} eq 'disp_adv') {
  358:         &print_advanced_search_form($r,$closebutton,$hidden_fields);
  359:     } elsif ($env{'form.phase'} eq 'results') {
  360:         &display_results($r,$importbutton,$closebutton,$diropendb,
  361:                          $env{'form.area'});
  362:     } elsif ($env{'form.phase'} =~ /^(sort|run_search)$/) {
  363:         my ($query,$customquery,$customshow,$libraries,$pretty_string,$domainsref) =
  364:             &get_persistent_data($persistent_db_file,
  365:                  ['query','customquery','customshow',
  366:                   'libraries','pretty_string','domains']);
  367:         if ($env{'form.phase'} eq 'sort') {
  368:             &print_sort_form($r,$pretty_string,$target);
  369:         } elsif ($env{'form.phase'} eq 'run_search') {
  370:             &run_search($r,$query,$customquery,$customshow,
  371:                         $libraries,$pretty_string,$env{'form.area'},$domainsref,$target);
  372:         }
  373:     } elsif(($env{'form.phase'} eq 'basic_search') ||
  374:             ($env{'form.phase'} eq 'adv_search')) {
  375:         #
  376:         # We are running a search, try to parse it
  377:         my ($query,$customquery,$customshow,$libraries,$domains) = 
  378:             (undef,undef,undef,undef,undef);
  379:         my $pretty_string;
  380:         if ($env{'form.phase'} eq 'basic_search') {
  381:             ($query,$pretty_string,$libraries,$domains) = 
  382:                 &parse_basic_search($r,$closebutton,$hidden_fields);
  383:             return OK if (! defined($query));
  384:             &make_persistent({ basicexp => $env{'form.basicexp'}},
  385:                              $persistent_db_file);
  386:         } else {                      # Advanced search
  387:             ($query,$customquery,$customshow,$libraries,$pretty_string,$domains) 
  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,
  395:                            pretty_string => $pretty_string,
  396:                            domains => $domains },
  397:                          $persistent_db_file);
  398:         #
  399:         # Set up table
  400:         if (! defined(&create_results_table($env{'form.area'}))) {
  401: 	    my $errorstring=&Apache::lonmysql::get_error();
  402:             &Apache::lonnet::logthis('lonsearchcat.pm: Unable to create '.
  403:                                      'needed table.  lonmysql error:'.
  404:                                      $errorstring);
  405: 
  406: 	    my $msg = 
  407: 		'Unable to create table in which to save search results. '.
  408: 		'The search has been aborted.';
  409: 	    &Apache::loncommon::simple_error_page($r,'Search Error',
  410: 						  $msg);
  411: 	    return OK;
  412:         }
  413:         delete($env{'form.launch'});
  414:         if (! &make_form_data_persistent($r,$persistent_db_file)) {
  415: 	    my $msg=
  416: 		'Unable to properly save search information. '.
  417: 		'The search has been aborted.';
  418: 	    &Apache::loncommon::simple_error_page($r,'Search Error',
  419: 						  $msg);
  420: 	    return OK;
  421: 	}
  422:         ##
  423:         ## Print out the frames interface
  424:         ##
  425:         if (defined($query)) {
  426:             &print_frames_interface($r);
  427:         }
  428:     }
  429:     return OK;
  430: }
  431: 
  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 {
  439:     if ($env{'form.phase'} eq 'basic_search') {
  440:         if (! exists($env{'form.related'})) {
  441:             $env{'form.related'} = '';
  442:         }
  443:         if (! exists($env{'form.domains'})) {
  444:             $env{'form.domains'} = '';
  445:         }
  446:     } elsif ($env{'form.phase'} eq 'adv_search') {
  447:         foreach my $field ('title','keywords','notes',
  448:                            'abstract','standards','mime') {
  449:             if (! exists($env{'form.'.$field.'_related'})) {
  450:                 $env{'form.'.$field.'_related'} = '';
  451:             }
  452:         }
  453:     } elsif ($env{'form.phase'} eq 'course_search') {
  454:         if (! exists($env{'form.crsrelated'})) {
  455:             $env{'form.crsrelated'} = '';
  456:         }
  457:     }
  458: }
  459: 
  460: sub hidden_field {
  461:     my ($name,$value) = @_;
  462:     if (! defined($value)) {
  463:         $value = $env{'form.'.$name};
  464:     }
  465:     return '<input type="hidden" name="'.$name.'" value="'.$value.'" />'.$/;
  466: }
  467: 
  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: 
  504: ######################################################################
  505: 
  506: =pod
  507: 
  508: =over 4
  509:  
  510: =item &print_basic_search_form() 
  511: 
  512: Prints the form for the basic search.  Sorry the name is so cryptic.
  513: 
  514: =cut
  515: 
  516: ######################################################################
  517: ######################################################################
  518: sub print_basic_search_form {
  519:     my ($r,$closebutton,$hidden_fields) = @_;
  520:     my %lt = &Apache::lonlocal::texthash (
  521:                               res => 'Content Library Search',
  522:                               portfolio => 'Portfolio Search',
  523:     );
  524:     my $result = ($env{'form.catalogmode'} ne 'import');
  525:     my $area;
  526:     my $bread_crumb =
  527:         &Apache::lonhtmlcommon::breadcrumbs('Searching','Search_Basic',
  528: 					    $env{'form.catalogmode'} ne 'import');
  529:     my $scrout = &Apache::loncommon::start_page('Content Library').$bread_crumb.
  530:                  '<div class="LC_landmark" role="main">'."\n".
  531:                  &start_search_tabs();
  532:     if (&Apache::lonnet::allowed('bre',$env{'request.role.domain'}) eq 'F') {
  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);
  543:     }
  544:     $scrout .= &end_search_tabs().&Apache::loncommon::end_page();
  545:     $r->print($scrout);
  546:     return;
  547: }
  548: 
  549: sub setup_basic_search {
  550:     my ($r,$area,$hidden_fields,$closebutton) = @_;
  551:     # Define interface components
  552:     my %lt = &Apache::lonlocal::texthash (
  553:                               res => 'Content Library Search',
  554:                               portfolio => 'Portfolio Search',
  555:     );
  556:     my ($userelatedwords,$onlysearchdomain,$inclext,$adv_search_link,$scrout);
  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: 
  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:     }
  585:     $onlysearchdomain = '<label>'
  586:                        .&Apache::lonhtmlcommon::checkbox(
  587:                            'domains',$checked,
  588:                            $singledom,$disabled)
  589:                        .' '
  590:                        .&mt('only search domain [_1]'
  591:                                ,'<b>'.$singledom.'</b>')
  592:                        .'</label>';
  593: 
  594:     $adv_search_link = '<a href="/adm/searchcat?'.
  595: 	               &Apache::loncommon::inhibit_menu_check().
  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'}.
  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:     #
  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" />'.$/;
  626:     #
  627:     $scrout .= '<div><p>'
  628:               .&viewoptions()
  629:               .'</p>'
  630:               .'<p>'
  631:               .'<input type="submit" name="basicsubmit" '
  632:               .'value="'.&mt('Search').'" />'
  633:               .' '
  634:               .$closebutton
  635:               .'</p></div>';
  636:     #
  637:     $scrout .= '</form>';
  638:     return $scrout;
  639: } 
  640: 
  641: ######################################################################
  642: ######################################################################
  643: 
  644: =pod 
  645: 
  646: =item &advanced_search_form() 
  647: 
  648: Prints the advanced search form.
  649: 
  650: =cut
  651: 
  652: ######################################################################
  653: ######################################################################
  654: sub print_advanced_search_form{
  655:     my ($r,$closebutton,$hidden_fields) = @_;
  656:     my $bread_crumb = 
  657:         &Apache::lonhtmlcommon::breadcrumbs('Searching','Search_Advanced',
  658: 					    $env{'form.catalogmode'} ne 'import');
  659:     my %lt=&Apache::lonlocal::texthash('srch' => 'Search',
  660: 				       'reset' => 'Reset',
  661: 				       'help' => 'Help');
  662:     my $advanced_buttons=<<"END";
  663: <p>
  664: <input type="submit" name="advancedsubmit" value='$lt{"srch"}' />
  665: <input type="reset" name="reset" value='$lt{"reset"}' />
  666: $closebutton
  667: </p>
  668: END
  669:     my $srchtype = 'Content Library';
  670:     my $jscript;
  671:     if ($env{'form.area'} eq 'portfolio') {
  672:         $srchtype = 'Portfolio';
  673:         $jscript = '<script type="text/javascript">
  674: // <![CDATA[
  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();
  680:     }
  681: }
  682: // ]]>
  683: </script>';
  684:     }
  685:     my $scrout= &Apache::loncommon::start_page("Advanced $srchtype Search",
  686:                                                $jscript);
  687:     $scrout .= $bread_crumb.'<div class="LC_landmark" role="main">'."\n".
  688:                &start_search_tabs();
  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: 
  703:     my %fields=&Apache::lonmeta::fieldnames();
  704: 
  705:     # Standard Metadata
  706:     $scrout .= &Apache::lonhtmlcommon::row_headline()
  707:               .'<h2 class="LC_heading_2">'.&mt("Standard $srchtype Metadata").'</h2>'
  708:               .&searchhelp()
  709:               .&Apache::lonhtmlcommon::row_closure();
  710:     my %related_word_search = 
  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,
  721:          'subject'  => 1,
  722:          );
  723:     #
  724:     foreach my $field ('title','author','subject','owner','authorspace',
  725:                        'modifyinguser','keywords','notes','abstract',
  726:                        'standards','mime') {
  727:         $scrout .= &Apache::lonhtmlcommon::row_title('<label for="'.$field.'">'.
  728:                                                      &titlefield($fields{$field}).'</label>')
  729:                   .&Apache::lonmeta::prettyinput($field,
  730:                                           $env{'form.'.$field},'',
  731:                                           $field,
  732:                                           'advsearch',
  733:                                           $related_word_search{$field},
  734:                                           '&nbsp;&nbsp;',
  735:                                           $env{'form.'.$field.'_related'},
  736:                                           50);
  737:         if ($related_word_search{$field}) {
  738:             $scrout .= '<label for="'.$field.'_related">'.&mt('related words').'</label>';
  739:         } else {
  740:             $scrout .= '';
  741:         }
  742:         $scrout .= &Apache::lonhtmlcommon::row_closure();
  743:     }
  744:     foreach my $field ('lowestgradelevel','highestgradelevel') {
  745:         $scrout .= &Apache::lonhtmlcommon::row_title('<label for="'.$field.'">'.
  746:                                                      &titlefield($fields{$field}).'</label>')
  747:                   .&Apache::lonmeta::prettyinput($field,
  748:                                           $env{'form.'.$field},'',
  749:                                           $field,
  750:                                           'advsearch',
  751:                                           0)
  752:                   .&Apache::lonhtmlcommon::row_closure();
  753:     }
  754: 
  755:     $scrout .= &Apache::lonhtmlcommon::row_title('<label for="category">'.
  756:                                                  &titlefield(&mt('MIME Type Category')).'</label>')
  757:               .&Apache::loncommon::filecategoryselect('category',
  758:                    $env{'form.category'},'category')
  759:               .&Apache::lonhtmlcommon::row_closure();
  760: 
  761:     my $anydomain = 1;
  762:     if ($env{'form.area'} ne 'portfolio') {
  763:         unless (&Apache::lonnet::allowed('bre','/res/')) {
  764:             $anydomain = 0; 
  765:         }
  766:     }
  767: 
  768:     $scrout .= &Apache::lonhtmlcommon::row_title('<label for="domains">'.
  769:                                                  &titlefield(&mt('Domains')).'</label>');
  770:     if ($anydomain) {
  771:         my $defdom = &Apache::lonnet::default_login_domain();
  772:         my ($trusted,$untrusted) = &Apache::lonnet::trusted_domains('shared',$defdom);
  773:         $scrout .= &Apache::loncommon::domain_select('domains',
  774:                    $env{'form.domains'},1,$trusted,$untrusted,'domains');
  775:     } else {
  776:         $scrout .= &Apache::loncommon::select_dom_form($env{'user.domain'},
  777:                                                        'domains','','','',
  778:                                                        [$env{'user.domain'}],'',1,'domains');
  779:     }
  780:     $scrout .= &Apache::lonhtmlcommon::row_closure();
  781: 
  782:     # Misc metadata
  783:     if ($env{'form.area'} ne 'portfolio') {
  784:         $scrout .= &Apache::lonhtmlcommon::row_title('<label for="copyright">'.
  785:                                                      &titlefield(&mt('Copyright/Distribution')).'</label>')
  786:                   .&Apache::lonmeta::selectbox('copyright',
  787:                                              $env{'form.copyright'},'',
  788:                                              'copyright',
  789:                                 \&Apache::loncommon::copyrightdescription,
  790:                                        ( undef,
  791:                                         &Apache::loncommon::copyrightids)
  792:                                 )
  793:                   .&Apache::lonhtmlcommon::row_closure();
  794:     }
  795: 
  796:     $scrout .= &Apache::lonhtmlcommon::row_title('<label for="language">'.
  797:                                                  &titlefield(&mt('Language')).'</label>')
  798:               .&Apache::lonmeta::selectbox('language',
  799:                                     $env{'form.language'},'','language',
  800:                                     \&Apache::loncommon::languagedescription,
  801:                                     ('any',&Apache::loncommon::languageids)
  802:                                     )
  803:               .&Apache::lonhtmlcommon::row_closure();
  804:     
  805:     # Portfolio Metadata
  806:     if ($env{'form.area'} eq 'portfolio') {
  807:         # Added fields
  808:         my $curnumadd = $env{'form.numaddedfields'};
  809:         if ($curnumadd eq '') {
  810:             $curnumadd = 1;
  811:         }
  812:         my $customlabel = &mt('Text box description');
  813:         $scrout .= &Apache::lonhtmlcommon::row_headline()
  814:                   .'<h3>'.&mt('Custom Metadata fields').'</h3>'
  815:                   .&Apache::lonhtmlcommon::row_closure()
  816:                   .&Apache::lonhtmlcommon::row_title('<span class="LC_visually_hidden">'.$customlabel.'</span>',
  817:                                                      '','','',1)
  818:                   .&mt('Field Name').' | '.&mt('Field Value(s)')
  819:                   .&Apache::lonhtmlcommon::row_closure();
  820: 
  821:         for (my $j=0; $j<$curnumadd; $j++) {
  822:             my $num = $j+1;
  823:             my $namelabel = &mt('name of custom metadata field [_1]',$num);
  824:             my $valuelabel = &mt('value of custom metadata field [_1]',$num);
  825:             $scrout .= &Apache::lonhtmlcommon::row_title(&mt('Custom metadata [_1]',$num))
  826:                       .'<input type="text" id="addedfield_'.$j.'"'
  827:                       .' name="addedfield_'.$j.'" size="10"'
  828:                       .' value="'.$env{'form.addedfield_'.$j}.'" aria-label="'.$namelabel.'" />'
  829:                       .' '
  830:                       .'<input type="text" '
  831:                       .'name="addedvalues_'.$j.'" size="15"'
  832:                       .' value="'.$env{'form.addedvalues_'.$j}.'" aria-label="'.$valuelabel.'" />'
  833:                       .&Apache::lonhtmlcommon::row_closure();
  834:         }
  835:         my $addcustomlabel = &mt('Add metadata field option');
  836:         $scrout .= &Apache::lonhtmlcommon::row_title('<span class="LC_visually_hidden">'.$addcustomlabel.'</span>',
  837:                                                      '','','',1)
  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 {
  846:         #
  847:         # Dynamic metadata
  848:         my $statslabel = &mt('Text box description');
  849:         $scrout .= &Apache::lonhtmlcommon::row_headline()
  850:                   .'<h3>'.&mt('Problem Statistics').'</h3>'
  851:                   .&Apache::lonhtmlcommon::row_closure();
  852:         $scrout .= &Apache::lonhtmlcommon::row_title('<span class="LC_visually_hidden">'.$statslabel.'</span>',
  853:                                                      '','','',1)
  854:                   .&mt('Minimum').' | '.&mt('Maximum')
  855:                   .&Apache::lonhtmlcommon::row_closure();
  856:         foreach my $statistic 
  857:             ({ name=>'count',
  858:                description=>'Network-wide number of accesses (hits)',
  859:                minlabel => 'minimum hit count',
  860:                maxlabel => 'maximum hit count'},
  861:              { name=>'stdno',
  862:                description=>
  863:                'Statistics calculated for number of students',
  864:                minlabel => 'minimum number of students in calculation',
  865:                maxlabel => 'maximum number of students in calculation'},
  866:              { name => 'avetries',
  867:                description=>'Average number of tries till solved',
  868:                minlabel => 'minimum average tries till solved',
  869:                maxlabel => 'maximum average tries till solved'},
  870:              { name => 'difficulty',
  871:                description=>'Degree of difficulty',
  872:                minlabel => 'minimum degree of difficulty',
  873:                maxlabel => 'maximum degree of difficulty'},
  874:              { name => 'disc',
  875:                description=>'Degree of discrimination',
  876:                minlabel => 'minimum degree of discrimination',
  877:                maxlabel => 'maximum degree of discrimination'}) {
  878:               $scrout .= &Apache::lonhtmlcommon::row_title(&titlefield(&mt($statistic->{'description'})))
  879:                         .'<input type="text" name="'.$statistic->{'name'}
  880:                         .'_min" value="" size="6" aria-label="'.&mt($statistic->{'minlabel'}).'" />'
  881:                         .' '
  882:                         .'<input type="text" name="'.$statistic->{'name'}
  883:                         .'_max" value="" size="6" aria-label="'.&mt($statistic->{'maxlabel'}).'" />'
  884:                         .&Apache::lonhtmlcommon::row_closure();
  885:         }
  886:         my $evallabel = &mt('Text box description');
  887:         $scrout .= &Apache::lonhtmlcommon::row_headline()
  888:                   .'<h3>'.&mt('Evaluation Data').'</h3>'
  889:                   .&Apache::lonhtmlcommon::row_closure();
  890:         $scrout .= &Apache::lonhtmlcommon::row_title('<span class="LC_visually_hidden">'.$evallabel.'</span>',
  891:                                                      '','','',1)
  892:                   .&mt('Minimum').' | '.&mt('Maximum')
  893:                   .&Apache::lonhtmlcommon::row_closure();
  894:         foreach my $evaluation
  895:             ( { name => 'clear',
  896:                 description => 'Material presented in clear way',
  897:                 minlabel => 'minimum score: clarity',
  898:                 maxlabel => 'maximum score: clarity'},
  899:               { name =>'depth',
  900:                 description => 'Material covered with sufficient depth',
  901:                 minlabel => 'minimum score: coverage depth',
  902:                 maxlabel => 'maximum score: coverage depth'},
  903:               { name => 'helpful',
  904:                 description => 'Material is helpful',
  905:                 minlabel => 'minimum score: content helpful',
  906:                 maxlabel => 'maximum score: content helpful'},
  907:               { name => 'correct',
  908:                 description => 'Material appears to be correct',
  909:                 minlabel => 'minimum score: correctness',
  910:                 maxlabel => 'maximum score: correctness'},
  911:               { name => 'technical',
  912:                 description => 'Resource is technically correct',
  913:                 minlabel => 'minimum score: technical correctness',
  914:                 maxlabel => 'maximum score: technical correctness'}) {
  915:             $scrout .= &Apache::lonhtmlcommon::row_title(&titlefield(&mt($evaluation->{'description'})))
  916:                       .'<input type="text" name="'
  917:                       .$evaluation->{'name'}.'_min" value="" size="6" aria-label="'.&mt($evaluation->{'minlabel'}).'" />'
  918:                       .' '
  919:                       .'<input type="text" name="'
  920:                       .$evaluation->{'name'}.'_max" value="" size="6" aria-label="'.&mt($evaluation->{'maxlabel'}).'" />'
  921:                       .&Apache::lonhtmlcommon::row_closure();
  922:         }
  923:     }
  924:     #
  925:     # Creation/Modification date limits
  926:     my $dateslabel = &mt('Text box description');
  927:     $scrout .= &Apache::lonhtmlcommon::row_headline()
  928:               .'<h3>'.&mt('Creation and Modification dates').'</h3>'
  929:               .&Apache::lonhtmlcommon::row_closure();
  930:     $scrout .= &Apache::lonhtmlcommon::row_title('<span class="LC_visually_hidden">'.$dateslabel.'</span>',
  931:                                                  '','','',1)
  932:               .&mt('Month[_1]Day[_2]Year','&nbsp;'x14,'&nbsp;'x6)
  933:               .&Apache::lonhtmlcommon::row_closure();
  934: 
  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:                                             );
  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: 
  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:                                             );
  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: 
  990:     $scrout .= &end_search_tabs().'</div>'.&Apache::loncommon::end_page();
  991:     $r->print($scrout);
  992:     return;
  993: }
  994: 
  995: ######################################################################
  996: ######################################################################
  997: 
  998: =pod 
  999: 
 1000: =item &titlefield()
 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;
 1012:     return $title;
 1013: }
 1014: 
 1015: ######################################################################
 1016: ######################################################################
 1017: 
 1018: =pod 
 1019: 
 1020: =item viewoptiontext()
 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;
 1032:     my %desc=&Apache::lonlocal::texthash
 1033:         ('detailed' => "Detailed Citation View",
 1034:          'xml' => 'XML/SGML',
 1035:          'compact' => 'Compact View',
 1036:          'fielded' => 'Fielded Format',
 1037:          'summary' => 'Summary View',
 1038:          'summarypreview' => 'Summary Preview',
 1039:          'detailedpreview' => 'Detailed Citation Preview');
 1040:     return $desc{$code};
 1041: }
 1042: 
 1043: ######################################################################
 1044: ######################################################################
 1045: 
 1046: =pod 
 1047: 
 1048: =item viewoptions()
 1049: 
 1050: Inputs: none
 1051: 
 1052: Outputs: text for box with view options
 1053: 
 1054: =cut
 1055: 
 1056: ######################################################################
 1057: ######################################################################
 1058: sub viewoptions {
 1059:     my $scrout;
 1060:     if (! defined($env{'form.viewselect'})) { 
 1061:         $env{'form.viewselect'}='detailed'; 
 1062:     }
 1063:     $scrout .= '<span class="LC_nobreak"><label>'
 1064:               .&mt('Type:').' '
 1065:               .&Apache::lonmeta::selectbox('viewselect',
 1066:                    $env{'form.viewselect'},'','',
 1067:                    \&viewoptiontext,
 1068:                    sort(keys(%Views)))
 1069:               .'</label></span>';
 1070:     my $countselect = &Apache::lonmeta::selectbox('show',
 1071:                                                   $env{'form.show'},'','',
 1072:                                                   undef,
 1073:                                                   (10,20,50,100,1000,10000));
 1074:     $scrout .= ' <span class="LC_nobreak"><label>'
 1075:               .&mt('Records per Page:').' '.$countselect
 1076:               .'</label></span>'.$/;
 1077:     return $scrout;
 1078: }
 1079: 
 1080: ######################################################################
 1081: ######################################################################
 1082: 
 1083: =pod 
 1084: 
 1085: =item searchhelp()
 1086: 
 1087: Inputs: none
 1088: 
 1089: Outputs: return little blurb on how to enter searches
 1090: 
 1091: =cut
 1092: 
 1093: ######################################################################
 1094: ######################################################################
 1095: sub searchhelp {
 1096:     return &mt('Enter words and quoted phrases');
 1097: }
 1098: 
 1099: ######################################################################
 1100: ######################################################################
 1101: 
 1102: =pod 
 1103: 
 1104: =item &get_persistent_form_data()
 1105: 
 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.
 1111: Retrieve persistent data from %persistent_db.  Retrieved items will have their
 1112: values unescaped.  If a form value already exists in $env, it will not be
 1113: overwritten.  Form values that are array references may have values appended
 1114: to them.
 1115: 
 1116: =cut
 1117: 
 1118: ######################################################################
 1119: ######################################################################
 1120: sub get_persistent_form_data {
 1121:     my $filename = shift;
 1122:     return 0 if (! -e $filename);
 1123:     return undef if (! tie(%persistent_db,'GDBM_File',$filename,
 1124:                            &GDBM_READER(),0640));
 1125:     #
 1126:     # These make sure we do not get array references printed out as 'values'.
 1127:     my %arrays_allowed = ('form.domains'=>1);
 1128:     #
 1129:     # Loop through the keys, looking for 'form.'
 1130:     foreach my $name (keys(%persistent_db)) {
 1131:         next if ($name !~ /^form./);
 1132:         # Kludgification begins!
 1133:         if ($name eq 'form.domains' && 
 1134:             $env{'form.searchmode'} eq 'basic' &&
 1135:             $env{'form.phase'} ne 'disp_basic') {
 1136:             next;
 1137:         }
 1138:         # End kludge (hopefully)
 1139:         next if (exists($env{$name}));
 1140:         my @values = map { 
 1141:             &unescape($_);
 1142:         } split(',',$persistent_db{$name});
 1143:         next if (@values <1);
 1144:         if ($arrays_allowed{$name}) {
 1145:             $env{$name} = [@values];
 1146:         } else {
 1147:             $env{$name} = $values[0] if ($values[0]);
 1148:         }
 1149:     }
 1150:     untie (%persistent_db);
 1151:     return 1;
 1152: }
 1153: 
 1154: ######################################################################
 1155: ######################################################################
 1156: 
 1157: =pod 
 1158: 
 1159: =item &get_persistent_data()
 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
 1167: values unescaped.  If the item is 'domains; then the returned
 1168: value will be a hash pointer.  Otherwise, if the item contains
 1169: commas (before unescaping), the returned value will be an array pointer.
 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,
 1181:                            &GDBM_READER(),0640));
 1182:     foreach my $name (@Vars) {
 1183:         if (! exists($persistent_db{$name})) {
 1184:             push @Values, undef;
 1185:             next;
 1186:         }
 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);
 1197:         } else {
 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:             }
 1206:         }
 1207:     }
 1208:     untie (%persistent_db);
 1209:     return @Values;
 1210: }
 1211: 
 1212: ######################################################################
 1213: ######################################################################
 1214: 
 1215: =pod 
 1216: 
 1217: =item &make_persistent() 
 1218: 
 1219: Inputs: Hash of values to save, filename of persistent database.
 1220: 
 1221: Store variables away to the %persistent_db.
 1222: Values will be escaped.  Values that are array pointers will have their
 1223: elements escaped and concatenated in a comma separated string. Values 
 1224: that are hash pointers will have their keys and values escaped and 
 1225: concatenated in a comma separated string.
 1226: 
 1227: =cut
 1228: 
 1229: ######################################################################
 1230: ######################################################################
 1231: sub make_persistent {
 1232:     my %save = %{shift()};
 1233:     my $filename = shift;
 1234:     return undef if (! tie(%persistent_db,'GDBM_File',
 1235:                            $filename,&GDBM_WRCREAT(),0640));
 1236:     foreach my $name (keys(%save)) {
 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.
 1248:         my $store = join(',', map { &escape($_); } @values );
 1249:         $persistent_db{$name} = $store;
 1250:     }
 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
 1266: elements escaped and concatenated in a comma separated string.  
 1267: 
 1268: =cut
 1269: 
 1270: ######################################################################
 1271: ######################################################################
 1272: sub make_form_data_persistent {
 1273:     my $r = shift;
 1274:     my $filename = shift;
 1275:     my %save;
 1276:     foreach (keys(%env)) {
 1277:         next if (!/^form/ || /submit/);
 1278:         $save{$_} = $env{$_};
 1279:     }
 1280:     return &make_persistent(\%save,$filename);
 1281: }
 1282: 
 1283: ######################################################################
 1284: ######################################################################
 1285: 
 1286: =pod 
 1287: 
 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.
 1295: 
 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
 1303: 
 1304: =cut
 1305: 
 1306: ######################################################################
 1307: ######################################################################
 1308: sub parse_advanced_search {
 1309:     my ($r,$closebutton,$hidden_fields)=@_;
 1310:     my @BasicFields = ('title','author','subject','keywords','url','version',
 1311:                        'notes','abstract','extension','owner','authorspace',
 1312: #                       'custommetadata','customshow',
 1313:                        'modifyinguser','standards','mime');
 1314:     my @StatsFields = &statfields();
 1315:     my @EvalFields = &evalfields();
 1316:     my $fillflag=0;
 1317:     my $pretty_search_string = "";
 1318:     # Clean up fields for safety
 1319:     for my $field (@BasicFields,
 1320:                    'creationdatestart_month','creationdatestart_day',
 1321: 		   'creationdatestart_year','creationdateend_month',
 1322: 		   'creationdateend_day','creationdateend_year',
 1323: 		   'lastrevisiondatestart_month','lastrevisiondatestart_day',
 1324: 		   'lastrevisiondatestart_year','lastrevisiondateend_month',
 1325: 		   'lastrevisiondateend_day','lastrevisiondateend_year') {
 1326: 	$env{'form.'.$field}=~s/[^\w\/\s\(\)\=\-\"\'.\*]//g;
 1327:     }
 1328:     foreach ('mode','form','element') {
 1329: 	# is this required?  Hmmm.
 1330: 	next if (! exists($env{'form.'.$_}));
 1331: 	$env{'form.'.$_}=&unescape($env{'form.'.$_});
 1332: 	$env{'form.'.$_}=~s/[^\w\/\s\(\)\=\-\"\']//g;
 1333:     }
 1334:     # Preprocess the category form element.
 1335:     $env{'form.category'} = 'any' if (! defined($env{'form.category'}) ||
 1336:                                       ref($env{'form.category'}));
 1337:     #
 1338:     # Check to see if enough information was filled in
 1339:     foreach my $field (@BasicFields) {
 1340: 	if (&filled($env{'form.'.$field})) {
 1341: 	    $fillflag++;
 1342: 	}
 1343:     }
 1344:     foreach my $field (@StatsFields,@EvalFields) {
 1345:         if (&filled($env{'form.'.$field.'_max'})) {
 1346:             $fillflag++;
 1347:         }
 1348:         if (&filled($env{'form.'.$field.'_min'})) {
 1349:             $fillflag++;
 1350:         }
 1351:     }
 1352: 
 1353:     for my $field ('lowestgradelevel','highestgradelevel') {
 1354:         if ( $env{'form.'.$field} =~ /^\d+$/ &&
 1355:              $env{'form.'.$field} > 0) {
 1356:             $fillflag++;
 1357:         }
 1358:     }
 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:     }
 1370:     if (! $fillflag) {
 1371: 	&output_blank_field_error($r,$closebutton,
 1372:                                   'phase=disp_adv&amp;area='.$env{'form.area'}.
 1373:                                   '&amp;catalogmode='.$env{'form.catalogmode'},
 1374:                                   $hidden_fields);
 1375: 	return;
 1376:     }
 1377:     # Turn the form input into a SQL-based query
 1378:     my $query='';
 1379:     my @queries;
 1380:     my $font = '<font color="#800000" face="helvetica">';
 1381:     # Evaluate logical expression AND/OR/NOT phrase fields.
 1382:     foreach my $field (@BasicFields) {
 1383: 	next if (!defined($env{'form.'.$field}) || $env{'form.'.$field} eq '');
 1384:         my ($error,$SQLQuery) = 
 1385:             &process_phrase_input($env{'form.'.$field},
 1386:                                   $env{'form.'.$field.'_related'},$field);
 1387:         if (defined($error)) {
 1388:             &output_unparsed_phrase_error($r,$closebutton,
 1389:                                          'phase=disp_adv&amp;area='.$env{'form.area'}.
 1390:                                          '&amp;catalogmode='.$env{'form.catalogmode'}.
 1391:                                          $hidden_fields,$field);
 1392:             return;
 1393:         } else {
 1394:             $pretty_search_string .= 
 1395:                 $font.$field.'</font>: '.$env{'form.'.$field};
 1396:             if ($env{'form.'.$field.'_related'}) {
 1397:                 my @Words = 
 1398:                     &Apache::loncommon::get_related_words
 1399:                     ($env{'form.'.$field});
 1400:                 if (@Words) {
 1401:                     $pretty_search_string.= ' with related words: '.
 1402:                         join(', ',@Words[0..4]);
 1403:                 } else {
 1404:                     $pretty_search_string.= ' with related words.';
 1405:                 }
 1406:             }
 1407:             $pretty_search_string .= '<br />';
 1408:             push (@queries,$SQLQuery);
 1409:         }
 1410:     }
 1411:     #
 1412:     # Make the 'mime' from 'form.category' and 'form.extension'
 1413:     #
 1414:     my $searchphrase;
 1415:     if (exists($env{'form.category'})    && 
 1416:         $env{'form.category'} !~ /^\s*$/ &&
 1417:         $env{'form.category'} ne 'any')     {
 1418:         my @extensions = &Apache::loncommon::filecategorytypes
 1419:                                                    ($env{'form.category'});
 1420:         if (scalar(@extensions) > 0) {
 1421:             $searchphrase = join(' OR ',@extensions);
 1422:         }
 1423:     }
 1424:     if (defined($searchphrase)) {
 1425:         my ($error,$SQLsearch) = &process_phrase_input($searchphrase,0,'mime');
 1426:         push @queries,$SQLsearch;
 1427:         $pretty_search_string .=$font.'mime</font> contains <b>'.
 1428:             $searchphrase.'</b><br />';
 1429:     }
 1430:     #
 1431:     # Evaluate option lists
 1432:     if ($env{'form.lowestgradelevel'}        &&
 1433:         $env{'form.lowestgradelevel'} ne '0' &&
 1434:         $env{'form.lowestgradelevel'} =~ /^\d+$/) {
 1435: 	push(@queries,
 1436:              '(lowestgradelevel>='.$env{'form.lowestgradelevel'}.')');
 1437:         $pretty_search_string.="lowestgradelevel>=".
 1438:             $env{'form.lowestgradelevel'}."<br />\n";
 1439:     }
 1440:     if ($env{'form.highestgradelevel'}        &&
 1441:         $env{'form.highestgradelevel'} ne '0' &&
 1442:         $env{'form.highestgradelevel'} =~ /^\d+$/) {
 1443: 	push(@queries,
 1444:              '(highestgradelevel<='.$env{'form.highestgradelevel'}.')');
 1445:         $pretty_search_string.="highestgradelevel<=".
 1446:             $env{'form.highestgradelevel'}."<br />\n";
 1447:     }
 1448:     if ($env{'form.language'} and $env{'form.language'} ne 'any') {
 1449: 	push @queries,"(language like \"$env{'form.language'}\")";
 1450:         $pretty_search_string.=$font."language</font>= ".
 1451:             &Apache::loncommon::languagedescription($env{'form.language'}).
 1452:                 "<br />\n";
 1453:     }
 1454:     if ($env{'form.copyright'} and $env{'form.copyright'} ne 'any') {
 1455: 	push @queries,"(copyright like \"$env{'form.copyright'}\")";
 1456:         $pretty_search_string.=$font."copyright</font> = ".
 1457:             &Apache::loncommon::copyrightdescription($env{'form.copyright'}).
 1458:                 "<br />\n";
 1459:     }
 1460:     if ($env{'form.area'} eq 'portfolio') {
 1461:         #
 1462:         # Added metadata fields
 1463:         for (my $i=0; $i<$env{'form.numaddedfields'} ; $i++) {
 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 '') {
 1471:                     $value =~ s/'/''/g; #' stupid emacs
 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:                 }
 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:             }
 1510:         }
 1511:     }
 1512:     #
 1513:     # Evaluate date windows
 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)) {
 1537:         # Here is where you would set up pretty_search_string to output
 1538:         # date query information.
 1539:         $pretty_search_string .= '<br />'.$prettydate.'<br />';
 1540: 	push @queries,$datequery;
 1541:     }
 1542:     #
 1543:     # Process form information for custom metadata querying
 1544:     my $customquery=undef;
 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:     ##
 1550:     # if ($env{'form.custommetadata'}) {
 1551:     #    $pretty_search_string .=$font."Custom Metadata Search</font>: <b>".
 1552:     #    $env{'form.custommetadata'}."</b><br />\n";
 1553:     #    $customquery=&build_custommetadata_query('custommetadata',
 1554:     #                                             $env{'form.custommetadata'});
 1555:     # }
 1556:     my $customshow=undef;
 1557:     # if ($env{'form.customshow'}) {
 1558:     # $pretty_search_string .=$font."Custom Metadata Display</font>: <b>".
 1559:     #                         $env{'form.customshow'}."</b><br />\n";
 1560:     #    $customshow=$env{'form.customshow'};
 1561:     #    $customshow=~s/[^\w\s]//g;
 1562:     #    my @fields=split(/\s+/,$customshow);
 1563:     #    $customshow=join(" ",@fields);
 1564:     # }
 1565:     ##
 1566:     ## Deal with restrictions to given domains
 1567:     ## 
 1568:     my ($libraries_to_query,$pretty_domains_string,$domains_to_query) = 
 1569:         &parse_domain_restrictions();
 1570:     if ($pretty_domains_string) {
 1571:        $pretty_search_string .= $pretty_domains_string."<br />\n";
 1572:     }
 1573:     #
 1574:     if (@queries) {
 1575:         if ($env{'form.area'} eq 'portfolio') {
 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).'))';
 1577:         } else {
 1578: 	    $query="SELECT * FROM metadata WHERE (".join(") AND (",@queries).')';
 1579:         }
 1580:     } elsif ($customquery) {
 1581:         $query = '';
 1582:     }
 1583:     #&Apache::lonnet::logthis('advanced query = '.$/.$query);
 1584:     return ($query,$customquery,$customshow,$libraries_to_query,
 1585:             $pretty_search_string,$domains_to_query);
 1586: }
 1587: 
 1588: sub parse_domain_restrictions {
 1589:     my $libraries_to_query = undef;
 1590:     my $domains_to_query = undef;
 1591:     # $env{'form.domains'} can be either a scalar or an array reference.
 1592:     # We need an array.
 1593:     if (! exists($env{'form.domains'}) || $env{'form.domains'} eq '') {
 1594:         return (undef,'',undef);
 1595:     }
 1596:     my @allowed_domains = &Apache::loncommon::get_env_multiple('form.domains');
 1597:     #
 1598:     my %domain_hash = ();
 1599:     my $pretty_domains_string;
 1600:     foreach (@allowed_domains) {
 1601:         $domain_hash{$_}++;
 1602:     }
 1603:     if ($domain_hash{'any'}) {
 1604:         $pretty_domains_string = &mt("in all LON-CAPA domains.");
 1605:     } else {
 1606:         if (@allowed_domains > 1) {
 1607:             $pretty_domains_string = &mt("in LON-CAPA domains:");
 1608:         } else {
 1609:             $pretty_domains_string = &mt("in LON-CAPA domain ");
 1610:         }
 1611:         foreach (sort @allowed_domains) {
 1612:             $pretty_domains_string .= "<b>".$_."</b> ";
 1613:         }
 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);
 1634: 	$libraries_to_query = [keys(%servers)];
 1635:         $domains_to_query = \%domains_for_id;
 1636:     }
 1637:     return ($libraries_to_query,
 1638:             $pretty_domains_string,
 1639:             $domains_to_query);
 1640: }
 1641: 
 1642: ######################################################################
 1643: ######################################################################
 1644: 
 1645: =pod 
 1646: 
 1647: =item &parse_basic_search() 
 1648: 
 1649: Parse the basic search form and return a scalar containing an sql query.
 1650: 
 1651: =cut
 1652: 
 1653: ######################################################################
 1654: ######################################################################
 1655: sub parse_basic_search {
 1656:     my ($r,$closebutton)=@_;
 1657:     #
 1658:     # Clean up fields for safety
 1659:     for my $field ('basicexp') {
 1660: 	$env{"form.$field"}=~s/[^\w\s\'\"\!\(\)\-\*]//g;
 1661:     }
 1662:     foreach ('mode','form','element') {
 1663: 	# is this required?  Hmmm.
 1664: 	next unless (exists($env{"form.$_"}));
 1665: 	$env{"form.$_"}=&unescape($env{"form.$_"});
 1666: 	$env{"form.$_"}=~s/[^\w\/\s\(\)\=\-\"\']//g;
 1667:     }
 1668:     my ($libraries_to_query,$pretty_domains_string,$domains_to_query) = 
 1669:         &parse_domain_restrictions();
 1670:     #
 1671:     # Check to see if enough of a query is filled in
 1672:     my $search_string = $env{'form.basicexp'};
 1673:     if (! &filled($search_string)) {
 1674: 	&output_blank_field_error($r,$closebutton,'phase=disp_basic'.
 1675:                                   '&amp;area='.$env{'form.area'}.
 1676:                                   '&amp;catalogmode='.$env{'form.catalogmode'});
 1677: 	return OK;
 1678:     }
 1679:     my $pretty_search_string=$search_string;
 1680:     my @Queries;
 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:     }
 1688:     my ($error,$SQLQuery) = &process_phrase_input($search_string,
 1689:                                                     $env{'form.related'},
 1690:                                                     $searchfield);
 1691:     if ($error) {
 1692:         &output_unparsed_phrase_error($r,$closebutton,'phase=disp_basic'.
 1693:                                       '&amp;area='.$env{'form.area'}.
 1694:                                       '&amp;catalogmode='.$env{'form.catalogmode'},
 1695:                                       '','basicexp');
 1696:         return;
 1697:     }
 1698:     push(@Queries,$SQLQuery);
 1699:     #foreach my $q (@Queries) {
 1700:     #    &Apache::lonnet::logthis('    '.$q);
 1701:     #}
 1702:     my $final_query;
 1703:     if ($env{'form.area'} eq 'portfolio') {
 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).')';
 1705:     } else {
 1706:         $final_query = 'SELECT * FROM metadata WHERE '.join(" AND ",@Queries);
 1707:     }
 1708:     #
 1709:     if ($env{'form.related'}) {
 1710: 	$pretty_search_string.=' '.&mt('(including related words)');
 1711:     }
 1712:     if (defined($pretty_domains_string) && $pretty_domains_string ne '') {
 1713:         $pretty_search_string .= ' '.$pretty_domains_string;
 1714:     }
 1715:     $pretty_search_string .= "<br />\n";
 1716:     $pretty_search_string =~ s:^<br /> and ::;
 1717:     &Apache::lonnet::logthis('simple search final query = '.$/.$final_query);
 1718:     return ($final_query,$pretty_search_string,
 1719:             $libraries_to_query,$domains_to_query);
 1720: }
 1721: 
 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: 
 1739: sub process_phrase_input {
 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:
 1820:         /[\w\Q:!@#$%^&*()+_=|{}<>,.;\\\/?\E\-]+/ {
 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);
 1854:             }
 1855:             if ($phrase eq 'NOT') {
 1856:                 $phrasedata->{'negate'}++;
 1857:                 if (! @::Phrases) { $phrasedata = undef; last; }
 1858:                 $phrase = shift(@::Phrases);
 1859:             }
 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'}.'%"';
 1876:         } else {
 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.')';
 1891:             }
 1892:         } else {
 1893:             $SQLQuery = '('.$query.')';
 1894:         }
 1895:     }
 1896:     #
 1897:     # &Apache::lonnet::logthis("SQLQuery = $SQLQuery");
 1898:     #
 1899:     return undef,$SQLQuery;
 1900: }
 1901: 
 1902: ######################################################################
 1903: ######################################################################
 1904: 
 1905: =pod 
 1906: 
 1907: =item &related_version()
 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 {
 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);
 1927: }
 1928: 
 1929: 
 1930: ######################################################################
 1931: ######################################################################
 1932: 
 1933: =pod 
 1934: 
 1935: =item &build_custommetadata_query() 
 1936: 
 1937: Constructs a custom metadata query using a rather heinous regular
 1938: expression.
 1939: 
 1940: =cut
 1941: 
 1942: ######################################################################
 1943: ######################################################################
 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
 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;
 1960:     return $matchexp;
 1961: }
 1962: 
 1963: 
 1964: ######################################################################
 1965: ######################################################################
 1966: 
 1967: =pod 
 1968: 
 1969: =item &build_date_queries() 
 1970: 
 1971: Builds a SQL logic query to check time/date entries.
 1972: Also reports errors (check for /^Incorrect/).
 1973: 
 1974: =cut
 1975: 
 1976: ######################################################################
 1977: ######################################################################
 1978: sub build_date_queries {
 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
 1991:         $error = &mt('Incorrect entry for the creation date. '.
 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
 1998:         $error = &mt('Incorrect entry for the last revision date. '.
 1999:                      'You must specify both the beginning and ending dates.');
 2000:     }
 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;
 2010:             # Correct month; localtime gives month 0..11 but MySQL expects 1..12
 2011:             $camon++; $cbmon++;
 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;
 2030:             # Correct month; localtime gives month 0..11 but MySQL expects 1..12
 2031:             $mamon++; $mbmon++;
 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:         }
 2048:     }
 2049:     return ($result,$error,$pretty_string);
 2050: }
 2051: 
 2052: ######################################################################
 2053: ######################################################################
 2054: 
 2055: =pod
 2056: 
 2057: =item &copyright_check()
 2058: 
 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: 
 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
 2074:     if ($Metadata->{'copyright'} eq 'priv') {
 2075:         unless (($env{'user.name'} eq $resname) &&
 2076:                 ($env{'user.domain'} eq $resdom)) {
 2077:             return 0;
 2078:         }
 2079:     }
 2080:     # Check for domain
 2081:     if (($Metadata->{'copyright'} eq 'domain') &&
 2082:         ($env{'user.domain'} ne $resdom)) {
 2083:         return 0;
 2084:     }
 2085:     # Check for custom rights
 2086:     if ($Metadata->{'copyright'} eq 'custom') {
 2087:        return &Apache::lonnet::customaccess('bre',$Metadata->{'url'});
 2088:     }
 2089:     return 1;
 2090: }
 2091: 
 2092: ######################################################################
 2093: ######################################################################
 2094: 
 2095: =pod
 2096: 
 2097: =item &ensure_db_and_table()
 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/ ) {
 2116:         $r->print(&Apache::loncommon::start_page('Error')
 2117:                  .'<p class="LC_error">'
 2118:                  .&mt('Unable to retrieve search results. '
 2119:                      .'Unable to determine the table results were saved in.')
 2120:                  .'</p>'
 2121:                  . '<p>'.&mt('Internal info:').'</p>'
 2122:                  .'<pre>'.$table.'</pre>'
 2123:                  .&Apache::loncommon::end_page()
 2124:         );
 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)) {
 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:         );
 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)) {
 2145:         $r->print(
 2146:             '<p class="LC_error">'
 2147:            .&mt('A MySQL error has occurred.')
 2148:            .'</p></form>'
 2149:            .&Apache::loncommon::end_page());
 2150:         &Apache::lonnet::logthis("lonmysql was unable to determine the status".
 2151:                                  " of table ".$table);
 2152:         return undef;
 2153:     } elsif (! $table_check) {
 2154:         $r->print(
 2155:             '<p class="LC_error">'
 2156:            .&mt('The table of results could not be found.')
 2157:            .'</p>'
 2158:         );
 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: 
 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.
 2175: 
 2176: =cut
 2177: 
 2178: ######################################################################
 2179: ######################################################################
 2180: sub print_sort_form {
 2181:     my ($r,$pretty_query_string,$target) = @_;
 2182: 
 2183:     ##
 2184:     my %SortableFields=&Apache::lonlocal::texthash( 
 2185:          id        => 'Default',
 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',
 2197:          lastrevisiondate => 'Revision Date'
 2198:      );
 2199:     ##
 2200:     my $table = $env{'form.table'};
 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)) {
 2207:         $r->print("A MySQL error has occurred.</form>".
 2208: 		  &Apache::loncommon::end_page());
 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:     }
 2214:     my $args;
 2215:     if ($target eq '_parent') {
 2216:         $args = {'links_target' => $target};
 2217:     }
 2218:     my $start_page = &Apache::loncommon::start_page('Results',undef,$args);
 2219:     my $breadcrumbs=
 2220:         &Apache::lonhtmlcommon::breadcrumbs('Searching','Searching',
 2221: 					    $env{'form.catalogmode'} ne 'import',
 2222:                                             '','','','','','',$target);
 2223:     my $result = <<END;
 2224: $start_page
 2225: $breadcrumbs
 2226: <div class="LC_landmark" role="main">
 2227: <form name="statusform" action="" method="post" target="$target">
 2228: <input type="hidden" name="catalogmode" value="import" />
 2229: <input type="hidden" name="acts" value="" />
 2230: END
 2231: 
 2232: #<h2>Sort Results</h2>
 2233: #Sort by: <select size="1" name="sortby" onchange="javascript:change_sort();">
 2234: #    $env{'form.sortby'} = 'id' if (! defined($env{'form.sortby'}));
 2235: #    foreach (keys(%SortableFields)) {
 2236: #        $result.="<option name=\"$_\"";
 2237: #        if ($_ eq $env{'form.sortby'}) {
 2238: #            $result.=" selected ";
 2239: #        }
 2240: #        $result.=" >$SortableFields{$_}</option>\n";
 2241: #    }
 2242: #    $result.="</select>\n";
 2243:     my $revise = &revise_button();
 2244:     $result.='<p>'
 2245:             .&mt('Total of [quant,_1,match,matches] to your query.',$total_results)
 2246:             .' '.$revise.'</p>'
 2247:             .'<p>'.&mt('Search: ').$pretty_query_string
 2248:             .'</p></form>';
 2249:     $r->print($result.'</div>'.&Apache::loncommon::end_page());
 2250:     return;
 2251: }
 2252: 
 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: 
 2267: #####################################################################
 2268: #####################################################################
 2269: #
 2270: # These should probably be scoped but I don't have time right now...
 2271: #
 2272: my @Datatypes;
 2273: my @Fullindicies;
 2274:     
 2275: ######################################################################
 2276: ######################################################################
 2277: 
 2278: =pod
 2279: 
 2280: =item &create_results_table()
 2281: 
 2282: Creates the table of search results by calling lonmysql.  Stores the
 2283: table id in $env{'form.table'}
 2284: 
 2285: Inputs: search area - either res or portfolio 
 2286: 
 2287: Returns: the identifier of the table on success, undef on error.
 2288: 
 2289: =cut
 2290: 
 2291: ######################################################################
 2292: ######################################################################
 2293: sub set_up_table_structure {
 2294:     my ($tabletype) = @_;
 2295:     my ($datatypes,$fullindicies) = 
 2296:         &LONCAPA::lonmetadata::describe_metadata_storage($tabletype);
 2297:     # Copy the table description before modifying it...
 2298:     @Datatypes = @{$datatypes};
 2299:     unshift(@Datatypes,{name => 'id',  
 2300:         type => 'MEDIUMINT',
 2301:         restrictions => 'UNSIGNED NOT NULL',
 2302:         primary_key  => 'yes',
 2303:         auto_inc     => 'yes' });
 2304:     @Fullindicies = @{$fullindicies};
 2305:     return;
 2306: }
 2307: 
 2308: sub create_results_table {
 2309:     my ($area) = @_;
 2310:     if ($area eq 'portfolio') {
 2311:         &set_up_table_structure('portfolio_search');
 2312:     } else {
 2313:         &set_up_table_structure('metadata');
 2314:     }
 2315:     my $table = &Apache::lonmysql::create_table
 2316:         ( { columns => \@Datatypes,
 2317:             FULLTEXT => [{'columns' => \@Fullindicies},],
 2318:         } );
 2319:     if (defined($table)) {
 2320:         $env{'form.table'} = $table;
 2321:         return $table;
 2322:     } 
 2323:     return undef; # Error...
 2324: }
 2325: 
 2326: ######################################################################
 2327: ######################################################################
 2328: 
 2329: =pod
 2330: 
 2331: =item Search Status update functions
 2332: 
 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.
 2336: 
 2337: Inputs: Apache request handler ($r), text to display.
 2338: 
 2339: Returns: Nothing.
 2340: 
 2341: =over 4
 2342: 
 2343: =item &update_count_status()
 2344: 
 2345: =item &update_status()
 2346: 
 2347: =item &update_seconds()
 2348: 
 2349: =back
 2350: 
 2351: =cut
 2352: 
 2353: ######################################################################
 2354: ######################################################################
 2355: sub update_count_status {
 2356:     my ($r,$text) = @_;
 2357:     $text =~ s/\'/\\\'/g;
 2358:     $r->print(<<SCRIPT);
 2359: <script type="text/javascript">
 2360: // <![CDATA[
 2361: document.statusform.count.value = ' $text'
 2362: // ]]>
 2363: </script>
 2364: SCRIPT
 2365: 
 2366:     $r->rflush();
 2367: }
 2368: 
 2369: sub update_status {
 2370:     my ($r,$text) = @_;
 2371:     $text =~ s/\'/\\\'/g;
 2372:     $r->print(<<SCRIPT);
 2373: <script type="text/javascript">
 2374: // <![CDATA[
 2375: document.statusform.status.value = ' $text'
 2376: // ]]>
 2377: </script>
 2378: SCRIPT
 2379: 
 2380:     $r->rflush();
 2381: }
 2382: 
 2383: sub reload_result_frame {
 2384:     my ($r) = @_;
 2385:     my $newloc = '/adm/searchcat?phase=results&persistent_db_id='.
 2386:         $env{'form.persistent_db_id'}.'&area='.$env{'form.area'}.
 2387:         '&catalogmode='.$env{'form.catalogmode'};
 2388:     $r->print(<<SCRIPT);
 2389: <script type="text/javascript">
 2390:     parent.update_results("$newloc");
 2391: </script>
 2392: SCRIPT
 2393: 
 2394:     $r->rflush();
 2395: }
 2396: 
 2397: {
 2398:     my $max_time  = 60;  # seconds for the search to complete
 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: 
 2416: sub update_seconds {
 2417:     my ($r) = @_;
 2418:     my $time = &time_left();
 2419:     if (($last_time-$time) > 0) {
 2420:         $r->print(<<SCRIPT);
 2421: <script type="text/javascript">
 2422: // <![CDATA[
 2423: document.statusform.seconds.value = '$time'
 2424: // ]]>
 2425: </script>
 2426: SCRIPT
 2427: 
 2428:         $r->rflush();
 2429:     }
 2430:     $last_time = $time;
 2431: }
 2432: 
 2433: }
 2434: 
 2435: ######################################################################
 2436: ######################################################################
 2437: 
 2438: =pod
 2439: 
 2440: =item &revise_button()
 2441: 
 2442: Inputs: None
 2443: 
 2444: Returns: html string for a 'revise search' button.
 2445: 
 2446: =cut
 2447: 
 2448: ######################################################################
 2449: ######################################################################
 2450: sub revise_button {
 2451:     my $revisetext = &mt('Revise search');
 2452:     my $revise_phase = 'disp_basic';
 2453:     $revise_phase = 'disp_adv' if ($env{'form.searchmode'} eq 'advanced');
 2454:     my $newloc = '/adm/searchcat'.
 2455:         '?persistent_db_id='.$env{'form.persistent_db_id'}.
 2456:             '&amp;cleargroupsort=1'.
 2457:             '&amp;phase='.$revise_phase.
 2458:             '&amp;area='.$env{'form.area'}.
 2459:             '&amp;catalogmode='.$env{'form.catalogmode'};
 2460:     my $result = qq{<input type="button" value="$revisetext" name="revise"} .
 2461:         qq{ onclick="parent.location='$newloc';" /> };
 2462:     return $result;
 2463: }
 2464: 
 2465: ######################################################################
 2466: ######################################################################
 2467: 
 2468: =pod
 2469: 
 2470: =item &run_search()
 2471: 
 2472: Executes a search query by sending it the the other servers and putting the
 2473: results into MySQL.
 2474: 
 2475: =cut
 2476: 
 2477: ######################################################################
 2478: ######################################################################
 2479: sub run_search {
 2480:     my ($r,$query,$customquery,$customshow,$serverlist,
 2481:         $pretty_string,$area,$domainsref,$target) = @_;
 2482:     my $tabletype = 'metadata';
 2483:     if ($area eq 'portfolio') {
 2484:         $tabletype = 'portfolio_search';
 2485:     }
 2486:     my $connection = $r->connection;
 2487:     #
 2488:     # Print run_search header
 2489:     #
 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);
 2495:     my $breadcrumbs =
 2496: 	&Apache::lonhtmlcommon::breadcrumbs('Searching','Searching',
 2497: 					    $env{'form.catalogmode'} ne 'import',
 2498:                                             '','','','','','',$target);
 2499:     $r->print(<<END);
 2500: $start_page
 2501: $breadcrumbs
 2502: <div class="LC_landmark" role="main">
 2503: END
 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:     }
 2512:     if (@Lines > 2) {
 2513:         $pretty_string = join '<br />',(@Lines[0..2],'...<br />');
 2514:     }
 2515:     $r->print(&mt("Search: [_1]",$pretty_string));
 2516:     $r->rflush();
 2517:     #
 2518:     # Determine the servers we need to contact.
 2519:     my (@Servers_to_contact,%domains_by_server);
 2520:     if (defined($serverlist)) {
 2521:         if (ref($serverlist) eq 'ARRAY') {
 2522:             @Servers_to_contact = @$serverlist;
 2523:         } else {
 2524:             @Servers_to_contact = ($serverlist);
 2525:         }
 2526:         if (ref($domainsref) eq 'HASH') {
 2527:             foreach my $server (@Servers_to_contact) {
 2528:                 $domains_by_server{$server} = $domainsref->{$server};
 2529:             }
 2530:         }
 2531:     } else {
 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))) {
 2539:                     map { $older_library_servers{$_} = 1; }
 2540:                         &Apache::lonnet::machine_ids($library_servers{$key});
 2541:                 }
 2542:             }
 2543:         }
 2544:         %all_library_servers = (%library_servers,%older_library_servers);
 2545:         @Servers_to_contact = sort(keys(%all_library_servers));
 2546:         foreach my $server (@Servers_to_contact) {
 2547:             $domains_by_server{$server} =
 2548:                 join(',',sort(&Apache::lonnet::machine_domains($all_library_servers{$server})));
 2549:         }
 2550:     }
 2551:     my %Server_status;
 2552:     #
 2553:     # Check on the mysql table we will use to store results.
 2554:     my $table =$env{'form.table'};
 2555:     if (! defined($table) || $table eq '' || $table =~ /\D/ ) {
 2556:         $r->print("Unable to determine table id to save search results in.".
 2557:                   "The search has been aborted.".
 2558: 		  &Apache::loncommon::end_page());
 2559:         return;
 2560:     }
 2561:     my $table_status = &Apache::lonmysql::check_table($table);
 2562:     if (! defined($table_status)) {
 2563:         $r->print("Unable to determine status of table.".
 2564: 		  &Apache::loncommon::end_page());
 2565:         &Apache::lonnet::logthis("Bogus table id of $table for ".
 2566:                                  "$env{'user.name'} @ $env{'user.domain'}");
 2567:         &Apache::lonnet::logthis("lonmysql error = ".
 2568:                                  &Apache::lonmysql::get_error());
 2569:         return;
 2570:     }
 2571:     if (! $table_status) {
 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.'"');
 2577:         $r->print("The table id,$table, we tried to use is invalid.".
 2578:                   "The search has been aborted.".
 2579: 		  &Apache::loncommon::end_page());
 2580:         return;
 2581:     }
 2582:     ##
 2583:     ## Prepare for the big loop.
 2584:     my $hitcountsum;
 2585:     my $oldhitcountsum;
 2586:     my $displaycount;
 2587:     my %matches;
 2588:     my $server; 
 2589:     my $status;
 2590:     my $revise = &revise_button();
 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());
 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>'
 2599:              .&Apache::loncommon::end_data_table_header_row()
 2600:              .&Apache::loncommon::start_data_table_row()
 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>'
 2604:              .&Apache::loncommon::end_data_table_row()
 2605:              .&Apache::loncommon::end_data_table()
 2606:              .'</td><td>&nbsp;</td><td>'.$revise.'</td></tr></table></form>');
 2607:     $r->rflush();
 2608:     &reset_timing();
 2609:     &update_seconds($r);
 2610:     &update_status($r,&mt('contacting [_1]',$Servers_to_contact[0]));
 2611:     while (&time_left() &&
 2612:            ((@Servers_to_contact) || keys(%Server_status))) {
 2613:         &update_seconds($r);
 2614:         #
 2615:         # Send out a search request
 2616:         if (@Servers_to_contact) {
 2617:             # Contact one server
 2618:             my $server = shift(@Servers_to_contact);
 2619:             &update_status($r,&mt('contacting [_1]',$server));
 2620:             my $reply=&Apache::lonnet::metadata_query($query,$customquery,
 2621:                                                       $customshow,[$server],\%domains_by_server);
 2622:             ($server) = keys(%$reply);
 2623:             $Server_status{$server} = $reply->{$server};
 2624:         } else {
 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.  
 2629:             if (scalar (keys(%Server_status))) {
 2630:                 &update_status($r,
 2631:                        &mt('waiting on [_1]',join(' ',keys(%Server_status))));
 2632:             }
 2633:             sleep(0.1);
 2634:         }
 2635:         #
 2636:         # Loop through the servers we have contacted but do not
 2637:         # have results from yet, looking for results.
 2638:         foreach my $server (keys(%Server_status)) {
 2639:             last if ($connection->aborted());
 2640:             &update_seconds($r);
 2641:             my $status = $Server_status{$server};
 2642:             if ($status eq 'con_lost') {
 2643:                 delete ($Server_status{$server});
 2644:                 next;
 2645:             }
 2646:             $status=~s|/||g;
 2647: 
 2648: 
 2649: 
 2650:        	    my $datafile=LONCAPA::tempdir().$status;
 2651:             if (-e $datafile && ! -e "$datafile.end") {
 2652:                 &update_status($r,&mt('Receiving results from [_1]',$server));
 2653:                 next;
 2654:             }
 2655:             last if ($connection->aborted());
 2656:             if (-e "$datafile.end") {
 2657:                 &update_status($r,&mt('Reading results from [_1]',$server));
 2658:                 if (-z "$datafile") {
 2659:                     delete($Server_status{$server});
 2660:                     next;
 2661:                 }
 2662:                 my $fh;
 2663:                 if (!($fh=Apache::File->new($datafile))) { 
 2664:                     $r->print("Unable to open search results file for ".
 2665:                                   "server $server.  Omitting from search");
 2666:                     delete($Server_status{$server}); 
 2667:                    next;
 2668:                 }
 2669:                 # Read in the whole file.
 2670:                 while (my $result = <$fh>) {
 2671:                     last if ($connection->aborted());
 2672:                     #
 2673:                     # Records are stored one per line
 2674:                     chomp($result);
 2675:                     next if (! $result);
 2676:                     #
 2677:                     # Parse the result.
 2678:                     my %Fields = &parse_raw_result($result,$server,$tabletype);
 2679:                     $Fields{'hostname'} = $server;
 2680:                     #
 2681:                     # Skip based on copyright
 2682:                     next if (! &copyright_check(\%Fields));
 2683: 
 2684:                     if ($area eq 'portfolio') {
 2685:                         next if (defined($matches{$Fields{'url'}}));
 2686:                         # Skip unless access control set to public or passphrase-protected
 2687:                         next unless (($Fields{'scope'} eq 'public') || ($Fields{'scope'} eq 'guest'));
 2688:                         $matches{$Fields{'url'}} = 1; 
 2689:                     }
 2690:                     #
 2691:                     # Store the result in the mysql database
 2692:                     my $result = &Apache::lonmysql::store_row($table,\%Fields);
 2693:                     if (! defined($result)) {
 2694:                         $r->print(&Apache::lonmysql::get_error());
 2695:                     }
 2696:                     #
 2697:                     $hitcountsum ++;
 2698:                     &update_seconds($r);
 2699:                     if ($hitcountsum % 50 == 0) {
 2700:                         &update_count_status($r,$hitcountsum);
 2701:                     }
 2702:                 }
 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:             }
 2708:             last if ($connection->aborted());
 2709:             if ($oldhitcountsum < $hitcountsum) {
 2710:                 &update_count_status($r,$hitcountsum);
 2711:                 if (($hitcountsum <= $env{'form.show'}) ||
 2712:                     (!$displaycount && $hitcountsum)) {
 2713:                     reload_result_frame($r);
 2714:                     $displaycount = $hitcountsum;
 2715:                 }
 2716:                 $oldhitcountsum = $hitcountsum;
 2717:             }
 2718:         }
 2719:         last if ($connection->aborted());
 2720:         &update_seconds($r);
 2721:     }
 2722:     &update_status($r,&mt('Search Complete on Server [_1]',$server));
 2723:     &update_seconds($r);
 2724:     #
 2725:     &Apache::lonmysql::disconnect_from_db(); # This is unneccessary
 2726:     #
 2727:     # We have run out of time or run out of servers to talk to and
 2728:     # results to get, so let the client know the top frame needs to be
 2729:     # loaded from /adm/searchcat
 2730:     $r->print('</div>'.&Apache::loncommon::end_page());
 2731: #    if ($env{'form.catalogmode'} ne 'import') {
 2732:          $r->print(<<SCRIPT);
 2733: <script>
 2734: window.location='/adm/searchcat?phase=sort&area=$env{"form.area"}&catalogmode=$env{"form.catalogmode"}&persistent_db_id=$env{"form.persistent_db_id"}';
 2735: </script>
 2736: SCRIPT
 2737: #    }
 2738:     return;
 2739: }
 2740: 
 2741: ######################################################################
 2742: ######################################################################
 2743: 
 2744: =pod
 2745: 
 2746: =item &prev_next_buttons()
 2747: 
 2748: Returns html for the previous and next buttons on the search results page.
 2749: 
 2750: =cut
 2751: 
 2752: ######################################################################
 2753: ######################################################################
 2754: sub prev_next_buttons {
 2755:     my ($current_min,$show,$total,$parms) = @_;
 2756:     return '' if ($show eq 'all'); # No links if you get them all at once.
 2757:     #
 2758:     # Create buttons
 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>';
 2768: }
 2769: 
 2770: ######################################################################
 2771: ######################################################################
 2772: 
 2773: =pod
 2774: 
 2775: =item &display_results()
 2776: 
 2777: Prints the results out for selection and perusal.
 2778: 
 2779: =cut
 2780: 
 2781: ######################################################################
 2782: ######################################################################
 2783: sub display_results {
 2784:     my ($r,$importbutton,$closebutton,$diropendb,$area) = @_;
 2785:     my $connection = $r->connection;
 2786:     $r->print(&search_results_header($importbutton,$closebutton));
 2787:     ##
 2788:     ## Set viewing function
 2789:     ##
 2790:     my $viewfunction = $Views{$env{'form.viewselect'}};
 2791:     if (!defined($viewfunction)) {
 2792:         $r->print('<p class="LC_error">'
 2793:                  .&mt('Internal Error - Bad view selected.')
 2794:                  .'</p>'."\n"
 2795:                  .'</form></div>'.&Apache::loncommon::end_page());
 2796:         $r->rflush();
 2797:         return;
 2798:     }
 2799:     ##
 2800:     ## $checkbox_num is a count of the number of checkboxes output on the 
 2801:     ## page this is used only during catalogmode=import.
 2802:     my $checkbox_num = 0;
 2803:     ##
 2804:     ## Get the catalog controls setup
 2805:     ##
 2806:     my $action = '/adm/searchcat?phase=results&amp;area='.$env{'form.area'}.
 2807:                  '&amp;catalogmode='.$env{'form.catalogmode'};
 2808:     ##
 2809:     ## Deal with import by opening the import db file.
 2810:     if ($env{'form.catalogmode'} eq 'import') {
 2811:         if (! tie(%groupsearch_db,'GDBM_File',$diropendb,
 2812:                   &GDBM_WRCREAT(),0640)) {
 2813:             # NOTE: this can happen when a previous request to searchcat?phase=results gets interrupted
 2814:             # (%groupsearch_db is not untied)
 2815:             $r->print('<p class="LC_error">'.
 2816:               &mt('Unable to save import results.').
 2817:               '</p>'.
 2818:               '</form></div>'.
 2819: 		      &Apache::loncommon::end_page());
 2820:             $r->rflush();
 2821:             return;
 2822:         } 
 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:         });
 2827:     }
 2828:     ##
 2829:     ## Prepare the table for querying
 2830:     my $table = $env{'form.table'};
 2831:     return if (! &ensure_db_and_table($r,$table));
 2832:     ##
 2833:     ## Get the number of results 
 2834:     my $total_results = &Apache::lonmysql::number_of_rows($table);
 2835:     if (! defined($total_results)) {
 2836:         $r->print('<p class="LC_error">'.
 2837:           &mt('A MySQL error has occurred.').
 2838:           '</p>'.
 2839:           '</form></div>'.
 2840: 		  &Apache::loncommon::end_page());
 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
 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'};
 2858:     my $max;
 2859:     if ($env{'form.show'} eq 'all') {
 2860:         $max = $total_results ;
 2861:     } else {
 2862:         $max = $min + $env{'form.show'} - 1;
 2863:         $max = $total_results if ($max > $total_results);
 2864:     }
 2865:     ##
 2866:     ## Output form elements
 2867:     $r->print(&hidden_field('table').
 2868:               &hidden_field('phase').
 2869:               &hidden_field('persistent_db_id').
 2870:               &hidden_field('start').
 2871:               &hidden_field('area')
 2872:               );
 2873:     #
 2874:     # Build sorting selector
 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'},
 2892:         );
 2893:     if ($area eq 'portfolio') {
 2894:         push(@fields,
 2895:        (
 2896:          {key => 'scope'},
 2897:          {key => 'keynum'},
 2898:        ));
 2899:     } else {
 2900:         push(@fields,
 2901:        (
 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'},
 2912:        ));
 2913:     }
 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;
 2929:     $env{'form.sortorder'} = 'desc' if (! exists($env{'form.sortorder'}));
 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:     }
 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:     }
 2944:     my $sortform = '<span class="LC_nobreak"><span id="LC_sortby">'
 2945:                   .&mt('Sort by:').'</span> '
 2946:                   .&Apache::loncommon::select_form($env{'form.sortfield'},
 2947:                                                    'sortfield',
 2948:                                                    \%sort_fields,'','','',
 2949:                                                    'LC_sortby')
 2950:                   .' '
 2951:                   .&Apache::loncommon::select_form($env{'form.sortorder'},
 2952:                                                    'sortorder',
 2953:                                                    {asc =>&mt('Ascending'),
 2954:                                                     desc=>&mt('Descending')
 2955:                                                    },'','','','LC_sortby')
 2956:                   .'</span>';
 2957:     ##
 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: 
 2968:     if ($total_results == 0) {
 2969:         $r->print('<h1 class="LC_search_results">'.&mt('There are currently no results.').'</h1>'.
 2970:                   '</form></div>'.
 2971: 		  &Apache::loncommon::end_page());
 2972:         return;
 2973:     } else {
 2974:         $r->print('<h1 class="LC_search_results">'.
 2975:                   mt('Results [_1] to [_2] out of [_3]',
 2976:                      $min,$max,$total_results).
 2977:                   "</h1>\n");
 2978:     }
 2979:     ##
 2980:     ## Get results from MySQL table
 2981:     my $sort_command  = 'id>='.$min.' AND id<='.$max;
 2982:     my $order;
 2983:     if (exists($env{'form.sortorder'})) {
 2984:         if ($env{'form.sortorder'} eq 'asc') {
 2985:             $order = 'ASC';
 2986:         } elsif ($env{'form.sortorder'} eq 'desc') {
 2987:             $order = 'DESC';
 2988:         } else {
 2989:             $order = '';
 2990:         }
 2991:     } else {
 2992:         $order = '';
 2993:     }
 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.
 2998:             '  LIMIT '.($min-1).','.($max-$min+1);
 2999:     }
 3000:     my @Results = &Apache::lonmysql::get_rows($table,$sort_command);
 3001:     ##
 3002:     ## Loop through the results and output them.
 3003:     my $tabletype = 'metadata';
 3004:     if ($area eq 'portfolio') {
 3005:         $tabletype = 'portfolio_search';
 3006:     }
 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());
 3015:     foreach my $row (@Results) {
 3016:         if ($connection->aborted()) {
 3017:             &cleanup();
 3018:             return;
 3019:         }
 3020:         my %Fields = %{&parse_row($tabletype,@$row)};
 3021:         my $output;
 3022:         if (! defined($Fields{'title'}) || $Fields{'title'} eq '') {
 3023:             $Fields{'title'} = 'Untitled';
 3024:         }
 3025:         my $prefix=&catalogmode_output($Fields{'title'},$Fields{'url'},
 3026:                                        $Fields{'id'},$checkbox_num++);
 3027:         # Render the result into html
 3028:         $output.= &$viewfunction($prefix,%Fields);
 3029:         # Print them out as they come in.
 3030:         $r->print(&Apache::loncommon::start_data_table_row()
 3031:                  .'<td>'
 3032:                  .$output
 3033:                  .'</td>'
 3034:                  .&Apache::loncommon::end_data_table_row()
 3035:         );
 3036:         $r->rflush();
 3037:     }
 3038:     $r->print(&Apache::loncommon::end_data_table());
 3039:     if (@Results < 1) {
 3040:         $r->print('<p class="LC_info">'
 3041:                  .&mt('There were no results matching your query.')
 3042:                  .'</p>');
 3043:     } else {
 3044:         $r->print(
 3045:             &prev_next_buttons($min,$env{'form.show'},$total_results,
 3046:                                 "table=".$env{'form.table'}.
 3047:                                 "&amp;phase=results".
 3048:                                 "&amp;persistent_db_id=".
 3049:                                 $env{'form.persistent_db_id'})
 3050:         );
 3051:     }
 3052:     $r->print('</form></div>'.&Apache::loncommon::end_page());
 3053:     $r->rflush();
 3054:     untie %groupsearch_db if (tied(%groupsearch_db));
 3055:     return;
 3056: }
 3057: 
 3058: ######################################################################
 3059: ######################################################################
 3060: 
 3061: =pod
 3062: 
 3063: =item &catalogmode_output($title,$url,$fnum,$checkbox_num)
 3064: 
 3065: Returns html needed for the various catalog modes.  Gets inputs from
 3066: $env{'form.catalogmode'}.  Stores data in %groupsearch_db.
 3067: 
 3068: =cut
 3069: 
 3070: ######################################################################
 3071: ######################################################################
 3072: sub catalogmode_output {
 3073:     my $output = '';
 3074:     my ($title,$url,$fnum,$checkbox_num) = @_;
 3075:     if ($env{'form.catalogmode'} eq 'interactive') {
 3076:         $title=~ s/\'/\\\'/g;
 3077:         if ($env{'form.catalogmode'} eq 'interactive') {
 3078:             $output.=<<END 
 3079: <font size='-1'><input type="button" name="returnvalues" value="select"
 3080: onclick="javascript:select_data('$title','$url')" />
 3081: </font>
 3082: END
 3083:         }
 3084:     } elsif ($env{'form.catalogmode'} eq 'import') {
 3085:         $groupsearch_db{"pre_${fnum}_link"}=$url;
 3086:         $groupsearch_db{"pre_${fnum}_title"}=$title;
 3087:         $output.=<<END;
 3088: <font size='-1'>
 3089: <input type="checkbox" name="returnvalues" value="select"
 3090: onclick="javascript:queue($checkbox_num,$fnum)" />
 3091: </font>
 3092: END
 3093:     }
 3094:     return $output;
 3095: }
 3096: ######################################################################
 3097: ######################################################################
 3098: 
 3099: =pod
 3100: 
 3101: =item &parse_row()
 3102: 
 3103: Parse a row returned from the database.
 3104: 
 3105: =cut
 3106: 
 3107: ######################################################################
 3108: ######################################################################
 3109: sub parse_row {
 3110:     my ($tabletype,@Row) = @_;
 3111:     my %Fields;
 3112:     if (! scalar(@Datatypes)) {
 3113:         &set_up_table_structure($tabletype);
 3114:     }
 3115:     for (my $i=0;$i<=$#Row;$i++) {
 3116:         $Fields{$Datatypes[$i]->{'name'}}=&unescape($Row[$i]);
 3117:     }
 3118:     $Fields{'language'} = 
 3119:         &Apache::loncommon::languagedescription($Fields{'language'});
 3120:     $Fields{'copyrighttag'} =
 3121:         &Apache::loncommon::copyrightdescription($Fields{'copyright'});
 3122:     $Fields{'mimetag'} =
 3123:         &Apache::loncommon::filedescription($Fields{'mime'});
 3124:     return \%Fields;
 3125: }
 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 
 3135: with keys according to column labels
 3136: 
 3137: In addition, the following tags are set by calling the appropriate 
 3138: lonnet function: 'language', 'copyrighttag', 'mimetag'.
 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 {
 3149:     my ($result,$hostname,$tabletype) = @_;
 3150:     # conclude from self to others regarding fields
 3151:     my %Fields=&LONCAPA::lonmetadata::metadata_col_to_hash
 3152:         ($tabletype,
 3153:          map {
 3154:             &unescape($_);
 3155:          } (split(/\,/,$result)) );
 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;
 3175:     if ($env{'form.customshow'}) {
 3176:         $customshow=$env{'form.customshow'};
 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\=//;
 3192:             my ($k,$v)=map {&unescape($_);
 3193:                         } split(/\,/,$tmp);
 3194:             $customhash{$k}=$v;
 3195:         }
 3196:     }
 3197:     return ($extrashow,\@customfields,\%customhash);
 3198: }
 3199: 
 3200: ######################################################################
 3201: ######################################################################
 3202: 
 3203: =pod
 3204: 
 3205: =item &search_results_header()
 3206: 
 3207: Output the proper html headers and javascript code to deal with different 
 3208: calling modes.
 3209: 
 3210: Takes most inputs directly from %env, except $mode.  
 3211: 
 3212: =over 4
 3213: 
 3214: =item $mode is either (at this writing) 'Basic' or 'Advanced'
 3215: 
 3216: =back
 3217: 
 3218: The following environment variables are checked:
 3219: 
 3220: =over 4
 3221: 
 3222: =item 'form.catalogmode' 
 3223: 
 3224: Checked for 'interactive' and 'import'.
 3225: 
 3226: =item 'form.mode'
 3227: 
 3228: Checked for existance & 'edit' mode.
 3229: 
 3230: =item 'form.form'
 3231: 
 3232: Contains the name of the form that has the input fields to set
 3233: 
 3234: =item 'form.element'
 3235: 
 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: 
 3242: =back
 3243: 
 3244: =cut
 3245: 
 3246: ######################################################################
 3247: ######################################################################
 3248: sub search_results_header {
 3249:     my ($importbutton,$closebutton) = @_;
 3250: 
 3251:     my $js;
 3252:     # output beginning of search page
 3253:     # conditional output of script functions dependent on the mode in
 3254:     # which the search was invoked
 3255:     if ($env{'form.catalogmode'} eq 'interactive'){
 3256: 	if (! exists($env{'form.mode'}) || $env{'form.mode'} ne 'edit') {
 3257:             $js.=<<SCRIPT;
 3258: <script type="text/javascript">
 3259: // <![CDATA[
 3260:     function select_data(title,url) {
 3261: 	changeTitle(title);
 3262: 	changeURL(url);
 3263: 	parent.close();
 3264:     }
 3265:     function changeTitle(val) {
 3266: 	if (parent.opener.inf.document.forms.resinfo.elements.t) {
 3267: 	    parent.opener.inf.document.forms.resinfo.elements.t.value=val;
 3268: 	}
 3269:     }
 3270:     function changeURL(val) {
 3271: 	if (parent.opener.inf.document.forms.resinfo.elements.u) {
 3272: 	    parent.opener.inf.document.forms.resinfo.elements.u.value=val;
 3273: 	}
 3274:     }
 3275: // ]]>
 3276: </script>
 3277: SCRIPT
 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'};
 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: 
 3298:             $js.=<<SCRIPT;
 3299: <script type="text/javascript">
 3300: // <![CDATA[
 3301: function select_data(title,url) {
 3302:     changeURL(url);
 3303:     changeTitle(title);
 3304:     parent.close();
 3305: }
 3306: $changetitle
 3307: function changeURL(val) {
 3308:     if (parent.targetwin.document) {
 3309:         parent.targetwin.document.forms["$form"].elements["$element"].value=val;
 3310:     } else {
 3311: 	var url = 'forms[\"$form\"].elements[\"$element\"].value';
 3312:         alert("Unable to transfer data to "+url);
 3313:     }
 3314: }
 3315: // ]]>
 3316: </script>
 3317: SCRIPT
 3318:         }
 3319:     }
 3320:     my $inhibit_menu = "&".&Apache::loncommon::inhibit_menu_check();
 3321:     $js.=<<SCRIPT if $env{'form.catalogmode'} eq 'import';
 3322: <script type="text/javascript">
 3323: // <![CDATA[
 3324:     function queue(checkbox_num,val) {
 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) {
 3328:                 parent.statusframe.document.forms.statusform.elements.acts.value +='1a'+val+'b';
 3329:             } else {
 3330:                 parent.statusframe.document.forms.statusform.elements.acts.value +='0a'+val+'b';
 3331:             }
 3332:         } else {
 3333:             if (document.forms.results.returnvalues.checked) {
 3334:                 parent.statusframe.document.forms.statusform.elements.acts.value +='1a'+val+'b';
 3335:             } else {
 3336:                 parent.statusframe.document.forms.statusform.elements.acts.value +='0a'+val+'b';
 3337:             }
 3338:         }
 3339:     }
 3340:     function select_group() {
 3341: 	parent.window.location=
 3342:     "/adm/groupsort?mode=$env{'form.mode'}&catalogmode=import$inhibit_menu&acts="+
 3343: 	    parent.statusframe.document.forms.statusform.elements.acts.value;
 3344:     }
 3345: // ]]>
 3346: </script>
 3347: SCRIPT
 3348: 
 3349:     $js.=<<SCRIPT;
 3350: <script type="text/javascript">
 3351:     \$(document).ready(function() {
 3352:         parent.done_loading_results();
 3353:     });
 3354: </script>
 3355: SCRIPT
 3356: 
 3357:     my $start_page  = &Apache::loncommon::start_page(undef,$js,
 3358: 						     {'only_body' =>1,
 3359:                                                       'add_wishlist' =>1,
 3360:                                                       'add_modal' =>1});
 3361:     my $result=<<END;
 3362: $start_page
 3363: <div class="LC_landmark" role="main">
 3364: <form name="results" method="post" action="/adm/searchcat">
 3365: $importbutton
 3366: END
 3367:     return $result;
 3368: }
 3369: 
 3370: sub results_link {
 3371:     my $basic_link   = "/adm/searchcat?"."&amp;table=".$env{'form.table'}.
 3372:         "&amp;area=".$env{'form.area'}.
 3373:         "&amp;catalogmode=".$env{'form.catalogmode'}.
 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";
 3377:     return $results_link;
 3378: }
 3379: 
 3380: ######################################################################
 3381: ######################################################################
 3382: sub print_frames_interface {
 3383:     my $r = shift;
 3384:     my $basic_link = "/adm/searchcat?table=".$env{'form.table'}.
 3385:         "&amp;area=".$env{'form.area'}.
 3386:         "&amp;catalogmode=".$env{'form.catalogmode'}.
 3387:         "&amp;persistent_db_id=".$env{'form.persistent_db_id'};
 3388:     my $run_search_link = $basic_link."&amp;phase=run_search";
 3389:     my $results_link = &results_link();
 3390:     my $js = <<JS;
 3391: <script type="text/javascript">
 3392: // <![CDATA[
 3393: var targetwin = opener;
 3394: var queue = '';
 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: }
 3415: // ]]>
 3416: </script>
 3417: JS
 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: 
 3428:     my $result = <<"ENDFRAMES";
 3429: $start_page
 3430:     <frame name="statusframe"  src="$run_search_link">
 3431:     <frame name="resultsframe" src="$results_link">
 3432: $end_page
 3433: ENDFRAMES
 3434: 
 3435:     $r->print($result);
 3436:     return;
 3437: }
 3438: 
 3439: ######################################################################
 3440: ######################################################################
 3441: 
 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: 
 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: 
 3499: =pod 
 3500: 
 3501: =item Metadata Viewing Functions
 3502: 
 3503: Output is a HTML-ified string.
 3504: 
 3505: Input arguments are title, author, subject, url, keywords, version,
 3506: notes, short abstract, mime, language, creation date,
 3507: last revision date, owner, copyright, hostname, and
 3508: extra custom metadata to show.
 3509: 
 3510: =over 4
 3511: 
 3512: =item &detailed_citation_view() 
 3513: 
 3514: =cut
 3515: 
 3516: ######################################################################
 3517: ######################################################################
 3518: sub detailed_citation_view {
 3519:     my ($prefix,%values) = @_;
 3520:     my $result;
 3521:     my $jumpurl=$values{'url'};
 3522:     $jumpurl=~s|^/ext/|http://|;
 3523:     $result .=
 3524:         '<b>'.$prefix.
 3525:         '<img src="'.&Apache::loncommon::icon($values{'url'}).'" alt="" />'.'&nbsp;'.
 3526:         '<a href="'.$jumpurl.'?inhibitmenu=yes" '.
 3527:         'target="preview" onclick="openMyModal(this.href, 500, 500, \'yes\');return false;">'.$values{'title'}."</a></b>\n".
 3528:         &display_tools($values{'title'}, $jumpurl).
 3529:         "<p>\n".
 3530:         '<b>'.$values{'author'}.'</b>,'.
 3531:         ' <i>'.$values{'owner'}.'</i><br />';
 3532:     foreach my $field 
 3533:         (
 3534:          { name=>'url',
 3535:            translate => '<b>URL:</b>&nbsp;[_1]',
 3536:            special => 'url link',},
 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]',},
 3549:          { name=>'count',
 3550:            format => "%d",
 3551:            translate => '<b>Access Count:</b>&nbsp;[_1]',},
 3552:          { name=>'stdno',
 3553:            format => "%d",
 3554:            translate => '<b>Number of Students:</b>&nbsp;[_1]',},
 3555:          { name=>'avetries',
 3556:            format => "%.2f",
 3557:            translate => '<b>Average Tries:</b>&nbsp;[_1]',},
 3558:          { name=>'disc',
 3559:            format => "%.2f",
 3560:            translate => '<b>Degree of Discrimination:</b>&nbsp;[_1]',},
 3561:          { name=>'difficulty',
 3562:            format => "%.2f",
 3563:            translate => '<b>Degree of Difficulty:</b>&nbsp;[_1]',},
 3564:          { name=>'clear',
 3565:            format => "%.2f",
 3566:            translate => '<b>Clear:</b>&nbsp;[_1]',},
 3567:          { name=>'depth',
 3568:            format => "%.2f",
 3569:            translate => '<b>Depth:</b>&nbsp;[_1]',},
 3570:          { name=>'helpful',
 3571:            format => "%.2f",
 3572:            translate => '<b>Helpful:</b>&nbsp;[_1]',},
 3573:          { name=>'correct',
 3574:            format => "%.2f",
 3575:            translate => '<b>Correct:</b>&nbsp;[_1]',},
 3576:          { name=>'technical',
 3577:            format => "%.2f",
 3578:            translate => '<b>Technical:</b>&nbsp;[_1]',},
 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',},
 3585:          { name=>'sequsage_list',
 3586:            type => 'list',
 3587:            translate => 'Resources using or importing resource',},
 3588:          ) {
 3589:         next if (! exists($values{$field->{'name'}}) ||
 3590:                  $values{$field->{'name'}} eq '');
 3591:         if (exists($field->{'type'}) && $field->{'type'} eq 'list') {
 3592:             $result .= '<b>'.&mt($field->{'translate'}).'</b>';
 3593:             foreach my $item (split(',',$values{$field->{'name'}})){
 3594:                 $item = &Apache::lonnet::clutter($item);
 3595:                 $result .= '<br />'.&display_url($item,1).'<br />';
 3596:             }
 3597:         } elsif (exists($field->{'format'}) && $field->{'format'} ne ''){
 3598:             $result.= &mt($field->{'translate'},
 3599:                           sprintf($field->{'format'},
 3600:                                   $values{$field->{'name'}}))."<br />\n";
 3601:         } else {
 3602:             if ($field->{'special'} eq 'url link') {
 3603:                 $result .= '<br />'.&display_url($jumpurl,1).'<br />';
 3604:             } else {
 3605:                 $result.= &mt($field->{'translate'},
 3606:                               $values{$field->{'name'}});
 3607:             }
 3608:             $result .= "<br />\n";
 3609:         }
 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>';
 3617:     }
 3618:     return $result;
 3619: }
 3620: 
 3621: sub detailed_citation_preview {
 3622:     my ($prefix,%values)=@_;
 3623:     return &detailed_citation_view($prefix,%values).
 3624:            '</td><td>'.
 3625:            &Apache::lonindexer::showpreview($values{'url'});
 3626: }
 3627: 
 3628: 
 3629: ######################################################################
 3630: ######################################################################
 3631: 
 3632: =pod 
 3633: 
 3634: =item &summary_view() 
 3635: 
 3636: =cut
 3637: ######################################################################
 3638: ######################################################################
 3639: sub summary_view {
 3640:     my ($prefix,%values) = @_;
 3641:     my $icon=&Apache::loncommon::icon($values{'url'});
 3642:     my $result=qq{$prefix<img src="$icon" alt="" />};
 3643:     if (exists($env{'form.sortfield'}) && 
 3644:         $env{'form.sortfield'} !~ /^(default|
 3645:                                      author|
 3646:                                      url|
 3647:                                      title|
 3648:                                      owner|
 3649:                                      lastrevisiondate|
 3650:                                      copyright)$/x) {
 3651:         my $tmp = $values{$env{'form.sortfield'}};
 3652:         if (! defined($tmp)) { $tmp = 'undefined'; }
 3653:         $result .= '&nbsp;'.$tmp.'&nbsp;';
 3654:     }
 3655:     my $jumpurl=$values{'url'};
 3656:     $jumpurl=~s|^/ext/|http://|;
 3657:     my $link = '<br />'.&display_url($jumpurl,1).'<br />';
 3658:     $result .=
 3659:         '<a href="'.$jumpurl.'?inhibitmenu=yes"'.
 3660:         ' target="preview" onclick="openMyModal(this.href, 500, 500, \'yes\');return false;">'.$values{'title'}.'</a>'.
 3661:         &display_tools($values{'title'}, $jumpurl).<<END;
 3662: <br />
 3663: $link<br />
 3664: $values{'author'}, $values{'owner'} -- $values{'lastrevisiondate'}<br />
 3665: $values{'copyrighttag'}<br />
 3666: $values{'extrashow'}
 3667: END
 3668:     return $result;
 3669: }
 3670: 
 3671: sub summary_preview {
 3672:     my ($prefix,%values)=@_;
 3673:     return &summary_view($prefix,%values).
 3674:            '</td><td>'.
 3675:            &Apache::lonindexer::showpreview($values{'url'});
 3676: }
 3677: 
 3678: ######################################################################
 3679: ######################################################################
 3680: 
 3681: =pod 
 3682: 
 3683: =item &compact_view() 
 3684: 
 3685: =cut
 3686: 
 3687: ######################################################################
 3688: ######################################################################
 3689: sub compact_view {
 3690:     my ($prefix,%values) = @_;
 3691:     my $jumpurl=$values{'url'};
 3692:     $jumpurl=~s|^/ext/|http://|;
 3693: 
 3694:     my $link = &display_url($jumpurl,1);
 3695:     
 3696:     my $result = 
 3697:         $prefix.'<img src="'.&Apache::loncommon::icon($values{'url'}).'" alt="" />';
 3698:     if (exists($env{'form.sortfield'}) && 
 3699:         $env{'form.sortfield'} !~ /^(default|author|url|title)$/) {
 3700:         my $tmp = $values{$env{'form.sortfield'}};
 3701:         if (! defined($tmp)) { $tmp = 'undefined'; }
 3702:         $result .= '&nbsp;'.$tmp.'&nbsp;';
 3703:     }
 3704:     $jumpurl = &HTML::Entities::encode($jumpurl,'<>&"');
 3705:     $result.=' <span class="LC_nobreak">'.
 3706: 	'<a href="'.$jumpurl.'?inhibitmenu=yes" target="preview" onclick="openMyModal(this.href, 500, 500, \'yes\');return false;">'.
 3707:         &HTML::Entities::encode($values{'title'},'<>&"').'</a></span> '.
 3708:         &display_tools($values{'title'}, $jumpurl).
 3709: 	$link.' <b>'.$values{'author'}.'</b> ('.$values{'domain'}.')';
 3710:     return $result;
 3711: }
 3712: 
 3713: sub display_url {
 3714:     my ($url,$skiplast) = @_;
 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 {
 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;\""; 
 3727:         $link=&Apache::lonhtmlcommon::crumbs(
 3728:                   $url,
 3729:                   'preview',
 3730:                   '',
 3731:                   '',
 3732:                   $skiplast,$onclick).' ';
 3733:     }
 3734:     return $link;
 3735: }
 3736: 
 3737: ######################################################################
 3738: ######################################################################
 3739: 
 3740: =pod 
 3741: 
 3742: =item &fielded_format_view() 
 3743: 
 3744: =cut
 3745: 
 3746: ######################################################################
 3747: ######################################################################
 3748: sub fielded_format_view {
 3749:     my ($prefix,%values) = @_;
 3750:     my $icon=&Apache::loncommon::icon($values{'url'});
 3751:     my %Translated = &Apache::lonmeta::fieldnames();
 3752:     my $jumpurl=$values{'url'};
 3753:     $jumpurl=~s|^/ext/|http://|;
 3754: 
 3755:     my $result=<<END;
 3756: $prefix <img src="$icon" alt="" />
 3757: <dl>
 3758: <dt>URL:</dt>
 3759:     <dd><a href="$jumpurl?inhibitmenu=yes" 
 3760:          target='preview'>$values{'url'}</a>
 3761: END
 3762:     $result .=
 3763:         &display_tools($values{'title'}, $jumpurl).'
 3764:     </dd>';
 3765:     foreach my $field ('title','author','domain','subject','keywords','notes',
 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'};
 3785:     return $result;
 3786: }
 3787: 
 3788: ######################################################################
 3789: ######################################################################
 3790: 
 3791: =pod 
 3792: 
 3793: =item &xml_sgml_view() 
 3794: 
 3795: =back 
 3796: 
 3797: =cut
 3798: 
 3799: ######################################################################
 3800: ######################################################################
 3801: sub xml_sgml_view {
 3802:     my ($prefix,%values) = @_;
 3803:     my $xml = '<LonCapaResource>'."\n";
 3804:     # The usual suspects
 3805:     foreach my $field ('url','title','author','subject','keywords','notes','domain') {
 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";
 3851:     $xml = &HTML::Entities::encode($xml,'<>&');
 3852:     my $result=<<END;
 3853: $prefix
 3854: <pre>
 3855: $xml
 3856: </pre>
 3857: $values{'extrashow'}
 3858: END
 3859:     return $result;
 3860: }
 3861: 
 3862: ######################################################################
 3863: ######################################################################
 3864: 
 3865: =pod 
 3866: 
 3867: =item &filled() see if field is filled.
 3868: 
 3869: =cut
 3870: 
 3871: ######################################################################
 3872: ######################################################################
 3873: sub filled {
 3874:     my ($field)=@_;
 3875:     if ($field=~/\S/ && $field ne 'any') {
 3876:         return 1;
 3877:     } else {
 3878:         return 0;
 3879:     }
 3880: }
 3881: 
 3882: ######################################################################
 3883: ######################################################################
 3884: 
 3885: =pod 
 3886: 
 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') {
 3897:         $errorstring = &mt('Unable to understand the search phrase [_1]. Please modify your search.'
 3898:                            ,'<i>'.$env{'form.basicexp'}.'</i>');
 3899:     } else {
 3900:         $errorstring = &mt('Unable to understand the search phrase [_1]: [_2]'
 3901:                            ,'<i>'.$field.'</i>'
 3902:                            ,$env{'form.'.$field});
 3903:     }
 3904:     my $heading = &mt('Unparsed Field');
 3905:     my $revise  = &mt('Revise search request');
 3906:     # make query information persistent to allow for subsequent revision
 3907:     my $start_page = &Apache::loncommon::start_page('Search');
 3908:     my $end_page   = &Apache::loncommon::end_page();
 3909:     $r->print(<<ENDPAGE);
 3910: $start_page
 3911: <form method="post" action="/adm/searchcat">
 3912: $hidden_fields
 3913: $closebutton
 3914: <hr />
 3915: <h2>$heading</h2>
 3916: <p class="LC_warning">
 3917: $errorstring
 3918: </p>
 3919: <p>
 3920: <a href="/adm/searchcat?$parms&amp;persistent_db_id=$env{'form.persistent_db_id'}">$revise</a>
 3921: </p>
 3922: $end_page
 3923: ENDPAGE
 3924: }
 3925: 
 3926: ######################################################################
 3927: ######################################################################
 3928: 
 3929: =pod 
 3930: 
 3931: =item &output_blank_field_error()
 3932: 
 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: 
 3942: =cut
 3943: 
 3944: ######################################################################
 3945: ######################################################################
 3946: sub output_blank_field_error {
 3947:     my ($r,$closebutton,$parms,$hidden_fields)=@_;
 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.');
 3949:     my $revise = &mt('Revise Search Request');
 3950:     my $heading = &mt('Unactionable Search Query');
 3951:     my $start_page = &Apache::loncommon::start_page('Search');
 3952:     my $end_page   = &Apache::loncommon::end_page();
 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: 
 3962:     $r->print(<<ENDPAGE);
 3963: $start_page
 3964: <form method="post" action="/adm/searchcat">
 3965: $hidden_fields
 3966: $closebutton
 3967: </form>
 3968: <h2>$heading</h2>
 3969: <p class="LC_warning">
 3970: $errormsg
 3971: </p>
 3972: <p>
 3973: <a href="/adm/searchcat?$parms&amp;persistent_db_id=$env{'form.persistent_db_id'}">$revise</a>
 3974: </p>
 3975: $end_page
 3976: ENDPAGE
 3977:     return;
 3978: }
 3979: 
 3980: ######################################################################
 3981: ######################################################################
 3982: 
 3983: =pod 
 3984: 
 3985: =item &output_date_error()
 3986: 
 3987: Output a full html page with an error message.
 3988: 
 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: 
 3995: =cut
 3996: 
 3997: ######################################################################
 3998: ######################################################################
 3999: sub output_date_error {
 4000:     my ($r,$message,$closebutton,$hidden_fields)=@_;
 4001:     # make query information persistent to allow for subsequent revision
 4002:     my $start_page = &Apache::loncommon::start_page('Search');
 4003:     my $end_page   = &Apache::loncommon::end_page();
 4004:     my $heading = &mt('Error');
 4005:     $r->print(<<RESULTS);
 4006: $start_page
 4007: <form method="post" action="/adm/searchcat">
 4008: $hidden_fields
 4009: <input type='button' value='Revise search request'
 4010: onclick='this.form.submit();' />
 4011: $closebutton
 4012: </form>
 4013: <hr />
 4014: <h3>$heading</h3>
 4015: <p class="LC_error">
 4016: $message
 4017: </p>
 4018: $end_page
 4019: RESULTS
 4020: }
 4021: 
 4022: ######################################################################
 4023: ######################################################################
 4024: 
 4025: =pod 
 4026: 
 4027: =item &start_fresh_session()
 4028: 
 4029: Cleans the global %groupsearch_db by removing all fields which begin with
 4030: 'pre_' or 'store'.
 4031: 
 4032: =cut
 4033: 
 4034: ######################################################################
 4035: ######################################################################
 4036: sub start_fresh_session {
 4037:     delete $groupsearch_db{'mode_catalog'};
 4038:     foreach (keys(%groupsearch_db)) {
 4039:         if ($_ =~ /^pre_/) {
 4040:             delete $groupsearch_db{$_};
 4041:         }
 4042:         if ($_ =~ /^store/) {
 4043: 	    delete $groupsearch_db{$_};
 4044: 	}
 4045:     }
 4046: }
 4047: 
 4048: 1;
 4049: 
 4050: sub cleanup {
 4051:     if (tied(%groupsearch_db)) {
 4052:         unless (untie(%groupsearch_db)) {
 4053: 	  &Apache::lonnet::logthis('Failed cleanup searchcat: groupsearch_db');
 4054:         }
 4055:     }
 4056:     &Apache::lonmysql::disconnect_from_db();
 4057:     return OK;
 4058: }
 4059: 
 4060: __END__
 4061: 
 4062: =pod
 4063: 
 4064: =back 
 4065: 
 4066: =cut

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