--- loncom/interface/lonsearchcat.pm 2002/07/29 21:53:57 1.146 +++ loncom/interface/lonsearchcat.pm 2005/02/17 08:29:43 1.238 @@ -1,7 +1,7 @@ # The LearningOnline Network with CAPA # Search Catalog # -# $Id: lonsearchcat.pm,v 1.146 2002/07/29 21:53:57 matthew Exp $ +# $Id: lonsearchcat.pm,v 1.238 2005/02/17 08:29:43 albertel Exp $ # # Copyright Michigan State University Board of Trustees # @@ -25,14 +25,6 @@ # # http://www.lon-capa.org/ # -# YEAR=2001 -# 3/8, 3/12, 3/13, 3/14, 3/15, 3/19 Scott Harrison -# 3/20, 3/21, 3/22, 3/26, 3/27, 4/2, 8/15, 8/24, 8/25 Scott Harrison -# 10/12,10/14,10/15,10/16,11/28,11/29,12/10,12/12,12/16 Scott Harrison -# YEAR=2002 -# 1/17 Scott Harrison -# 6/17 Matthew Hall -# ############################################################################### ############################################################################### @@ -56,7 +48,7 @@ described at http://www.lon-capa.org. lonsearchcat presents the user with an interface to search the LON-CAPA digital library. lonsearchcat also initiates the execution of a search by sending the search parameters to LON-CAPA servers. The progress of -search (on a server basis) is displayed to the user in a seperate window. +search (on a server basis) is displayed to the user in a separate window. =head1 Internals @@ -67,123 +59,85 @@ search (on a server basis) is displayed ############################################################################### ############################################################################### -############################################################################### -## ## -## ORGANIZATION OF THIS PERL MODULE ## -## ## -## 1. Modules used by this module ## -## 2. Variables used throughout the module ## -## 3. handler subroutine called via Apache and mod_perl ## -## 4. Other subroutines ## -## ## -############################################################################### - package Apache::lonsearchcat; -# ------------------------------------------------- modules used by this module use strict; -use Apache::Constants qw(:common); +use Apache::Constants qw(:common :http); use Apache::lonnet(); use Apache::File(); use CGI qw(:standard); use Text::Query; -use DBI; use GDBM_File; use Apache::loncommon(); use Apache::lonmysql(); - -# ---------------------------------------- variables used throughout the module +use Apache::lonmeta; +use Apache::lonhtmlcommon; +use Apache::lonlocal; +use LONCAPA::lonmetadata(); +use HTML::Entities(); +use Parse::RecDescent; +use Apache::lonnavmaps; ###################################################################### ###################################################################### - -=pod - -=item Global variables - -=over 4 - -=item $importbutton - -button to take the select results and go to group sorting - -=item %groupsearch_db - -Database hash used to save values for the groupsearch RAT interface. - -=item $diropendb - -The full path to the (temporary) search database file. This is set and -used in &handler() and is also used in &output_results(). - -=item %Views - -Hash which associates an output view description with the function -that produces it. Adding a new view type should be as easy as -adding a line to the definition of this hash and making sure the function -takes the proper parameters. - -=back - -=cut - +## +## Global variables +## ###################################################################### ###################################################################### - -# -- dynamically rendered interface components -my $importbutton; # button to take the selected results and go to group sorting - -# -- miscellaneous variables -my %groupsearch_db; # database hash -my $diropendb = ""; # db file -# View Description Function Pointer -my %Views = ("Detailed Citation View" => \&detailed_citation_view, - "Summary View" => \&summary_view, - "Fielded Format" => \&fielded_format_view, - "XML/SGML" => \&xml_sgml_view ); -my %persistent_db; -my $hidden_fields; -###################################################################### -###################################################################### - -=pod - -=item &handler() - main handler invoked by httpd child - -=item Variables - -=over 4 - -=item $hidden - -holds 'hidden' html forms - -=item $scrout - -string that holds portions of the screen output - -=back - -=cut +my %groupsearch_db; # Database hash used to save values for the + # groupsearch RAT interface. +my %persistent_db; # gdbm hash which holds data which is supposed to + # persist across calls to lonsearchcat.pm + +# The different view modes and associated functions + +my %Views = ("detailed" => \&detailed_citation_view, + "summary" => \&summary_view, + "fielded" => \&fielded_format_view, + "xml" => \&xml_sgml_view, + "compact" => \&compact_view); ###################################################################### ###################################################################### sub handler { my $r = shift; +# &set_defaults(); + # + # set form defaults + # + my $hidden_fields;# Hold all the hidden fields used to keep track + # of the search system state + my $importbutton; # button to take the selected results and go to group + # sorting + my $diropendb; # The full path to the (temporary) search database file. + # This is set and used in &handler() and is also used in + # &output_results(). + my $bodytag; # LON-CAPA standard body tag, gotten from + # &Apache::lonnet::bodytag. + # No title, no table, just a tag. + + my $loaderror=&Apache::lonnet::overloaderror($r); + if ($loaderror) { return $loaderror; } # my $closebutton; # button that closes the search window # This button is different for the RAT compared to # normal invocation. # - $r->content_type('text/html'); + &Apache::loncommon::content_type($r,'text/html'); $r->send_http_header; return OK if $r->header_only; + ## + ## Prevent caching of the search interface window. Hopefully this means + ## we will get the launch=1 passed in a little more. + &Apache::loncommon::no_cache($r); ## ## Pick up form fields passed in the links. ## &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'}, ['catalogmode','launch','acts','mode','form','element','pause', - 'phase','persistent_db_id','table','start','show']); + 'phase','persistent_db_id','table','start','show', + 'cleargroupsort','titleelement']); ## ## The following is a trick - we wait a few seconds if asked to so ## the daemon running the search can get ahead of the daemon @@ -191,55 +145,132 @@ sub handler { ## this once, so the pause indicator is deleted ## if (exists($ENV{'form.pause'})) { - sleep(5); + sleep(1); delete($ENV{'form.pause'}); } ## ## Initialize global variables ## my $domain = $r->dir_config('lonDefDomain'); - $diropendb= "/home/httpd/perl/tmp/".&Apache::lonnet::escape($domain). - "\_".&Apache::lonnet::escape($ENV{'user.name'})."_searchcat.db"; + $diropendb= "/home/httpd/perl/tmp/". + "$ENV{'user.domain'}_$ENV{'user.name'}_searchcat.db"; # # set the name of the persistent database # $ENV{'form.persistent_db_id'} can only have digits in it. if (! exists($ENV{'form.persistent_db_id'}) || - $ENV{'form.persistent_db_id'} =~ /\D/ ) { + ($ENV{'form.persistent_db_id'} =~ /\D/) || + ($ENV{'form.launch'} eq '1')) { $ENV{'form.persistent_db_id'} = time; } + $bodytag=&Apache::loncommon::bodytag(undef,undef,undef,1); my $persistent_db_file = "/home/httpd/perl/tmp/". &Apache::lonnet::escape($domain). '_'.&Apache::lonnet::escape($ENV{'user.name'}). '_'.$ENV{'form.persistent_db_id'}.'_persistent_search.db'; ## - &get_persistent_form_data($r,$persistent_db_file); + &Apache::lonhtmlcommon::clear_breadcrumbs(); + if (exists($ENV{'request.course.id'}) && $ENV{'request.course.id'} ne '') { + &Apache::lonhtmlcommon::add_breadcrumb + ({href=>'/adm/searchcat?'. + 'catalogmode='.$ENV{'form.catalogmode'}. + '&launch='.$ENV{'form.launch'}. + '&mode='.$ENV{'form.mode'}, + text=>"Course and Catalog Search", + target=>'_top', + bug=>'Searching',}); + } else { + &Apache::lonhtmlcommon::add_breadcrumb + ({href=>'/adm/searchcat?'. + 'catalogmode='.$ENV{'form.catalogmode'}. + '&launch='.$ENV{'form.launch'}. + '&mode='.$ENV{'form.mode'}, + text=>"Catalog Search", + target=>'_top', + bug=>'Searching',}); + } + # + if ($ENV{'form.phase'} !~ m/(basic|adv|course)_search/) { + if (! &get_persistent_form_data($persistent_db_file)) { + if ($ENV{'form.phase'} =~ /(run_search|results)/) { + &Apache::lonnet::logthis('lonsearchcat:'. + 'Unable to recover data from '. + $persistent_db_file); + my $html=&Apache::lonxml::xmlbegin(); + $r->print(< +LON-CAPA Search Error +$bodytag +We were unable to retrieve data describing your search. This is a serious +error and has been logged. Please alert your LON-CAPA administrator. + + +END + return OK; + } + } + } else { + &clean_up_environment(); + } ## ## Clear out old values from groupsearch database ## untie %groupsearch_db if (tied(%groupsearch_db)); - if ($ENV{'form.launch'} eq '1') { - if (tie(%groupsearch_db,'GDBM_File',$diropendb,&GDBM_WRCREAT,0640)) { + if (($ENV{'form.cleargroupsort'} eq '1') || + (($ENV{'form.launch'} eq '1') && + ($ENV{'form.catalogmode'} eq 'groupsearch'))) { + if (tie(%groupsearch_db,'GDBM_File',$diropendb,&GDBM_WRCREAT(),0640)) { &start_fresh_session(); untie %groupsearch_db; + delete($ENV{'form.cleargroupsort'}); } else { - $r->print('Unable to tie hash to db '. - 'file'); + # This is a stupid error to give to the user. + # It really tells them nothing. + my $html=&Apache::lonxml::xmlbegin(); + $r->print($html.''.$bodytag. + 'Unable to tie hash to db file'); return OK; } } ## - ## Configure dynamic components of interface + ## Configure hidden fields ## $hidden_fields = ''; + $ENV{'form.persistent_db_id'}.'" />'."\n"; + if (exists($ENV{'form.catalogmode'})) { + $hidden_fields .= &hidden_field('catalogmode'); + } + if (exists($ENV{'form.form'})) { + $hidden_fields .= &hidden_field('form'); + } + if (exists($ENV{'form.element'})) { + $hidden_fields .= &hidden_field('element'); + } + if (exists($ENV{'form.titleelement'})) { + $hidden_fields .= &hidden_field('titleelement'); + } + if (exists($ENV{'form.mode'})) { + $hidden_fields .= &hidden_field('mode'); + } + ## + ## Configure dynamic components of interface ## if ($ENV{'form.catalogmode'} eq 'interactive') { - $closebutton=""."\n"; + $closebutton=" -END + $closebutton=" @@ -252,73 +283,396 @@ END ## Sanity checks on form elements ## if (!defined($ENV{'form.viewselect'})) { - $ENV{'form.viewselect'} ="Detailed Citation View"; + if (($ENV{'form.catalogmode'} eq 'groupsearch') || + ($ENV{'form.catalogmode'} eq 'interactive')) { + $ENV{'form.viewselect'} ="Compact View"; + } else { + $ENV{'form.viewselect'} ="Detailed Citation View"; + } + } + $ENV{'form.phase'} = 'disp_basic' if (! exists($ENV{'form.phase'})); + $ENV{'form.show'} = 20 if (! exists($ENV{'form.show'})); + # + $ENV{'form.searchmode'} = 'basic' if (! exists($ENV{'form.searchmode'})); + if ($ENV{'form.phase'} eq 'adv_search' || + $ENV{'form.phase'} eq 'disp_adv') { + $ENV{'form.searchmode'} = 'advanced'; + } elsif ($ENV{'form.phase'} eq 'course_search') { + $ENV{'form.searchmode'} = 'course_search'; + } + # + if ($ENV{'form.searchmode'} eq 'advanced') { + &Apache::lonhtmlcommon::add_breadcrumb + ({href=>'/adm/searchcat?phase=disp_adv&'. + 'catalogmode='.$ENV{'form.catalogmode'}. + '&launch='.$ENV{'form.launch'}. + '&mode='.$ENV{'form.mode'}, + text=>"Advanced Search", + bug=>'Searching',}); + } elsif ($ENV{'form.searchmode'} eq 'course search') { + &Apache::lonhtmlcommon::add_breadcrumb + ({href=>'/adm/searchcat?phase=disp_adv&'. + 'catalogmode='.$ENV{'form.catalogmode'}. + '&launch='.$ENV{'form.launch'}. + '&mode='.$ENV{'form.mode'}, + text=>"Course Search", + bug=>'Searching',}); } - $ENV{'form.phase'} = 'displaybasic' if (! exists($ENV{'form.phase'})); ## ## Switch on the phase ## if ($ENV{'form.phase'} eq 'disp_basic') { - &print_basic_search_form($r,$closebutton); + &print_basic_search_form($r,$closebutton,$hidden_fields); } elsif ($ENV{'form.phase'} eq 'disp_adv') { - &print_advanced_search_form($r,$closebutton); + &print_advanced_search_form($r,$closebutton,$hidden_fields); } elsif ($ENV{'form.phase'} eq 'results') { - &display_results($r,$importbutton,$closebutton); - } elsif($ENV{'form.phase'} eq 'run_search') { + &display_results($r,$importbutton,$closebutton,$diropendb); + } elsif ($ENV{'form.phase'} =~ /^(sort|run_search)$/) { my ($query,$customquery,$customshow,$libraries,$pretty_string) = &get_persistent_data($persistent_db_file, ['query','customquery','customshow', 'libraries','pretty_string']); - &write_status($r,"query = $query"); - &write_status($r,"customquery = $customquery"); - &write_status($r,"customshow = $customshow"); - &write_status($r,"libraries = $libraries"); - &write_status($r,"pretty_string = $pretty_string"); - &run_search($r,$query,$customquery,$customshow, - $libraries,$pretty_string); + if ($ENV{'form.phase'} eq 'sort') { + &print_sort_form($r,$pretty_string); + } elsif ($ENV{'form.phase'} eq 'run_search') { + &run_search($r,$query,$customquery,$customshow, + $libraries,$pretty_string); + } + } elsif ($ENV{'form.phase'} eq 'course_search') { + &course_search($r); } elsif(($ENV{'form.phase'} eq 'basic_search') || ($ENV{'form.phase'} eq 'adv_search')) { - # Set up table - if (! defined(&create_results_table())) { - # Unable to make table to store results in. - # Definately abort search. - } - if (! &make_form_data_persistent($r,$persistent_db_file)) { - # Unable to store persistent data. - # Probably should bail out. - } # - # We are running a search + # We are running a search, try to parse it my ($query,$customquery,$customshow,$libraries) = (undef,undef,undef,undef); my $pretty_string; if ($ENV{'form.phase'} eq 'basic_search') { - ($query,$pretty_string) = &parse_basic_search($r,$closebutton); + ($query,$pretty_string,$libraries) = + &parse_basic_search($r,$closebutton,$hidden_fields); + return OK if (! defined($query)); + &make_persistent({ basicexp => $ENV{'form.basicexp'}}, + $persistent_db_file); } else { # Advanced search ($query,$customquery,$customshow,$libraries,$pretty_string) - = &parse_advanced_search($r,$closebutton); + = &parse_advanced_search($r,$closebutton,$hidden_fields); return OK if (! defined($query)); } - &write_status($r,"query = $query"); - &write_status($r,"customquery = $customquery"); - &write_status($r,"customshow = $customshow"); - &write_status($r,"libraries = $libraries"); - &write_status($r,"pretty_string = $pretty_string"); - &make_persistent($r, - { query => $query, + &make_persistent({ query => $query, customquery => $customquery, customshow => $customshow, libraries => $libraries, pretty_string => $pretty_string }, $persistent_db_file); + # + # Set up table + if (! defined(&create_results_table())) { + my $errorstring=&Apache::lonmysql::get_error(); + &Apache::lonnet::logthis('lonsearchcat.pm: Unable to create '. + 'needed table. lonmysql error:'. + $errorstring); + my $html=&Apache::lonxml::xmlbegin(); + $r->print(< +Search Error +$bodytag +Unable to create table in which to store search results. +The search has been aborted. + + +END + return OK; + } + delete($ENV{'form.launch'}); + if (! &make_form_data_persistent($r,$persistent_db_file)) { + my $html=&Apache::lonxml::xmlbegin(); + $r->print(< +Search Error +$bodytag +Unable to properly store search information. The search has been aborted. + + +END + return OK; + } ## ## Print out the frames interface ## - &print_frames_interface($r); + if (defined($query)) { + &print_frames_interface($r); + } } return OK; } +# +# The mechanism used to store values away and retrieve them does not +# handle the case of missing environment variables being significant. +# +# This routine sets non existant checkbox form elements to ''. +# +sub clean_up_environment { + if ($ENV{'form.phase'} eq 'basic_search') { + if (! exists($ENV{'form.related'})) { + $ENV{'form.related'} = ''; + } + if (! exists($ENV{'form.domains'})) { + $ENV{'form.domains'} = ''; + } + } elsif ($ENV{'form.phase'} eq 'adv_search') { + foreach my $field ('title','keywords','notes', + 'abstract','standards','mime') { + if (! exists($ENV{'form.'.$field.'_related'})) { + $ENV{'form.'.$field.'_related'} = ''; + } + } + } elsif ($ENV{'form.phase'} eq 'course_search') { + if (! exists($ENV{'form.crsrelated'})) { + $ENV{'form.crsrelated'} = ''; + } + } +} + +sub hidden_field { + my ($name,$value) = @_; + if (! defined($value)) { + $value = $ENV{'form.'.$name}; + } + return ''.$/; +} + +###################################################################### +###################################################################### +## +## Course Search +## +###################################################################### +###################################################################### +{ # Scope the course search to avoid global variables +# +# Variables For course search +my %alreadyseen; +my %hash; +my $totalfound; + +sub make_symb { + my ($id)=@_; + my ($mapid,$resid)=split(/\./,$id); + my $map=$hash{'map_id_'.$mapid}; + my $res=$hash{'src_'.$id}; + my $symb=&Apache::lonnet::encode_symb($map,$resid,$res); + return $symb; +} + +sub course_search { + my $r=shift; + my $bodytag=&Apache::loncommon::bodytag('Course Search'); + my $pretty_search_string = ''.$ENV{'form.courseexp'}.''; + my $search_string = $ENV{'form.courseexp'}; + my @New_Words; + undef(%alreadyseen); + if ($ENV{'form.crsrelated'}) { + ($search_string,@New_Words) = &related_version($ENV{'form.courseexp'}); + if (@New_Words) { + $pretty_search_string .= ' '.&mt("with related words").": @New_Words."; + } else { + $pretty_search_string .= ' '.&mt('with no related words')."."; + } + } + my $fulltext=$ENV{'form.crsfulltext'}; + my $discuss=$ENV{'form.crsdiscuss'}; + my @allwords=($search_string,@New_Words); + $totalfound=0; + my $html=&Apache::lonxml::xmlbegin(); + $r->print($html.'LON-CAPA Course Search'. + $bodytag.'
'.$pretty_search_string.'

