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

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

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