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

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

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