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

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

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