File:  [LON-CAPA] / loncom / interface / lonsearchcat.pm
Revision 1.331.4.10: download - view: text, annotated - select for diffs
Sun Feb 23 22:16:20 2014 UTC (10 years, 2 months ago) by raeburn
Branches: version_2_11_X
CVS tags: version_2_11_0_RC3, version_2_11_0
Diff to branchpoint 1.331: preferred, unified
- For 2.11
  - Backport 1.341, 1.342.

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

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