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

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

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