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

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

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