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

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

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