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

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

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