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

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

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