'.&mt('Course content').':
'); + $r->rflush(); +# ======================================================= Go through the course + my $c=$r->connection; + if (tie(%hash,'GDBM_File',$ENV{'request.course.fn'}.".db", + &GDBM_READER(),0640)) { + foreach (sort(keys(%hash))) { + if ($c->aborted()) { last; } + if (($_=~/^src\_(.+)$/)) { + if ($hash{'randomout_'.$1} & !$ENV{'request.role.adv'}) { + next; + } + my $symb=&make_symb($1); + &checkonthis($r,$1,$hash{$_},0,&Apache::lonnet::gettitle($symb), + $fulltext,$symb,@allwords); + } + } + untie(%hash); + } + unless ($totalfound) { + $r->print('

'.&mt('No matches found in resources').'.

'); + } + +# Check discussions if requested + if ($discuss) { + my $totaldiscussions = 0; + $r->print('

'.&mt('Discussion postings').':
'); + my $navmap = Apache::lonnavmaps::navmap->new(); + my @allres=$navmap->retrieveResources(); + my %discussiontime = &Apache::lonnet::dump('discussiontimes', + $ENV{'course.'.$ENV{'request.course.id'}.'.domain'}, + $ENV{'course.'.$ENV{'request.course.id'}.'.num'}); + foreach my $resource (@allres) { + my $result = ''; + my $applies = 0; + my $symb = $resource->symb(); + my $ressymb = $symb; + if ($symb =~ m#(___adm/\w+/\w+)/(\d+)/bulletinboard$#) { + $ressymb = 'bulletin___'.$2.$1.'/'.$2.'/bulletinboard'; + unless ($ressymb =~ m#bulletin___\d+___adm/wrapper#) { + $ressymb=~s#(bulletin___\d+___)#$1adm/wrapper/#; + } + } + if (defined($discussiontime{$ressymb})) { + my %contrib = &Apache::lonnet::restore($ressymb,$ENV{'request.course.id'}, + $ENV{'course.'.$ENV{'request.course.id'}.'.domain'}, + $ENV{'course.'.$ENV{'request.course.id'}.'.num'}); + if ($contrib{'version'}) { + for (my $id=1;$id<=$contrib{'version'};$id++) { + unless (($contrib{'hidden'}=~/\.$id\./) || ($contrib{'deleted'}=~/\.$id\./)) { + if ($contrib{$id.':subject'}) { + $result .= $contrib{$id.':subject'}; + } + if ($contrib{$id.':message'}) { + $result .= $contrib{$id.':message'}; + } + if ($contrib{$id,':attachmenturl'}) { + if ($contrib{$id,':attachmenturl'} =~ m-/([^/]+)$-) { + $result .= $1; + } + } + $applies = &checkwords($result,$applies,@allwords); + } + } + } + } +# Does this discussion apply? + if ($applies) { + my ($map,$ind,$url)=&Apache::lonnet::decode_symb($ressymb); + my $disctype = &mt('resource'); + if ($url =~ m#/bulletinboard$#) { + if ($url =~m#^adm/wrapper/adm/.*/bulletinboard$#) { + $url =~s#^adm/wrapper##; + } + $disctype = &mt('bulletin board'); + } else { + $url = '/res/'.$url; + } + if ($url =~ /\?/) { + $url .= '&symb='; + } else { + $url .= '?symb='; + } + $url .= &Apache::lonnet::escape($resource->symb()); + my $title = $resource->compTitle(); + $r->print('
'. + ($title?$title:$url).'  - '.$disctype.'
'); + $totaldiscussions++; + } else { + $r->print(' .'); + } + } + unless ($totaldiscussions) { + $r->print('

'.&mt('No matches found in postings').'.

