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

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

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