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

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

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