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

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

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