Annotation of loncom/interface/lonsearchcat.pm, revision 1.222

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

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