'); + } + } + +# =================================================== Done going through course + $r->print(''); +} + +# =============================== This pulls up a resource and its dependencies + +sub checkonthis { + my ($r,$id,$url,$level,$title,$fulltext,$symb,@allwords)=@_; + $alreadyseen{$id}=1; + if (&Apache::loncommon::connection_aborted($r)) { return; } + $r->rflush(); + + my $result=$title.' '; + if ($ENV{'request.role.adv'} || !$hash{'encrypted_'.$id}) { + $result.=&Apache::lonnet::metadata($url,'title').' '. + &Apache::lonnet::metadata($url,'subject').' '. + &Apache::lonnet::metadata($url,'abstract').' '. + &Apache::lonnet::metadata($url,'keywords'); + } + my ($extension)=($url=~/\.(\w+)$/); + if (&Apache::loncommon::fileembstyle($extension) eq 'ssi' && + ($url) && ($fulltext)) { + $result.=&Apache::lonnet::ssi_body($url.'?symb='.&Apache::lonnet::escape($symb)); + } + $result=~s/\s+/ /gs; + my $applies = 0; + $applies = &checkwords($result,$applies,@allwords); +# Does this resource apply? + if ($applies) { + $r->print('
'); + for (my $i=0;$i<=$level*5;$i++) { + $r->print(' '); + } + my $href=$url; + if ($hash{'encrypted_'.$id} && !$ENV{'request.role.adv'}) { + $href=&Apache::lonenc::encrypted($href) + .'?symb='.&Apache::lonenc::encrypted($symb); + } else { + $href.='?symb='.&Apache::lonnet::escape($symb); + } + $r->print(''.($title?$title:$url). + '
'); + $totalfound++; + } elsif ($fulltext) { + $r->print(' .'); + } + $r->rflush(); +# Check also the dependencies of this one + my $dependencies= + &Apache::lonnet::metadata($url,'dependencies'); + foreach (split(/\,/,$dependencies)) { + if (($_=~/^\/res\//) && (!$alreadyseen{$id})) { + &checkonthis($r,$id,$_,$level+1,'',$fulltext,undef,@allwords); + } + } +} + +sub checkwords { + my ($result,$applies,@allwords) = @_; + foreach (@allwords) { + if ($_=~/\w/) { + if ($result=~/$_/si) { + $applies++; + } + } + } + return $applies; +} + +sub untiehash { + if (tied(%hash)) { + untie(%hash); + } +} + +} # End of course search scoping + +sub search_html_header { + my $html=&Apache::lonxml::xmlbegin(); + my $Str = < +The LearningOnline Network with CAPA + +ENDHEADER + return $Str; +} + ###################################################################### ###################################################################### @@ -326,64 +680,126 @@ END =item &print_basic_search_form() -Returns a scalar which holds html for the basic search form. +Prints the form for the basic search. Sorry the name is so cryptic. =cut ###################################################################### ###################################################################### - -sub print_basic_search_form{ - my ($r,$closebutton) = @_; - my $scrout=<<"ENDDOCUMENT"; - - -The LearningOnline Network with CAPA - - - - -

Search Catalog

