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

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

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