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

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

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