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

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

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