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

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

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