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

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

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