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

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

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