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

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

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