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

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

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