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

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

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