-
- +sub print_basic_search_form { + my ($r,$closebutton,$hidden_fields) = @_; + my $result = ($ENV{'form.catalogmode'} ne 'groupsearch'); + my $bodytag=&Apache::loncommon::bodytag('Search'). + &Apache::lonhtmlcommon::breadcrumbs(undef,'Searching','Search_Basic', + undef,undef, + $ENV{'form.catalogmode'} ne 'groupsearch'); + my $scrout = &search_html_header().$bodytag; + if (&Apache::lonnet::allowed('bre',$ENV{'request.role.domain'})) { + # Define interface components + my $userelatedwords= ''; + my $onlysearchdomain=''; + my $adv_search_link = + ''.&mt('Advanced Search').''; + # + $scrout.=''. + ''. + $hidden_fields; + # + $scrout .= '
'.$/; + if ($ENV{'request.course.id'}) { + $scrout .= '

'.&mt('LON-CAPA Catalog Search').'

'; + } else { + # No need to tell them they are searching + $scrout.= ('
'x2); + } + $scrout.=''. + ''. + ''. + ''.$/; + # + $scrout .= ''.$/; + $scrout .= '
'. + &Apache::lonhtmlcommon::textbox + ('basicexp', + &HTML::Entities::encode($ENV{'form.basicexp'},'<>&"'),50 + ). + '
'. + ''.&searchhelp().''.'
'. + ''.(' 'x3).$adv_search_link.''.'
'. + ''.(' 'x1).$userelatedwords.''.'
'. + ''.(' 'x1).$onlysearchdomain.''.'
'. + '
'. + ''. + ''. + (' 'x2).$closebutton.(' 'x2). + &viewoptions(). + ''. + '
'.$/.'
'.'
'; + } + if ($ENV{'request.course.id'}) { + my %lt=&Apache::lonlocal::texthash('srch' => 'Search', + 'header' => 'Course Search', + 'note' => 'Enter terms or phrases, then press "Search" below', + 'use' => 'use related words', + 'full' =>'fulltext search (time consuming)', + 'disc' => 'search discussion postings (resources and bulletin boards)', + ); + $scrout.=(< +
+
+

$lt{'header'}

+ $hidden_fields -

Basic Search

-Enter terms or phrases separated by AND, OR, or NOT -then press SEARCH below. +$lt{'note'}.

- -
-ENDDOCUMENT - $scrout.=' '.&simpletextfield('basicexp',$ENV{'form.basicexp'},40). - ' '; -# $scrout.=&simplecheckbox('allversions',$ENV{'form.allversions'}); -# $scrout.='Search historic archives'; - my $checkbox = &simplecheckbox('related',$ENV{'form.related'}); - $scrout.=<Advanced Search
$checkbox use related words
-

-

  -$closebutton -END - $scrout.=&selectbox(undef,'viewselect', - $ENV{'form.viewselect'}, - undef,undef,undef, - sort(keys(%Views))); - $scrout.=< +ENDCOURSESEARCH + $scrout.=' '. + &Apache::lonhtmlcommon::textbox('courseexp', + $ENV{'form.courseexp'},40); + my $crscheckbox = + &Apache::lonhtmlcommon::checkbox('crsfulltext', + $ENV{'form.crsfulltext'}); + my $relcheckbox = + &Apache::lonhtmlcommon::checkbox('crsrelated', + $ENV{'form.crsrelated'}); + my $discheckbox = + &Apache::lonhtmlcommon::checkbox('crsdiscuss', + $ENV{'form.crsrelated'}); + $scrout.=(< + + + +

+
+ENDENDCOURSE + } + $scrout.=(< ENDDOCUMENT @@ -397,183 +813,216 @@ ENDDOCUMENT =item &advanced_search_form() -Returns a scalar which holds html for the advanced search form. +Prints the advanced search form. =cut ###################################################################### ###################################################################### - sub print_advanced_search_form{ - my ($r,$closebutton) = @_; - my $advanced_buttons = <<"END"; -

- - + my ($r,$closebutton,$hidden_fields) = @_; + my $bodytag=&Apache::loncommon::bodytag('Advanced Catalog Search'). + &Apache::lonhtmlcommon::breadcrumbs(undef,'Searching', + 'Search_Advanced', + undef,undef, + $ENV{'form.catalogmode'} ne 'groupsearch'); + my %lt=&Apache::lonlocal::texthash('srch' => 'Search', + 'reset' => 'Reset', + 'help' => 'Help'); + my $advanced_buttons=<<"END"; + + $closebutton - -

END - if (!defined($ENV{'form.viewselect'})) { - $ENV{'form.viewselect'} ="Detailed Citation View"; - } - my $scrout=<<"ENDHEADER"; - - -The LearningOnline Network with CAPA - - - - -

Advanced Catalog Search

-
-Enter terms or phrases separated by search operators -such as AND, OR, or NOT.
-
+ my $scrout=&search_html_header(); + $scrout .= <<"ENDHEADER"; +$bodytag + +

$advanced_buttons -$hidden_fields - - - -\n"; - $scrout.=&searchphrasefield_with_related('title', 'title' , - $ENV{'form.title'}); - $scrout.=&searchphrasefield('author', 'author' ,$ENV{'form.author'}); - $scrout.=&searchphrasefield_with_related('subject', 'subject' , - $ENV{'form.subject'}); - $scrout.=&searchphrasefield_with_related('keywords','keywords', - $ENV{'form.keywords'}); - $scrout.=&searchphrasefield('URL', 'url' ,$ENV{'form.url'}); - $scrout.=&searchphrasefield_with_related('notes', 'notes' , - $ENV{'form.notes'}); - $scrout.=&searchphrasefield_with_related('abstract','abstract', - $ENV{'form.abstract'}); - # Hack - an empty table row. - $scrout.="\n"; - $scrout.=&searchphrasefield('file
extension','mime', - $ENV{'form.mime'}); - $scrout.="\n"; - $scrout.=&searchphrasefield('publisher
owner','owner', - $ENV{'form.owner'}); - $scrout.="
VIEW: ENDHEADER - $scrout.=&selectbox(undef,'viewselect', - $ENV{'form.viewselect'}, - undef,undef,undef, - sort(keys(%Views))); - $scrout.="Related
Words
   
   
\n"; - $ENV{'form.category'}='any' unless length($ENV{'form.category'}); - $scrout.=&selectbox('File Category','category', - $ENV{'form.category'}, - 'any','Any category', - undef, - (&Apache::loncommon::filecategories())); - $ENV{'form.language'}='any' unless length($ENV{'form.language'}); - #---------------------------------------------------------------- - # Allow restriction to multiple domains. - # I make the crazy assumption that there will never be a domain 'any'. - # - $ENV{'form.domains'} = 'any' if (! exists($ENV{'form.domains'})); - my @allowed_domains = (ref($ENV{'form.domains'}) ? @{$ENV{'form.domains'}} - : ($ENV{'form.domains'}) ); - my %domain_hash = (); - foreach (@allowed_domains) { - $domain_hash{$_}++; + $scrout.=(' 'x2).&viewoptions().'

'.$hidden_fields. + ''; + my %fields=&Apache::lonmeta::fieldnames(); + # + $scrout .= '

'.&mt('Standard Metadata').'

'; + $scrout .= "\n"; + $scrout .= '\n"; + my %related_word_search = + ('title' => 1, + 'author' => 0, + 'owner' => 0, + 'authorspace' => 0, + 'modifyinguser'=> 0, + 'keywords' => 1, + 'notes' => 1, + 'abstract' => 1, + 'standards'=> 1, + 'mime' => 1, + ); + # + foreach my $field ('title','author','owner','authorspace','modifyinguser', + 'keywords','notes','abstract','standards','mime') { + $scrout.=''.$/; } - my @domains =&Apache::loncommon::get_domains(); - # adjust the size of the select box - my $size = 4; - my $size = (scalar @domains < ($size - 1) ? scalar @domains + 1 : $size); - $scrout.="\n".''. - 'DOMAINS
'. - '\n"; - #---------------------------------------------------------------- - $scrout.=&selectbox('Limit by language','language', - $ENV{'form.language'},'any','Any Language', - \&{Apache::loncommon::languagedescription}, - (&Apache::loncommon::languageids), - ); -# ------------------------------------------------ Compute date selection boxes - $scrout.=< -LIMIT BY CREATION DATE RANGE: - -
-between: -CREATIONDATESTART - $scrout.=&dateboxes('creationdatestart',1,1,1976, - $ENV{'form.creationdatestart_month'}, - $ENV{'form.creationdatestart_day'}, - $ENV{'form.creationdatestart_year'}, - ); - $scrout.="and:\n"; - $scrout.=&dateboxes('creationdateend',12,31,2051, - $ENV{'form.creationdateend_month'}, - $ENV{'form.creationdateend_day'}, - $ENV{'form.creationdateend_year'}, - ); - $scrout.="

"; - $scrout.=< -LIMIT BY LAST REVISION DATE RANGE: - -
between: -LASTREVISIONDATESTART - $scrout.=&dateboxes('lastrevisiondatestart',1,1,1976, - $ENV{'form.lastrevisiondatestart_month'}, - $ENV{'form.lastrevisiondatestart_day'}, - $ENV{'form.lastrevisiondatestart_year'}, - ); - $scrout.=< -LIMIT BY SPECIAL METADATA FIELDS: - -For resource-specific metadata, enter in an expression in the form of -key=value separated by operators such as AND, OR or NOT.
-Example: grandmother=75 OR grandfather=85 -
-CUSTOMMETADATA - $scrout.=&simpletextfield('custommetadata',$ENV{'form.custommetadata'}); - $scrout.=< -SHOW SPECIAL METADATA FIELDS: - -Enter in a space-separated list of special metadata fields to show -in a fielded listing for each record result. -
-CUSTOMSHOW - $scrout.=&simpletextfield('customshow',$ENV{'form.customshow'}); + foreach my $field ('lowestgradelevel','highestgradelevel') { + $scrout.='
'. + ''. + ''.$/; + } + $scrout.=''.$/; + $scrout.=''.$/; + # + # Misc metadata + $scrout.=''.$/; + $scrout.=''; + $scrout .= "
 '. + (' 'x2).&searchhelp()."
'.&titlefield($fields{$field}).''. + &Apache::lonmeta::prettyinput($field, + $ENV{'form.'.$field}, + $field, + 'advsearch', + $related_word_search{$field}, + '', + $ENV{'form.'.$field.'_related'}, + 50); + if ($related_word_search{$field}) { + $scrout .= 'related words'; + } else { + $scrout .= ' '; + } + $scrout .= '
'.&titlefield($fields{$field}).''. + &Apache::lonmeta::prettyinput($field, + $ENV{'form.'.$field}, + $field, + 'advsearch', + 0). + '
'. + &titlefield(&mt('MIME Type Category')).''. + &Apache::loncommon::filecategoryselect('category', + $ENV{'form.category'}). + '
'. + &titlefield(&mt('Domains')).''. + &Apache::loncommon::domain_select('domains', + $ENV{'form.domains'},1). + '
'. + &titlefield(&mt('Copyright/Distribution')).''. + &Apache::lonmeta::selectbox('copyright', + $ENV{'form.copyright'}, + \&Apache::loncommon::copyrightdescription, + ( undef, + &Apache::loncommon::copyrightids) + ).'
'. + &titlefield(&mt('Language')).''. + &Apache::lonmeta::selectbox('language', + $ENV{'form.language'}, + \&Apache::loncommon::languagedescription, + ('any',&Apache::loncommon::languageids) + ).'
\n"; + # + # Dynamic metadata + $scrout .= '

'.&mt('Problem Statistics').'

'; + $scrout .= "\n"; + $scrout .= ''. + ''."\n"; + foreach my $statistic + ({ name=>'count', + description=>'Network-wide number of accesses (hits)',}, + { name=>'stdno', + description=> + 'Total number of students who have worked on this problem',}, + { name => 'avetries', + description=>'Average number of tries till solved',}, + { name => 'difficulty', + description=>'Degree of difficulty',}, + { name => 'disc', + description=>'Degree of discrimination'}) { + $scrout .= ''.$/; + } + $scrout .= "
 '.&mt('Minimum').''.&mt('Maximum').'
'. + &titlefield(&mt($statistic->{'description'})). + ''. + ''. + ''. + ''. + '
\n"; + $scrout .= '

'.&mt('Evaluation Data').'

'; + $scrout .= "\n"; + $scrout .= ''. + ''."\n"; + foreach my $evaluation + ( { name => 'clear', + description => 'Material presented in clear way'}, + { name =>'depth', + description => 'Material covered with sufficient depth'}, + { name => 'helpful', + description => 'Material is helpful'}, + { name => 'correct', + description => 'Material appears to be correct'}, + { name => 'technical', + description => 'Resource is technically correct'}){ + $scrout .= ''.$/; + } + $scrout .= "
 '.&mt('Minimum').''.&mt('Maximum').'
'. + &titlefield(&mt($evaluation->{'description'})). + ''. + ''. + ''. + ''. + '
\n"; + # + # Creation/Modification date limits + $scrout .= '

'.&mt('Creation and Modification dates').'

'; + $scrout .= "\n\n"; + my $cafter = + &Apache::lonhtmlcommon::date_setter('advsearch', # formname + 'creationdate1', # fieldname + 0, # current value + '', # special + 1, # includeempty + '', # state + 1, # no_hh_mm_ss + ); + my $cbefore = + &Apache::lonhtmlcommon::date_setter('advsearch', # formname + 'creationdate2', # fieldname + 0, # current value + '', # special + 1, # includeempty + '', # state + 1, # no_hh_mm_ss + ); + $scrout .= &mt(''. + ''. + ''. + '',$cafter,$cbefore); + my $lafter = + &Apache::lonhtmlcommon::date_setter('advsearch', + 'revisiondate1', + 0, # current value + '', # special + 1, # includeempty + '', # state + 1, # no_hh_mm_ss + ); + my $lbefore = + &Apache::lonhtmlcommon::date_setter('advsearch', + 'revisiondate2', + 0, # current value + '', # special + 1, # includeempty + '', # state + 1, # no_hh_mm_ss + ); + $scrout .= &mt(''. + ''. + ''. + '',$lafter,$lbefore); + $scrout.="
Created between[_1]
and [_2]
Last modified between [_1]
and[_2]
\n"; $scrout.=< @@ -589,7 +1038,106 @@ ENDDOCUMENT =pod -=item &get_persistent_form_data +=item &titlefield() + +Inputs: title text + +Outputs: titletext with font wrapper + +=cut + +###################################################################### +###################################################################### +sub titlefield { + my $title=shift; + return $title; +} + +###################################################################### +###################################################################### + +=pod + +=item viewoptiontext() + +Inputs: codename for view option + +Outputs: displayed text + +=cut + +###################################################################### +###################################################################### +sub viewoptiontext { + my $code=shift; + my %desc=&Apache::lonlocal::texthash + ('detailed' => "Detailed Citation View", + 'xml' => 'XML/SGML', + 'compact' => 'Compact View', + 'fielded' => 'Fielded Format', + 'summary' => 'Summary View'); + return $desc{$code}; +} + +###################################################################### +###################################################################### + +=pod + +=item viewoptions() + +Inputs: none + +Outputs: text for box with view options + +=cut + +###################################################################### +###################################################################### +sub viewoptions { + my $scrout; + if (! defined($ENV{'form.viewselect'})) { + $ENV{'form.viewselect'}='detailed'; + } + $scrout.=&Apache::lonmeta::selectbox('viewselect', + $ENV{'form.viewselect'}, + \&viewoptiontext, + sort(keys(%Views))); + $scrout.= '  '; + my $countselect = &Apache::lonmeta::selectbox('show', + $ENV{'form.show'}, + undef, + (10,20,50,100,1000,10000)); + $scrout .= (' 'x2).&mt('[_1] Records per Page',$countselect). + ''.$/; + return $scrout; +} + +###################################################################### +###################################################################### + +=pod + +=item searchhelp() + +Inputs: none + +Outputs: return little blurb on how to enter searches + +=cut + +###################################################################### +###################################################################### +sub searchhelp { + return &mt('Enter words and quoted phrases'); +} + +###################################################################### +###################################################################### + +=pod + +=item &get_persistent_form_data() Inputs: filename of database @@ -606,48 +1154,45 @@ to them. ###################################################################### ###################################################################### sub get_persistent_form_data { - my $r = shift; my $filename = shift; - return undef if (! -e $filename); + return 0 if (! -e $filename); return undef if (! tie(%persistent_db,'GDBM_File',$filename, - &GDBM_READER,0640)); + &GDBM_READER(),0640)); # # These make sure we do not get array references printed out as 'values'. - my %arrays_allowed = ('form.category'=>1,'form.domains'=>1); + my %arrays_allowed = ('form.domains'=>1); # # Loop through the keys, looking for 'form.' foreach my $name (keys(%persistent_db)) { next if ($name !~ /^form./); + # Kludgification begins! + if ($name eq 'form.domains' && + $ENV{'form.searchmode'} eq 'basic' && + $ENV{'form.phase'} ne 'disp_basic') { + next; + } + # End kludge (hopefully) + next if (exists($ENV{$name})); my @values = map { &Apache::lonnet::unescape($_); } split(',',$persistent_db{$name}); next if (@values <1); - if (exists($ENV{$name})) { - if (ref($ENV{$name}) eq 'ARRAY') { - # If it is an array, tack @values on the end of it. - $ENV{$name} = [@$ENV{$name},@values]; - } elsif (! ref($ENV{$name}) && $arrays_allowed{$name}) { - # if arrays are allowed, turn it into one and add @values - $ENV{$name} = [$ENV{$name},@values]; - } # otherwise, assume the value in $ENV{$name} is better than ours. + if ($arrays_allowed{$name}) { + $ENV{$name} = [@values]; } else { - if ($arrays_allowed{$name}) { - $ENV{$name} = [@values]; - } else { - $ENV{$name} = $values[0] if ($values[0]); - } + $ENV{$name} = $values[0] if ($values[0]); } - &write_status($r,"Reconstructed $name = $ENV{$name}"); } untie (%persistent_db); return 1; } + ###################################################################### ###################################################################### =pod -=item &get_persistent_data +=item &get_persistent_data() Inputs: filename of database, ref to array of values to recover. @@ -668,7 +1213,7 @@ sub get_persistent_data { my @Values; # Return array return undef if (! -e $filename); return undef if (! tie(%persistent_db,'GDBM_File',$filename, - &GDBM_READER,0640)); + &GDBM_READER(),0640)); foreach my $name (@Vars) { if (! exists($persistent_db{$name})) { push @Values, undef; @@ -677,7 +1222,7 @@ sub get_persistent_data { my @values = map { &Apache::lonnet::unescape($_); } split(',',$persistent_db{$name}); - if (@values == 1) { + if (@values <= 1) { push @Values,$values[0]; } else { push @Values,\@values; @@ -698,26 +1243,22 @@ Inputs: Hash of values to save, filename Store variables away to the %persistent_db. Values will be escaped. Values that are array pointers will have their -elements escaped and concatenated in a comma seperated string. +elements escaped and concatenated in a comma separated string. =cut ###################################################################### ###################################################################### sub make_persistent { - my $r = shift; my %save = %{shift()}; my $filename = shift; return undef if (! tie(%persistent_db,'GDBM_File', - $filename,&GDBM_WRCREAT,0640)); + $filename,&GDBM_WRCREAT(),0640)); foreach my $name (keys(%save)) { - next if (! exists($save{$name})); - next if (! defined($save{$name}) || $save{$name} eq ''); my @values = (ref($save{$name}) ? @{$save{$name}} : ($save{$name})); # We handle array references, but not recursively. my $store = join(',', map { &Apache::lonnet::escape($_); } @values ); $persistent_db{$name} = $store; - &write_status($r,"Stored $name = $store"); } untie(%persistent_db); return 1; @@ -734,7 +1275,7 @@ Inputs: filename of persistent database. Store most form variables away to the %persistent_db. Values will be escaped. Values that are array pointers will have their -elements escaped and concatenated in a comma seperated string. +elements escaped and concatenated in a comma separated string. =cut @@ -745,294 +1286,13 @@ sub make_form_data_persistent { my $filename = shift; my %save; foreach (keys(%ENV)) { - next if (! /^form/ || /submit/); + next if (!/^form/ || /submit/); $save{$_} = $ENV{$_}; } - return &make_persistent($r,\%save,$filename); -} - -###################################################################### -# HTML form building functions # -###################################################################### - -=pod - -=item HTML form building functions - -=over 4 - -=cut - -############################################### -############################################### - -=pod - -=item &simpletextfield() - -Inputs: $name,$value,$size - -Returns a text input field with the given name, value, and size. -If size is not specified, a value of 20 is used. - -=cut - -############################################### -############################################### - -sub simpletextfield { - my ($name,$value,$size)=@_; - $size = 20 if (! defined($size)); - return ''; -} - -############################################### -############################################### - -=pod - -=item &simplecheckbox() - -Inputs: $name,$value - -Returns a simple check box with the given $name. -If $value eq 'on' the box is checked. - -=cut - -############################################### -############################################### - -sub simplecheckbox { - my ($name,$value)=@_; - my $checked=''; - $checked="checked" if $value eq 'on'; - return ''; -} - -############################################### -############################################### - -=pod - -=item &fieldtitle() - -Input: $title - -Returns a scalar with html which will display $title as a search -field heading. - -=cut - -############################################### -############################################### - -sub fieldtitle { - my $title = uc(shift()); - return ''.$title. - ': '; -} - -############################################### -############################################### - -=pod - -=item &searchphrasefield() - -Inputs: $title,$name,$value - -Returns html for a title line and an input field for entering search terms. -The entry field (which is where the $name and $value are used) is a 50 column -simpletextfield. The html returned is for a row in a three column table. - -=cut - -############################################### -############################################### - -sub searchphrasefield { - my ($title,$name,$value)=@_; - return ''.&fieldtitle($title).''. - &simpletextfield($name,$value,50)." \n"; -} - -############################################### -############################################### - -=pod - -=item &searchphrasefield_with_related() - -Inputs: $title,$name,$value - -Returns html for a title line and an input field for entering search terms -and a check box for 'related words'. The entry field (which is where the -$name and $value are used) is a 50 column simpletextfield. The name of -the related words checkbox is "$name_related". - -=cut - -############################################### -############################################### - -sub searchphrasefield_with_related { - my ($title,$name,$value)=@_; - return ''.&fieldtitle($title).''. - &simpletextfield($name,$value,50).' '. - &simplecheckbox($name.'_related',$ENV{'form.'.$name.'_related'}). - " \n"; -} - -############################################### -############################################### - -=pod - -=item &dateboxes() - -Returns html selection form elements for the specification of -the day, month, and year. - -=cut - -############################################### -############################################### - -sub dateboxes { - my ($name,$defaultmonth,$defaultday,$defaultyear, - $currentmonth,$currentday,$currentyear)=@_; - ($defaultmonth,$defaultday,$defaultyear)=('','',''); - # - # Day - my $day=< - -END - for (my $i = 1; $i<=31; $i++) { - $day.="\n"; - } - $day.="\n"; - $day=~s/(\"$currentday\")/$1 SELECTED/ if length($currentday); - # - # Month - my $month=< - -END - my $i = 1; - foreach (qw/January February March April May June - July August September October November December /){ - $month .="\n"; - $i++; - } - $month.="\n"; - $month=~s/(\"$currentmonth\")/$1 SELECTED/ if length($currentmonth); - # - # Year (obviously) - my $year=< - -END - my $maxyear = 2051; - for (my $i = 1976; $i<=$maxyear; $i++) { - $year.="\n"; - } - $year.="\n"; - $year=~s/(\"$currentyear\")/$1 SELECTED/ if length($currentyear); - return "$month$day$year"; -} - -############################################### -############################################### - -=pod - -=item &selectbox() - -Returns a scalar containing an html tag. - -=item $default - -The default value of the form. Can be $anyvalue, or in @idlist. - -=item $anyvalue - -The "); + &Apache::lonnet::logthis("lonmysql was unable to determine the status". + " of table ".$table); + return undef; + } elsif (! $table_check) { + $r->print("The table of results could not be found."); + &Apache::lonnet::logthis("The user requested a table, ".$table. + ", that could not be found."); + return undef; + } + return 1; +} + +###################################################################### +###################################################################### + +=pod + +=item &print_sort_form() + +The sort feature is not implemented at this time. This form just prints +a link to change the search query. + +=cut + +###################################################################### +###################################################################### +sub print_sort_form { + my ($r,$pretty_query_string) = @_; + my $bodytag=&Apache::loncommon::bodytag(undef,undef,undef,1). + &Apache::lonhtmlcommon::breadcrumbs + (undef,'Searching','Searching',undef,undef, + $ENV{'form.catalogmode'} ne 'groupsearch'); + + ## + my %SortableFields=&Apache::lonlocal::texthash( + id => 'Default', + title => 'Title', + author => 'Author', + subject => 'Subject', + url => 'URL', + version => 'Version Number', + mime => 'Mime type', + lang => 'Language', + owner => 'Owner/Publisher', + copyright => 'Copyright', + hostname => 'Host', + creationdate => 'Creation Date', + lastrevisiondate => 'Revision Date' + ); + ## + my $table = $ENV{'form.table'}; + return if (! &ensure_db_and_table($r,$table)); + ## + ## Get the number of results + ## + my $total_results = &Apache::lonmysql::number_of_rows($table); + if (! defined($total_results)) { + $r->print("A MySQL error has occurred."); + &Apache::lonnet::logthis("lonmysql was unable to determine the number". + " of rows in table ".$table); + &Apache::lonnet::logthis(&Apache::lonmysql::get_error()); + return; + } + my $result; + my $html=&Apache::lonxml::xmlbegin(); + $result.=< + +Results + +$bodytag +
+ +END + +#

Sort Results

+#Sort by: }; + return $result; } ###################################################################### @@ -1619,7 +2345,10 @@ sub write_status { =pod -=item &run_search +=item &run_search() + +Executes a search query by sending it the the other servers and putting the +results into MySQL. =cut @@ -1627,138 +2356,218 @@ sub write_status { ###################################################################### sub run_search { my ($r,$query,$customquery,$customshow,$serverlist,$pretty_string) = @_; - # - # Timing variables - # - my $starttime = time; - my $max_time = 120; # seconds for the search to complete + my $bodytag=&Apache::loncommon::bodytag(undef,undef,undef,1); + $bodytag.=&Apache::lonhtmlcommon::breadcrumbs + (undef,'Searching','Searching',undef,undef, + $ENV{'form.catalogmode'} ne 'groupsearch'); + my $connection = $r->connection; # # Print run_search header # - $r->print("Search Status"); - $r->print("Search: ".$pretty_string."
\n"); + my $html=&Apache::lonxml::xmlbegin(); + $r->print(< +Search Status +$bodytag + + +END + # Remove leading and trailing
+ $pretty_string =~ s:^\s*
::i; + $pretty_string =~ s:(
)*\s*$::im; + my @Lines = split("
",$pretty_string); + # I keep getting blank items at the end of the list, hence the following: + while ($Lines[-1] =~ /^\s*$/ && @Lines) { + pop(@Lines); + } + if (@Lines > 2) { + $pretty_string = join '
',(@Lines[0..2],'....
'); + } + $r->print(&mt("Search: [_1]",$pretty_string)); $r->rflush(); # # Determine the servers we need to contact. - # my @Servers_to_contact; if (defined($serverlist)) { - @Servers_to_contact = @$serverlist; + if (ref($serverlist) eq 'ARRAY') { + @Servers_to_contact = @$serverlist; + } else { + @Servers_to_contact = ($serverlist); + } } else { @Servers_to_contact = sort(keys(%Apache::lonnet::libserv)); } my %Server_status; + # + # Check on the mysql table we will use to store results. my $table =$ENV{'form.table'}; - if (! defined($table)) { - # What do I do now? Print out an error page. - &Apache::lonnet::logthis("lonmysql attempted to create a table ". - "and this was the result:". + if (! defined($table) || $table eq '' || $table =~ /\D/ ) { + $r->print("Unable to determine table id to store search results in.". + "The search has been aborted."); + return; + } + my $table_status = &Apache::lonmysql::check_table($table); + if (! defined($table_status)) { + $r->print("Unable to determine status of table."); + &Apache::lonnet::logthis("Bogus table id of $table for ". + "$ENV{'user.name'} @ $ENV{'user.domain'}"); + &Apache::lonnet::logthis("lonmysql error = ". + &Apache::lonmysql::get_error()); + return; + } + if (! $table_status) { + &Apache::lonnet::logthis("lonmysql error = ". &Apache::lonmysql::get_error()); - $r->print("An internal error occured with the database.
". - "The error has been logged, but you should probably alert". - " your system administrator."); + &Apache::lonnet::logthis("lonmysql debug = ". + &Apache::lonmysql::get_debug()); + &Apache::lonnet::logthis('table status = "'.$table_status.'"'); + $r->print("The table id,$table, we tried to use is invalid.". + "The search has been aborted."); return; } ## ## Prepare for the big loop. - ## my $hitcountsum; my $server; my $status; - while ((time - $starttime < $max_time) && + my $revise = &revise_button(); + $r->print(< +StatusTotal MatchesTime Remaining + + + + +$revise + + + +END + $r->rflush(); + &reset_timing(); + &update_seconds($r); + &update_status($r,&mt('contacting [_1]',$Servers_to_contact[0])); + while (&time_left() && ((@Servers_to_contact) || keys(%Server_status))) { - # Send out a search request if it needs to be done. + &update_seconds($r); + # + # Send out a search request if (@Servers_to_contact) { # Contact one server my $server = shift(@Servers_to_contact); + &update_status($r,&mt('contacting [_1]',$server)); my $reply=&Apache::lonnet::metadata_query($query,$customquery, $customshow,[$server]); ($server) = keys(%$reply); $Server_status{$server} = $reply->{$server}; - # $r->print("Contacted:$server:reply:$Server_status{$server}"); - if ($max_time - (time - $starttime) < 20) { - # If there are less than 20 seconds to go in the search, - # give the newly contacted servers 20 more seconds to - # respond.... - $max_time += 20; - } } else { - sleep(1); # wait a sec. to give time for files to be written + # wait a sec. to give time for files to be written + # This sleep statement is here instead of outside the else + # block because we do not want to pause if we have servers + # left to contact. + if (scalar (keys(%Server_status))) { + &update_status($r, + &mt('waiting on [_1]',join(' ',keys(%Server_status)))); + } + sleep(1); } - while (my ($server,$status) = each(%Server_status)) { + # + # Loop through the servers we have contacted but do not + # have results from yet, looking for results. + foreach my $server (keys(%Server_status)) { + last if ($connection->aborted()); + &update_seconds($r); + my $status = $Server_status{$server}; if ($status eq 'con_lost') { delete ($Server_status{$server}); - # $r->print("server $server is not responding."); next; } $status=~/^([\.\w]+)$/; my $datafile=$r->dir_config('lonDaemons').'/tmp/'.$1; if (-e $datafile && ! -e "$datafile.end") { - # Let the user know we are receiving data from the server - # $r->print("$server:Receiving file"); + &update_status($r,&mt('Receiving results from [_1]',$server)); next; } + last if ($connection->aborted()); if (-e "$datafile.end") { + &update_status($r,&mt('Reading results from [_1]',$server)); if (-z "$datafile") { delete($Server_status{$server}); next; } my $fh; if (!($fh=Apache::File->new($datafile))) { - # Error opening file... - # Tell the user and exit...? - # Should I give up on opening it? $r->print("Unable to open search results file for ". "server $server. Omitting from search"); - next; + delete($Server_status{$server}); + next; } # Read in the whole file. while (my $result = <$fh>) { - # handle custom fields? Someday we will! + last if ($connection->aborted()); + # + # Records are stored one per line chomp($result); - next unless $result; + next if (! $result); + # # Parse the result. my %Fields = &parse_raw_result($result,$server); $Fields{'hostname'} = $server; + # + # Skip based on copyright next if (! ©right_check(\%Fields)); + # # Store the result in the mysql database my $result = &Apache::lonmysql::store_row($table,\%Fields); if (! defined($result)) { $r->print(&Apache::lonmysql::get_error()); } - # $r->print(&Apache::lonmysql::get_debug()); + # $hitcountsum ++; - } # End of foreach (@results) + &update_seconds($r); + if ($hitcountsum % 50 == 0) { + &update_count_status($r,$hitcountsum); + } + } $fh->close(); # $server is only deleted if the results file has been # found and (successfully) opened. This may be a bad idea. delete($Server_status{$server}); - # $r->print("Received $new_count more results from ". - # $server."."); } + last if ($connection->aborted()); + &update_count_status($r,$hitcountsum); } - # Finished looping through the servers + last if ($connection->aborted()); + &update_seconds($r); } - &Apache::lonmysql::disconnect_from_db(); - # Let the user know + &update_status($r,&mt('Search Complete [_1]',$server)); + &update_seconds($r); + # + &Apache::lonmysql::disconnect_from_db(); # This is unneccessary # # We have run out of time or run out of servers to talk to and - # results to get. - $r->print("

Search completed.

"); - if ($hitcountsum) { - $r->print($hitcountsum." successful matches to your query.
"); - } else { - $r->print("There were no successful matches to your query.
"); - } + # results to get, so let the client know the top frame needs to be + # loaded from /adm/searchcat $r->print(""); +# if ($ENV{'form.catalogmode'} ne 'groupsearch') { + $r->print(""); +# } return; } ###################################################################### ###################################################################### + =pod -=item &prev_next_buttons +=item &prev_next_buttons() + +Returns html for the previous and next buttons on the search results page. =cut @@ -1767,51 +2576,36 @@ sub run_search { sub prev_next_buttons { my ($current_min,$show,$total,$parms) = @_; return '' if ($show eq 'all'); # No links if you get them all at once. - my $links; - ## - ## Prev - my $prev_min = $current_min - $show; - $prev_min = 0 if $prev_min < 0; - if ($prev_min < $current_min) { - $links .= qq{ -prev -}; - } else { - $links .= 'prev'; - } - ## - ## Pages.... Someday. - ## - $links .= qq{   -reload -}; - ## - ## Next - my $next_min = $current_min + $show; - $next_min = $current_min if ($next_min > $total); - if ($next_min != $current_min) { - $links .= qq{   -next -}; - } else { - $links .= ' next'; - } - return $links; + # + # Create buttons + my $buttons = ''; + $buttons .= ' 'x3; + $buttons .= 'print(&search_results_header()); + my ($r,$importbutton,$closebutton,$diropendb) = @_; + my $connection = $r->connection; + $r->print(&search_results_header($importbutton,$closebutton)); ## ## Set viewing function ## @@ -1822,108 +2616,192 @@ sub display_results { return; } ## + ## $checkbox_num is a count of the number of checkboxes output on the + ## page this is used only during catalogmode=groupsearch. + my $checkbox_num = 0; + ## ## Get the catalog controls setup ## my $action = "/adm/searchcat?phase=results"; ## - ## - ## + ## Deal with groupsearch by opening the groupsearch db file. if ($ENV{'form.catalogmode'} eq 'groupsearch') { if (! tie(%groupsearch_db,'GDBM_File',$diropendb, - &GDBM_WRCREAT,0640)) { - $r->print('Unable to tie hash to db file'); + &GDBM_WRCREAT(),0640)) { + $r->print('Unable to store import results.'); $r->rflush(); return; } } ## ## Prepare the table for querying - ## my $table = $ENV{'form.table'}; - my $connection_result = &Apache::lonmysql::connect_to_db(); - if (!defined($connection_result)) { - $r->print(&Apache::lonmysql::get_error()); - } - my $table_check = &Apache::lonmysql::check_table($table); - if (! defined($table_check)) { - $r->print("A MySQL error has occurred."); - &Apache::lonnet::logthis("lonmysql was unable to determine the status". - " of table ".$table); - return; - } elsif (! $table_check) { - $r->print("The table of results could not be found."); - &Apache::lonnet::logthis("The user requested a table, ".$table. - ", that could not be found."); - return; - } + return if (! &ensure_db_and_table($r,$table)); ## ## Get the number of results - ## my $total_results = &Apache::lonmysql::number_of_rows($table); if (! defined($total_results)) { - $r->print("A MySQL error has occurred."); + $r->print("A MySQL error has occurred."); &Apache::lonnet::logthis("lonmysql was unable to determine the number". " of rows in table ".$table); &Apache::lonnet::logthis(&Apache::lonmysql::get_error()); - &Apache::lonnet::logthis(&Apache::lonmysql::get_debug()); - return; - } - if ($total_results == 0) { - $r->print("There were no results matching your query.\n". - ""); return; } ## ## Determine how many results we need to get - ## - $ENV{'form.show'} = 20; - $ENV{'form.start'} = 0 if (! exists($ENV{'form.start'})); - $ENV{'form.show'} = 'all' if (! exists($ENV{'form.show'})); + $ENV{'form.start'} = 1 if (! exists($ENV{'form.start'})); + $ENV{'form.show'} = 20 if (! exists($ENV{'form.show'})); + if (exists($ENV{'form.prev'})) { + $ENV{'form.start'} -= $ENV{'form.show'}; + } elsif (exists($ENV{'form.next'})) { + $ENV{'form.start'} += $ENV{'form.show'}; + } + $ENV{'form.start'} = 1 if ($ENV{'form.start'}<1); + $ENV{'form.start'} = $total_results if ($ENV{'form.start'}>$total_results); my $min = $ENV{'form.start'}; my $max; if ($ENV{'form.show'} eq 'all') { $max = $total_results ; } else { - $max = $min + $ENV{'form.show'}; + $max = $min + $ENV{'form.show'} - 1; $max = $total_results if ($max > $total_results); } ## - ## Output links (if necessary) for 'prev' and 'next' pages. + ## Output form elements + $r->print(&hidden_field('table'). + &hidden_field('phase'). + &hidden_field('persistent_db_id'). + &hidden_field('start') + ); + # + # Build sorting selector + my @field_order = ('default', + 'title', + 'author', + 'subject', + 'url', + 'keywords', + 'version', + 'language', + 'creationdate'=>, + 'lastrevisiondate', + 'owner', + 'copyright', + 'authorspace', + 'lowestgradeleve', + 'highestgradelevel', + 'standards', + 'count', + 'stdno', + 'avetries', + 'difficulty', + 'disc', + 'clear', + 'technical', + 'correct', + 'helpful', + 'depth', + ); + my %sort_fields = ('default' => 'Default', + 'title' => 'Title', + 'author' => 'Author', + 'subject' => 'Subject', + 'url' => 'URL', + 'keywords' => 'Keywords', + 'version' => 'Version', + 'language' => 'Language', + 'creationdate'=> 'Creation Date', + 'lastrevisiondate' => 'Last Revision Date', + 'owner' => 'Owner', + 'copyright' => 'Copyright', + 'authorspace' => 'Authorspace', + 'lowestgradeleve' => 'Lowest Grade Level', + 'highestgradelevel' => 'Highest Grade Level', + 'standards' => 'Standards', + 'count' => 'Number of Accesses', + 'stdno' => 'Students Attempting', + 'avetries' => 'Average Number of Tries', + 'difficulty' => 'Mean Degree of Difficulty', + 'disc' => 'Mean Degree of Discrimination', + 'clear' => 'Evaluation: Clear', + 'technical' => 'Evaluation: Technically Correct', + 'correct' => 'Evaluation: Material is Correct', + 'helpful' => 'Evaluation: Material is Helpful', + 'depth' => 'Evaluation: Material has Depth', + 'select_form_order' => \@field_order, + ); + + my $sortform = &mt('Sort by [_1]', + &Apache::loncommon::select_form($ENV{'form.sortfield'}, + 'sortfield', + %sort_fields)); ## - $r->print("
Results $min to $max out of $total_results
\n"); + ## Output links (if necessary) for 'prev' and 'next' pages. $r->print - ('
'. - &prev_next_buttons($min,$ENV{'form.show'},$total_results, - "table=".$ENV{'form.table'}. - "&phase=results". - "&persistent_db_id=".$ENV{'form.persistent_db_id'}) - ."

\n" + ('
'. + $sortform. + ''. + &prev_next_buttons($min,$ENV{'form.show'},$total_results). + ''. + &viewoptions().'
' ); + if ($total_results == 0) { + $r->print(''. + '

'.&mt('There are currently no results').'.

'. + ""); + return; + } else { + $r->print('
'. + mt('Results [_1] to [_2] out of [_3]', + $min,$max,$total_results). + "
\n"); + } ## ## Get results from MySQL table - ## - my @Results = &Apache::lonmysql::get_rows($table, - 'id>'.$min.' AND id<='.$max); + my $sort_command = 'id>='.$min.' AND id<='.$max; + if ($ENV{'form.sortfield'} ne 'default' && + exists($sort_fields{$ENV{'form.sortfield'}})) { + $sort_command = $ENV{'form.sortfield'}.' IS NOT NULL '. + 'ORDER BY '.$ENV{'form.sortfield'}. + ' LIMIT '.($min-1).','.($max-$min); + } + my @Results = &Apache::lonmysql::get_rows($table,$sort_command); ## ## Loop through the results and output them. - ## foreach my $row (@Results) { + if ($connection->aborted()) { + &cleanup(); + return; + } my %Fields = %{&parse_row(@$row)}; my $output="

\n"; - $output.=&catalogmode_output($Fields{'title'},$Fields{'url'}); + if (! defined($Fields{'title'}) || $Fields{'title'} eq '') { + $Fields{'title'} = 'Untitled'; + } + my $prefix=&catalogmode_output($Fields{'title'},$Fields{'url'}, + $Fields{'id'},$checkbox_num++); # Render the result into html - $output.= &$viewfunction(%Fields); - $output.="

\n
"; + $output.= &$viewfunction($prefix,%Fields); # Print them out as they come in. $r->print($output); $r->rflush(); } if (@Results < 1) { - $r->print("There were no results matching your query"); + $r->print(&mt("There were no results matching your query")); + } else { + $r->print + ('
'. + &prev_next_buttons($min,$ENV{'form.show'},$total_results, + "table=".$ENV{'form.table'}. + "&phase=results". + "&persistent_db_id=". + $ENV{'form.persistent_db_id'}) + ."
\n" + ); } - $r->print(""); + $r->print(""); $r->rflush(); - untie %groupsearch_db; + untie %groupsearch_db if (tied(%groupsearch_db)); return; } @@ -1932,24 +2810,20 @@ sub display_results { =pod -=item &catalogmode_output($title,$url) +=item &catalogmode_output($title,$url,$fnum,$checkbox_num) Returns html needed for the various catalog modes. Gets inputs from -$ENV{'form.catalogmode'}. Stores data in %groupsearch_db and $fnum -(local variable). +$ENV{'form.catalogmode'}. Stores data in %groupsearch_db. =cut ###################################################################### ###################################################################### -{ -my $fnum; - sub catalogmode_output { my $output = ''; - my ($title,$url) = @_; + my ($title,$url,$fnum,$checkbox_num) = @_; if ($ENV{'form.catalogmode'} eq 'interactive') { - $title=~ s/\'/\\'/g; # ' Escape single quotes. + $title=~ s/\'/\\\'/g; if ($ENV{'form.catalogmode'} eq 'interactive') { $output.=< +onClick="javascript:queue($checkbox_num,$fnum)" /> END - $fnum++; } return $output; } - -} ###################################################################### ###################################################################### =pod -=item &parse_row +=item &parse_row() Parse a row returned from the database. @@ -1990,11 +2859,14 @@ Parse a row returned from the database. sub parse_row { my @Row = @_; my %Fields; + if (! scalar(@Datatypes)) { + &set_up_table_structure(); + } for (my $i=0;$i<=$#Row;$i++) { - $Fields{$DataOrder[$i]}=&Apache::lonnet::unescape($Row[$i]); + $Fields{$Datatypes[$i]->{'name'}}=&Apache::lonnet::unescape($Row[$i]); } $Fields{'language'} = - &Apache::loncommon::languagedescription($Fields{'lang'}); + &Apache::loncommon::languagedescription($Fields{'language'}); $Fields{'copyrighttag'} = &Apache::loncommon::copyrightdescription($Fields{'copyright'}); $Fields{'mimetag'} = @@ -2010,13 +2882,10 @@ sub parse_row { =item &parse_raw_result() Takes a line from the file of results and parse it. Returns a hash -with keys for the following fields: -'title', 'author', 'subject', 'url', 'keywords', 'version', 'notes', -'abstract', 'mime', 'lang', 'owner', 'copyright', 'creationdate', -'lastrevisiondate'. +with keys according to column labels In addition, the following tags are set by calling the appropriate -lonnet function: 'language', 'cprtag', 'mimetag'. +lonnet function: 'language', 'copyrighttag', 'mimetag'. The 'title' field is set to "Untitled" if the title field is blank. @@ -2028,63 +2897,11 @@ The 'title' field is set to "Untitled" i ########################################################### sub parse_raw_result { my ($result,$hostname) = @_; - # Check for a comma - if it is there then we do not need to unescape the - # string. There seems to be some kind of problem with some items in - # the database - the entire string gets sent out unescaped...? - unless ($result =~ /,/) { - $result = &Apache::lonnet::unescape($result); - } - my @fields=map { - &Apache::lonnet::unescape($_); - } (split(/\,/,$result)); - my ($title,$author,$subject,$url,$keywords,$version, - $notes,$abstract,$mime,$lang, - $creationdate,$lastrevisiondate,$owner,$copyright)=@fields; - my %Fields = - ( title => &Apache::lonnet::unescape($title), - author => &Apache::lonnet::unescape($author), - subject => &Apache::lonnet::unescape($subject), - url => &Apache::lonnet::unescape($url), - keywords => &Apache::lonnet::unescape($keywords), - version => &Apache::lonnet::unescape($version), - notes => &Apache::lonnet::unescape($notes), - abstract => &Apache::lonnet::unescape($abstract), - mime => &Apache::lonnet::unescape($mime), - lang => &Apache::lonnet::unescape($lang), - owner => &Apache::lonnet::unescape($owner), - copyright => &Apache::lonnet::unescape($copyright), - creationdate => &Apache::lonnet::unescape($creationdate), - lastrevisiondate => &Apache::lonnet::unescape($lastrevisiondate) - ); - $Fields{'language'} = - &Apache::loncommon::languagedescription($Fields{'lang'}); - $Fields{'copyrighttag'} = - &Apache::loncommon::copyrightdescription($Fields{'copyright'}); - $Fields{'mimetag'} = - &Apache::loncommon::filedescription($Fields{'mime'}); - if ($Fields{'author'}=~/^(\s*|error)$/) { - $Fields{'author'}="Unknown Author"; - } - # Put spaces in the keyword list, if needed. - $Fields{'keywords'}=~ s/,([A-z])/, $1/g; - if ($Fields{'title'}=~ /^\s*$/ ) { - $Fields{'title'}='Untitled'; - } - unless ($ENV{'user.adv'}) { - # What is this anyway? - $Fields{'keywords'} = '- not displayed -'; - $Fields{'notes'} = '- not displayed -'; - $Fields{'abstract'} = '- not displayed -'; - $Fields{'subject'} = '- not displayed -'; - } - if (length($Fields{'abstract'})>200) { - $Fields{'abstract'} = - substr($Fields{'abstract'},0,200).'...'; - } - if (length($Fields{'keywords'})>200) { - $Fields{'keywords'} = - substr($Fields{'keywords'},0,200).'...'; - } + # conclude from self to others regarding fields + my %Fields=&LONCAPA::lonmetadata::metadata_col_to_hash + (map { + &Apache::lonnet::unescape($_); + } (split(/\,/,$result)) ); return %Fields; } @@ -2134,7 +2951,7 @@ sub handle_custom_fields { =pod -=item &search_results_header +=item &search_results_header() Output the proper html headers and javascript code to deal with different calling modes. @@ -2161,8 +2978,16 @@ Checked for existance & 'edit' mode. =item 'form.form' +Contains the name of the form that has the input fields to set + =item 'form.element' +the name of the input field to put the URL into + +=item 'form.titleelement' + +the name of the input field to put the title into + =back =cut @@ -2170,6 +2995,8 @@ Checked for existance & 'edit' mode. ###################################################################### ###################################################################### sub search_results_header { + my ($importbutton,$closebutton) = @_; + my $bodytag=&Apache::loncommon::bodytag(undef,undef,undef,1); my $result = ''; # output beginning of search page # conditional output of script functions dependent on the mode in @@ -2181,16 +3008,16 @@ sub search_results_header { function select_data(title,url) { changeTitle(title); changeURL(url); - self.close(); + parent.close(); } function changeTitle(val) { - if (opener.inf.document.forms.resinfo.elements.t) { - opener.inf.document.forms.resinfo.elements.t.value=val; + if (parent.opener.inf.document.forms.resinfo.elements.t) { + parent.opener.inf.document.forms.resinfo.elements.t.value=val; } } function changeURL(val) { - if (opener.inf.document.forms.resinfo.elements.u) { - opener.inf.document.forms.resinfo.elements.u.value=val; + if (parent.opener.inf.document.forms.resinfo.elements.u) { + parent.opener.inf.document.forms.resinfo.elements.u.value=val; } } @@ -2198,17 +3025,34 @@ SCRIPT } elsif ($ENV{'form.mode'} eq 'edit') { my $form = $ENV{'form.form'}; my $element = $ENV{'form.element'}; + my $titleelement = $ENV{'form.titleelement'}; + my $changetitle; + if (!$titleelement) { + $changetitle='function changeTitle(val) {}'; + } else { + $changetitle=< function select_data(title,url) { changeURL(url); - self.close(); -} -function changeTitle(val) { + changeTitle(title); + parent.close(); } +$changetitle function changeURL(val) { - if (window.opener.document) { - window.opener.document.forms["$form"].elements["$element"].value=val; + if (parent.targetwin.document) { + parent.targetwin.document.forms["$form"].elements["$element"].value=val; } else { var url = 'forms[\"$form\"].elements[\"$element\"].value'; alert("Unable to transfer data to "+url); @@ -2220,26 +3064,35 @@ SCRIPT } $result.=< SCRIPT $result.=< +$bodytag +
+ +$importbutton END return $result; } @@ -2247,14 +3100,26 @@ END ###################################################################### ###################################################################### sub search_status_header { + my $bodytag=&Apache::loncommon::bodytag(undef,undef,undef,1); + my $html=&Apache::lonxml::xmlbegin(); return <Search Status - +$html + +Search Status +$bodytag

Search Status

Sending search request to LON-CAPA servers.
ENDSTATUS } +sub results_link { + my $basic_link = "/adm/searchcat?"."&table=".$ENV{'form.table'}. + "&persistent_db_id=".$ENV{'form.persistent_db_id'}; + my $results_link = $basic_link."&phase=results". + "&pause=1"."&start=1"; + return $results_link; +} + ###################################################################### ###################################################################### sub print_frames_interface { @@ -2262,11 +3127,15 @@ sub print_frames_interface { my $basic_link = "/adm/searchcat?"."&table=".$ENV{'form.table'}. "&persistent_db_id=".$ENV{'form.persistent_db_id'}; my $run_search_link = $basic_link."&phase=run_search"; - my $results_link = $basic_link."&phase=results". - "&pause=10"."&start=0"."&show=20"; + my $results_link = &results_link(); + my $html=&Apache::lonxml::xmlbegin(); my $result = <<"ENDFRAMES"; - +$html + LON-CAPA Digital Library Search Results @@ -2283,11 +3152,47 @@ ENDFRAMES ###################################################################### ###################################################################### +sub has_stat_data { + my ($values) = @_; + if ( (defined($values->{'count'}) && $values->{'count'} ne '') || + (defined($values->{'stdno'}) && $values->{'stdno'} ne '') || + (defined($values->{'disc'}) && $values->{'disc'} ne '') || + (defined($values->{'avetries'}) && $values->{'avetries'} ne '') || + (defined($values->{'difficulty'}) && $values->{'difficulty'} ne '')) { + return 1; + } + return 0; +} + +sub statfields { + return ('count','stdno','disc','avetries','difficulty'); +} + +sub has_eval_data { + my ($values) = @_; + if ( (defined($values->{'clear'}) && $values->{'clear'} ne '') || + (defined($values->{'technical'}) && $values->{'technical'} ne '') || + (defined($values->{'correct'}) && $values->{'correct'} ne '') || + (defined($values->{'helpful'}) && $values->{'helpful'} ne '') || + (defined($values->{'depth'}) && $values->{'depth'} ne '')) { + return 1; + } + return 0; +} + +sub evalfields { + return ('clear','technical','correct','helpful','depth'); +} + +###################################################################### +###################################################################### + =pod =item Metadata Viewing Functions Output is a HTML-ified string. + Input arguments are title, author, subject, url, keywords, version, notes, short abstract, mime, language, creation date, last revision date, owner, copyright, hostname, and @@ -2302,25 +3207,109 @@ extra custom metadata to show. ###################################################################### ###################################################################### sub detailed_citation_view { - my %values = @_; - my $result=<$values{'title'} -

