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

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

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