File:  [LON-CAPA] / loncom / interface / lonsearchcat.pm
Revision 1.278: download - view: text, annotated - select for diffs
Wed Dec 6 22:22:37 2006 UTC (17 years, 5 months ago) by albertel
Branches: MAIN
CVS tags: version_2_3_X, version_2_3_2, version_2_3_1, version_2_3_0, version_2_2_99_1, version_2_2_99_0, HEAD
- more re fix ups

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

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