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

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

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