File:  [LON-CAPA] / loncom / interface / lonsearchcat.pm
Revision 1.293: download - view: text, annotated - select for diffs
Wed May 28 21:07:29 2008 UTC (15 years, 11 months ago) by www
Branches: MAIN
CVS tags: HEAD
NSDL is dead.

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

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