-$values{'author'}, $values{'owner'}
- -Subject: $values{'subject'}
-Keyword(s): $values{'keywords'}
-Notes: $values{'notes'}
-MIME Type: $values{'mimetag'}
-Language: $values{'language'}
-Copyright/Distribution: $values{'cprtag'}
-

-$values{'extrashow'} -

-$values{'shortabstract'} -

-END + my ($prefix,%values) = @_; + my $result; + $result .= ''.$prefix. + ''.' '. + ''.$values{'title'}."\n"; + $result .= "

\n"; + $result .= ''.$values{'author'}.','. + ' '.$values{'owner'}.'
'; + foreach my $field + ( + { name=>'url', + translate => 'URL: [_1]', + special => 'url link',}, + { name=>'subject', + translate => 'Subject: [_1]',}, + { name=>'keywords', + translate => 'Keywords: [_1]',}, + { name=>'notes', + translate => 'Notes: [_1]',}, + { name=>'mimetag', + translate => 'MIME Type: [_1]',}, + { name=>'standards', + translate => 'Standards:[_1]',}, + { name=>'copyrighttag', + translate => 'Copyright/Distribution: [_1]',}, + { name=>'count', + format => "%d", + translate => 'Access Count: [_1]',}, + { name=>'stdno', + format => "%d", + translate => 'Number of Students: [_1]',}, + { name=>'avetries', + format => "%.2f", + translate => 'Average Tries: [_1]',}, + { name=>'disc', + format => "%.2f", + translate => 'Degree of Discrimination: [_1]',}, + { name=>'difficulty', + format => "%.2f", + translate => 'Degree of Difficulty: [_1]',}, + { name=>'clear', + format => "%.2f", + translate => 'Clear: [_1]',}, + { name=>'depth', + format => "%.2f", + translate => 'Depth: [_1]',}, + { name=>'helpful', + format => "%.2f", + translate => 'Helpful: [_1]',}, + { name=>'correct', + format => "%.2f", + translate => 'Correct: [_1]',}, + { name=>'technical', + format => "%.2f", + translate => 'Technical: [_1]',}, + { name=>'comefrom_list', + type => 'list', + translate => 'Resources that lead up to this resource in maps',}, + { name=>'goto_list', + type => 'list', + translate => 'Resources that follow this resource in maps',}, + { name=>'sequsage_list', + type => 'list', + translate => 'Resources using or importing resource',}, + ) { + next if (! exists($values{$field->{'name'}}) || + $values{$field->{'name'}} eq ''); + if (exists($field->{'type'}) && $field->{'type'} eq 'list') { + $result .= ''.&mt($field->{'translate'}).'

    '; + foreach my $item (split(',',$values{$field->{'name'}})){ + $result .= '
  • '. + ''.$item.'
  • '; + } + $result .= '
