File:  [LON-CAPA] / loncom / interface / lonsearchcat.pm
Revision 1.311: download - view: text, annotated - select for diffs
Fri Jul 3 08:18:48 2009 UTC (14 years, 10 months ago) by bisitz
Branches: MAIN
CVS tags: HEAD
Added breadcrumbs to Course Search

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

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