File:  [LON-CAPA] / loncom / interface / lonsearchcat.pm
Revision 1.277: download - view: text, annotated - select for diffs
Wed Sep 27 19:32:11 2006 UTC (17 years, 8 months ago) by raeburn
Branches: MAIN
CVS tags: HEAD
Some wording changes in breadcrumbs. Advanced search now functional for portfolios.  Needs additional work on searching based on added metadata fields.

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

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