File:  [LON-CAPA] / loncom / interface / lonsearchcat.pm
Revision 1.347: download - view: text, annotated - select for diffs
Thu Jun 18 15:10:52 2015 UTC (8 years, 11 months ago) by damieng
Branches: MAIN
CVS tags: HEAD
search: fixed bug 6774 + opening previews in a modal, as with import

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

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