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

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

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