'; + } elsif (exists($field->{'format'}) && $field->{'format'} ne ''){ + $result.= &mt($field->{'translate'}, + sprintf($field->{'format'}, + $values{$field->{'name'}}))."
\n"; + } else { + if ($field->{'special'} eq 'url link') { + $result.= + &mt($field->{'translate'}, + ''. + $values{$field->{'name'}}. + ''); + } else { + $result.= &mt($field->{'translate'}, + $values{$field->{'name'}}); + } + $result .= "
\n"; + } + } + $result .= "

"; + if (exists($values{'extrashow'}) && $values{'extrashow'} ne '') { + $result .= '

'.$values{'extrashow'}.'

'; + } + if (exists($values{'shortabstract'}) && $values{'shortabstract'} ne '') { + $result .= '

'.$values{'shortabstract'}.'

'; + } + $result .= '
'."\n"; return $result; } @@ -2335,8 +3324,10 @@ END ###################################################################### ###################################################################### sub summary_view { - my %values = @_; + my ($prefix,%values) = @_; + my $icon=&Apache::loncommon::icon($values{'url'}); my $result=<  $values{'author'}
$values{'title'}
@@ -2344,6 +3335,7 @@ $values{'owner'} -- $values{'lastrevisio $values{'copyrighttag'}
$values{'extrashow'}

+
END return $result; } @@ -2353,6 +3345,28 @@ END =pod +=item &compact_view() + +=cut + +###################################################################### +###################################################################### +sub compact_view { + my ($prefix,%values) = @_; + my $result = + $prefix.' '. + $values{'title'}.''.(' 'x2). + ''.$values{'author'}.'
'; + return $result; +} + + +###################################################################### +###################################################################### + +=pod + =item &fielded_format_view() =cut @@ -2360,27 +3374,37 @@ END ###################################################################### ###################################################################### sub fielded_format_view { - my %values = @_; + my ($prefix,%values) = @_; + my $icon=&Apache::loncommon::icon($values{'url'}); + my %Translated = &Apache::lonmeta::fieldnames(); my $result=<URL: $values{'url'} -
-Title: $values{'title'}
-Author(s): $values{'author'}
-Subject: $values{'subject'}
-Keyword(s): $values{'keywords'}
-Notes: $values{'notes'}
-MIME Type: $values{'mimetag'}
-Language: $values{'language'}
-Creation Date: $values{'creationdate'}
-Last Revision Date: $values{'lastrevisiondate'}
-Publisher/Owner: $values{'owner'}
-Copyright/Distribution: $values{'copyrighttag'}
-Repository Location: $values{'hostname'}
-Abstract: $values{'shortabstract'}
-$values{'extrashow'} -

