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

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

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