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

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

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