File:  [LON-CAPA] / loncom / interface / lonsearchcat.pm
Revision 1.320: download - view: text, annotated - select for diffs
Sat Feb 13 01:12:16 2010 UTC (14 years, 3 months ago) by raeburn
Branches: MAIN
CVS tags: version_2_9_99_0, HEAD
- Add missing & to catalogmode element in query strings for breadcrumb links.

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

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