File:  [LON-CAPA] / loncom / interface / lonsearchcat.pm
Revision 1.360: download - view: text, annotated - select for diffs
Sat Dec 30 03:52:33 2023 UTC (4 months, 2 weeks ago) by raeburn
Branches: MAIN
CVS tags: version_2_12_X, HEAD
- Wording Change

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

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