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

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

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