File:  [LON-CAPA] / loncom / interface / lonsearchcat.pm
Revision 1.230.2.1: download - view: text, annotated - select for diffs
Wed Jan 19 20:22:36 2005 UTC (19 years, 4 months ago) by albertel
Branches: version_1_2_X
Diff to branchpoint 1.230: preferred, unified
- backport 1.235

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

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