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

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

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