File:  [LON-CAPA] / loncom / interface / lonsearchcat.pm
Revision 1.324: download - view: text, annotated - select for diffs
Sun Jun 6 02:40:30 2010 UTC (13 years, 11 months ago) by raeburn
Branches: MAIN
CVS tags: version_2_10_X, version_2_10_1, version_2_10_0_RC2, version_2_10_0_RC1, version_2_10_0, loncapaMITrelate_1, HEAD
- Bug 6251.
  - Third arg is now a ref to a hash, instead of a hash.
  - New (optional) fourth arg, is an additional attribute for the
    select tag, e.g., an onchange action.
- Update calls to loncommon::select_form() accordingly.

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

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