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

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

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