File:  [LON-CAPA] / loncom / interface / lonsearchcat.pm
Revision 1.331.4.16.2.1: download - view: text, annotated - select for diffs
Sun May 29 21:59:55 2022 UTC (2 years ago) by raeburn
Branches: version_2_11_4_msu
Diff to branchpoint 1.331.4.16: preferred, unified
- For 2.11.4 (modified)
  Include changes in rev. 1.355, 1.356

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

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