+$prefix +
+
URL:
+
$values{'url'}
END + foreach my $field ('title','author','subject','keywords','notes', + 'mimetag','language','creationdate','lastrevisiondate', + 'owner','copyrighttag','hostname','abstract') { + $result .= (' 'x4).'
'.$Translated{$field}.'
'."\n". + (' 'x8).'
'.$values{$field}.'
'."\n"; + } + if (&has_stat_data(\%values)) { + foreach my $field (&statfields()) { + $result .= (' 'x4).'
'.$Translated{$field}.'
'."\n". + (' 'x8).'
'.$values{$field}.'
'."\n"; + } + } + if (&has_eval_data(\%values)) { + foreach my $field (&evalfields()) { + $result .= (' 'x4).'
'.$Translated{$field}.'
'."\n". + (' 'x8).'
'.$values{$field}.'
'."\n"; + } + } + $result .= "
\n"; + $result .= $values{'extrashow'}; + $result .= '
'."\n"; return $result; } @@ -2398,36 +3422,63 @@ END ###################################################################### ###################################################################### sub xml_sgml_view { - my %values = @_; + my ($prefix,%values) = @_; + my $xml = ''."\n"; + # The usual suspects + foreach my $field ('url','title','author','subject','keywords','notes') { + $xml .= qq{<$field>$values{$field}}."\n"; + } + # + $xml .= "\n"; + foreach my $field ('mime','mimetag') { + $xml .= qq{<$field>$values{$field}}."\n"; + } + $xml .= "\n"; + # + $xml .= "\n"; + foreach my $field ('language','languagetag') { + $xml .= qq{<$field>$values{$field}}."\n"; + } + $xml .= "\n"; + # + foreach my $field ('creationdate','lastrevisiondate','owner') { + $xml .= qq{<$field>$values{$field}}."\n"; + } + # + $xml .= "\n"; + foreach my $field ('copyright','copyrighttag') { + $xml .= qq{<$field>$values{$field}}."\n"; + } + $xml .= "\n"; + $xml .= qq{$values{'hostname'}}. + "\n"; + $xml .= qq{$values{'shortabstract'}}."\n"; + # + if (&has_stat_data(\%values)){ + $xml .= "\n"; + foreach my $field (&statfields()) { + $xml .= qq{<$field>$values{$field}}."\n"; + } + $xml .= "\n"; + } + # + if (&has_eval_data(\%values)) { + $xml .= "\n"; + foreach my $field (&evalfields) { + $xml .= qq{<$field>$values{$field}}."\n"; + } + $xml .= "\n"; + } + # + $xml .= "\n"; + $xml = &HTML::Entities::encode($xml,'<>&'); my $result=< -<LonCapaResource> -<url>$values{'url'}</url> -<title>$values{'title'}</title> -<author>$values{'author'}</author> -<subject>$values{'subject'}</subject> -<keywords>$values{'keywords'}</keywords> -<notes>$values{'notes'}</notes> -<mimeInfo> -<mime>$values{'mime'}</mime> -<mimetag>$values{'mimetag'}</mimetag> -</mimeInfo> -<languageInfo> -<language>$values{'lang'}</language> -<languagetag>$values{'language'}</languagetag> -</languageInfo> -<creationdate>$values{'creationdate'}</creationdate> -<lastrevisiondate>$values{'lastrevisiondate'}</lastrevisiondate> -<owner>$values{'owner'}</owner> -<copyrightInfo> -<copyright>$values{'copyright'}</copyright> -<copyrighttag>$values{'copyrighttag'}</copyrighttag> -</copyrightInfo> -<repositoryLocation>$values{'hostname'}</repositoryLocation> -<shortabstract>$values{'shortabstract'}</shortabstract> -</LonCapaResource> +$xml $values{'extrashow'} +
END return $result; } @@ -2446,11 +3497,56 @@ END sub filled { my ($field)=@_; if ($field=~/\S/ && $field ne 'any') { - return 1; + return 1; + } else { + return 0; } - else { - return 0; +} + +###################################################################### +###################################################################### + +=pod + +=item &output_unparsed_phrase_error() + +=cut + +###################################################################### +###################################################################### +sub output_unparsed_phrase_error { + my ($r,$closebutton,$parms,$hidden_fields,$field)=@_; + my $errorstring; + if ($field eq 'basicexp') { + $errorstring = &mt('Unable to understand the search phrase [_1]. Please modify your search.',$ENV{'form.basicexp'}); + } else { + $errorstring = &mt('Unable to understand the search phrase [_1]:[_2].',$field,$ENV{'form.'.$field}); } + my $bodytag = &Apache::loncommon::bodytag('Search'); + my $heading = &mt('Unparsed Field'); + my $revise = &mt('Revise search request'); + # make query information persistent to allow for subsequent revision + my $html=&Apache::lonxml::xmlbegin(); + $r->print(< +The LearningOnline Network with CAPA + +$bodytag + +$hidden_fields +$closebutton +
+

$heading

+

+$errorstring +

+

+$revise +

+ + +ENDPAGE } ###################################################################### @@ -2460,39 +3556,47 @@ sub filled { =item &output_blank_field_error() +Output a complete page that indicates the user has not filled in enough +information to do a search. + +Inputs: $r (Apache request handle), $closebutton, $parms. + +Returns: nothing + +$parms is extra information to include in the 'Revise search request' link. + =cut ###################################################################### ###################################################################### sub output_blank_field_error { - my ($r,$closebutton)=@_; - # make query information persistent to allow for subsequent revision - $r->print(< + my ($r,$closebutton,$parms,$hidden_fields)=@_; + my $bodytag=&Apache::loncommon::bodytag('Search'); + 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.'); + my $revise = &mt('Revise Search Request'); + my $heading = &mt('Unactionable Search Queary'); + my $html=&Apache::lonxml::xmlbegin(); + $r->print(< The LearningOnline Network with CAPA -BEGINNING - $r->print(< - - -

