File:  [LON-CAPA] / loncom / interface / lonsearchcat.pm
Revision 1.331.4.3: download - view: text, annotated - select for diffs
Mon Dec 17 13:54:25 2012 UTC (11 years, 5 months ago) by raeburn
Branches: version_2_11_X
Diff to branchpoint 1.331: preferred, unified
- For 2.11
  - "Stored links" instead of "wishlist".

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

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