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

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

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