Search Catalog

+$bodytag $hidden_fields -Revise search request  $closebutton
-

Helpful Message

+

$heading

+

+$errormsg +

-Incorrect search query due to blank entry fields. -You need to fill in the relevant -fields on the search page in order for a query to be -processed. +$revise 

-RESULTS +ENDPAGE + return; } ###################################################################### @@ -2515,14 +3619,16 @@ Inputs: ###################################################################### ###################################################################### sub output_date_error { - my ($r,$message,$closebutton)=@_; + my ($r,$message,$closebutton,$hidden_fields)=@_; # make query information persistent to allow for subsequent revision + my $bodytag=&Apache::loncommon::bodytag(undef,undef,undef,1); + my $html=&Apache::lonxml::xmlbegin(); $r->print(< +$html The LearningOnline Network with CAPA - +$bodytag

Search Catalog

@@ -2531,7 +3637,7 @@ $hidden_fields onClick='this.form.submit();' /> $closebutton
-

Helpful Message

+

Error

$message

@@ -2568,6 +3674,16 @@ sub start_fresh_session { 1; +sub cleanup { + if (tied(%groupsearch_db)) { + unless (untie(%groupsearch_db)) { + &Apache::lonnet::logthis('Failed cleanup searchcat: groupsearch_db'); + } + } + &untiehash(); + &Apache::lonmysql::disconnect_from_db(); +} + __END__ =pod