File:  [LON-CAPA] / loncom / interface / lonsearchcat.pm
Revision 1.327: download - view: text, annotated - select for diffs
Mon Jan 17 20:18:02 2011 UTC (13 years, 4 months ago) by www
Branches: MAIN
CVS tags: HEAD
"Search Course" was only inside of searchcat because the Remote did not
have enough buttons.

Separate the two, incorporate content search under "Content"

Declutter lonsearchcat a little bit before necessary major cleanup.

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

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