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

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

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