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

1.98      harris41    1: # The LearningOnline Network with CAPA
1.108     harris41    2: # Search Catalog
                      3: #
1.256   ! albertel    4: # $Id: lonsearchcat.pm,v 1.255 2006/03/06 18:23:10 www Exp $
1.108     harris41    5: #
                      6: # Copyright Michigan State University Board of Trustees
                      7: #
                      8: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
                      9: #
                     10: # LON-CAPA is free software; you can redistribute it and/or modify
                     11: # it under the terms of the GNU General Public License as published by
                     12: # the Free Software Foundation; either version 2 of the License, or
                     13: # (at your option) any later version.
1.98      harris41   14: #
1.108     harris41   15: # LON-CAPA is distributed in the hope that it will be useful,
                     16: # but WITHOUT ANY WARRANTY; without even the implied warranty of
                     17: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
                     18: # GNU General Public License for more details.
                     19: #
                     20: # You should have received a copy of the GNU General Public License
                     21: # along with LON-CAPA; if not, write to the Free Software
                     22: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
                     23: #
                     24: # /home/httpd/html/adm/gpl.txt
                     25: #
                     26: # http://www.lon-capa.org/
1.1       www        27: #
1.121     matthew    28: ###############################################################################
                     29: ###############################################################################
                     30: 
                     31: =pod 
                     32: 
                     33: =head1 NAME
                     34: 
1.140     matthew    35: lonsearchcat - LONCAPA Search Interface
1.121     matthew    36: 
                     37: =head1 SYNOPSIS
                     38: 
                     39: Search interface to LON-CAPAs digital library
                     40: 
                     41: =head1 DESCRIPTION
                     42: 
                     43: This module enables searching for a distributed browseable catalog.
1.104     harris41   44: 
1.121     matthew    45: This is part of the LearningOnline Network with CAPA project
                     46: described at http://www.lon-capa.org.
                     47: 
                     48: lonsearchcat presents the user with an interface to search the LON-CAPA
                     49: digital library.  lonsearchcat also initiates the execution of a search
                     50: by sending the search parameters to LON-CAPA servers.  The progress of 
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.243     albertel   66: use Apache::lonnet;
1.6       harris41   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.228     matthew    78: use Parse::RecDescent;
1.231     raeburn    79: use Apache::lonnavmaps;
1.255     www        80: use Apache::lonindexer();
1.1       www        81: 
1.121     matthew    82: ######################################################################
                     83: ######################################################################
1.196     matthew    84: ##
                     85: ## Global variables
                     86: ##
1.121     matthew    87: ######################################################################
                     88: ######################################################################
1.196     matthew    89: my %groupsearch_db;  # Database hash used to save values for the 
                     90:                      # groupsearch RAT interface.
                     91: my %persistent_db;   # gdbm hash which holds data which is supposed to
                     92:                      # persist across calls to lonsearchcat.pm
1.121     matthew    93: 
1.200     www        94: # The different view modes and associated functions
                     95: 
                     96: my %Views = ("detailed" => \&detailed_citation_view,
1.255     www        97:              "detailedpreview" => \&detailed_citation_preview,
1.200     www        98: 	     "summary"  => \&summary_view,
1.255     www        99:              "summarypreview" => \&summary_preview,
1.200     www       100: 	     "fielded"  => \&fielded_format_view,
                    101: 	     "xml"      => \&xml_sgml_view,
                    102: 	     "compact"  => \&compact_view);
1.101     harris41  103: 
1.121     matthew   104: ######################################################################
                    105: ######################################################################
1.98      harris41  106: sub handler {
                    107:     my $r = shift;
1.197     www       108: #    &set_defaults();
1.196     matthew   109:     #
                    110:     # set form defaults
1.145     matthew   111:     #
1.196     matthew   112:     my $hidden_fields;# Hold all the hidden fields used to keep track
                    113:                       # of the search system state
                    114:     my $importbutton; # button to take the selected results and go to group 
                    115:                       # sorting
                    116:     my $diropendb;    # The full path to the (temporary) search database file.
                    117:                       # This is set and used in &handler() and is also used in 
                    118:                       # &output_results().
                    119:     my $bodytag;  # LON-CAPA standard body tag, gotten from 
                    120:                   # &Apache::lonnet::bodytag. 
                    121:                   # No title, no table, just a <body> tag.
1.157     www       122: 
                    123:     my $loaderror=&Apache::lonnet::overloaderror($r);
                    124:     if ($loaderror) { return $loaderror; }
1.221     matthew   125:     #
1.145     matthew   126:     my $closebutton;  # button that closes the search window 
                    127:                       # This button is different for the RAT compared to
                    128:                       # normal invocation.
                    129:     #
1.186     www       130:     &Apache::loncommon::content_type($r,'text/html');
1.98      harris41  131:     $r->send_http_header;
                    132:     return OK if $r->header_only;
1.156     matthew   133:     ##
                    134:     ## Prevent caching of the search interface window.  Hopefully this means
                    135:     ## we will get the launch=1 passed in a little more.
                    136:     &Apache::loncommon::no_cache($r);
1.145     matthew   137:     ## 
                    138:     ## Pick up form fields passed in the links.
                    139:     ##
                    140:     &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
1.146     matthew   141:              ['catalogmode','launch','acts','mode','form','element','pause',
1.158     matthew   142:               'phase','persistent_db_id','table','start','show',
1.191     albertel  143:               'cleargroupsort','titleelement']);
1.146     matthew   144:     ##
                    145:     ## The following is a trick - we wait a few seconds if asked to so
                    146:     ##     the daemon running the search can get ahead of the daemon
                    147:     ##     printing the results.  We only need (theoretically) to do
                    148:     ##     this once, so the pause indicator is deleted
                    149:     ##
1.243     albertel  150:     if (exists($env{'form.pause'})) {
1.181     matthew   151:         sleep(1);
1.243     albertel  152:         delete($env{'form.pause'});
1.146     matthew   153:     }
1.143     matthew   154:     ##
                    155:     ## Initialize global variables
                    156:     ##
1.121     matthew   157:     my $domain  = $r->dir_config('lonDefDomain');
1.213     matthew   158:     $diropendb= "/home/httpd/perl/tmp/".
1.243     albertel  159:         "$env{'user.domain'}_$env{'user.name'}_searchcat.db";
1.145     matthew   160:     #
                    161:     # set the name of the persistent database
1.243     albertel  162:     #          $env{'form.persistent_db_id'} can only have digits in it.
                    163:     if (! exists($env{'form.persistent_db_id'}) ||
                    164:         ($env{'form.persistent_db_id'} =~ /\D/) ||
                    165:         ($env{'form.launch'} eq '1')) {
                    166:         $env{'form.persistent_db_id'} = time;
1.145     matthew   167:     }
1.155     matthew   168:     $bodytag=&Apache::loncommon::bodytag(undef,undef,undef,1);
1.146     matthew   169:     my $persistent_db_file = "/home/httpd/perl/tmp/".
1.145     matthew   170:         &Apache::lonnet::escape($domain).
1.243     albertel  171:             '_'.&Apache::lonnet::escape($env{'user.name'}).
                    172:                 '_'.$env{'form.persistent_db_id'}.'_persistent_search.db';
1.146     matthew   173:     ##
1.209     matthew   174:     &Apache::lonhtmlcommon::clear_breadcrumbs();
1.243     albertel  175:     if (exists($env{'request.course.id'}) && $env{'request.course.id'} ne '') {
1.209     matthew   176:         &Apache::lonhtmlcommon::add_breadcrumb
                    177:              ({href=>'/adm/searchcat?'.
1.243     albertel  178:                    'catalogmode='.$env{'form.catalogmode'}.
                    179:                    '&launch='.$env{'form.launch'}.
                    180:                    '&mode='.$env{'form.mode'},
1.209     matthew   181:               text=>"Course and Catalog Search",
1.227     matthew   182:               target=>'_top',
1.209     matthew   183:               bug=>'Searching',});
                    184:     } else {
                    185:         &Apache::lonhtmlcommon::add_breadcrumb
                    186:              ({href=>'/adm/searchcat?'.
1.243     albertel  187:                    'catalogmode='.$env{'form.catalogmode'}.
                    188:                    '&launch='.$env{'form.launch'}.
                    189:                    '&mode='.$env{'form.mode'},
1.209     matthew   190:               text=>"Catalog Search",
1.227     matthew   191:               target=>'_top',
1.209     matthew   192:               bug=>'Searching',});
                    193:     }
                    194:     #
1.243     albertel  195:     if ($env{'form.phase'} !~ m/(basic|adv|course)_search/) {
1.221     matthew   196:         if (! &get_persistent_form_data($persistent_db_file)) {
1.243     albertel  197:             if ($env{'form.phase'} =~ /(run_search|results)/) {
1.221     matthew   198:                 &Apache::lonnet::logthis('lonsearchcat:'.
                    199:                                          'Unable to recover data from '.
                    200:                                          $persistent_db_file);
1.256   ! albertel  201: 		my $msg =
        !           202: 		    'We were unable to retrieve data describing your search. '.
        !           203: 		    'This is a serious error and has been logged. '.
        !           204: 		    'Please alert your LON-CAPA administrator.';
        !           205: 		return &error_page($r,$msg);
1.221     matthew   206:             }
1.150     matthew   207:         }
1.221     matthew   208:     } else {
                    209:         &clean_up_environment();
1.147     matthew   210:     }
1.124     matthew   211:     ##
1.143     matthew   212:     ## Clear out old values from groupsearch database
1.124     matthew   213:     ##
1.146     matthew   214:     untie %groupsearch_db if (tied(%groupsearch_db));
1.243     albertel  215:     if (($env{'form.cleargroupsort'} eq '1') || 
                    216:         (($env{'form.launch'} eq '1') && 
                    217:          ($env{'form.catalogmode'} eq 'groupsearch'))) {
1.148     matthew   218: 	if (tie(%groupsearch_db,'GDBM_File',$diropendb,&GDBM_WRCREAT(),0640)) {
1.101     harris41  219: 	    &start_fresh_session();
1.142     matthew   220: 	    untie %groupsearch_db;
1.243     albertel  221:             delete($env{'form.cleargroupsort'});
1.122     matthew   222: 	} else {
1.155     matthew   223:             # This is a stupid error to give to the user.  
                    224:             # It really tells them nothing.
1.256   ! albertel  225: 	    my $msg = 'Unable to tie hash to db file.';
        !           226: 	    return &error_page($r,$msg);
1.101     harris41  227: 	}
                    228:     }
1.124     matthew   229:     ##
1.150     matthew   230:     ## Configure hidden fields
1.124     matthew   231:     ##
1.145     matthew   232:     $hidden_fields = '<input type="hidden" name="persistent_db_id" value="'.
1.243     albertel  233:         $env{'form.persistent_db_id'}.'" />'."\n";
                    234:     if (exists($env{'form.catalogmode'})) {
1.223     matthew   235:         $hidden_fields .= &hidden_field('catalogmode');
1.150     matthew   236:     }
1.243     albertel  237:     if (exists($env{'form.form'})) {
1.223     matthew   238:         $hidden_fields .= &hidden_field('form');
1.150     matthew   239:     }
1.243     albertel  240:     if (exists($env{'form.element'})) {
1.223     matthew   241:         $hidden_fields .= &hidden_field('element');
1.150     matthew   242:     }
1.243     albertel  243:     if (exists($env{'form.titleelement'})) {
1.223     matthew   244:         $hidden_fields .= &hidden_field('titleelement');
1.191     albertel  245:     }
1.243     albertel  246:     if (exists($env{'form.mode'})) {
1.223     matthew   247:         $hidden_fields .= &hidden_field('mode');
1.150     matthew   248:     }
                    249:     ##
                    250:     ## Configure dynamic components of interface
1.146     matthew   251:     ##
1.243     albertel  252:     if ($env{'form.catalogmode'} eq 'interactive') {
1.150     matthew   253:         $closebutton="<input type='button' name='close' value='CLOSE' ";
1.243     albertel  254:         if ($env{'form.phase'} =~ /(results|run_search)/) {
1.150     matthew   255: 	    $closebutton .="onClick='parent.close()'";
                    256:         } else {
                    257:             $closebutton .="onClick='self.close()'";
                    258:         }
                    259:         $closebutton .=">\n";
1.243     albertel  260:     } elsif ($env{'form.catalogmode'} eq 'groupsearch') {
1.150     matthew   261:         $closebutton="<input type='button' name='close' value='CLOSE' ";
1.243     albertel  262:         if ($env{'form.phase'} =~ /(results|run_search)/) {
1.150     matthew   263: 	    $closebutton .="onClick='parent.close()'";
                    264:         } else {
                    265:             $closebutton .="onClick='self.close()'";
                    266:         }
                    267:         $closebutton .= ">";
1.98      harris41  268:         $importbutton=<<END;
                    269: <input type='button' name='import' value='IMPORT'
                    270: onClick='javascript:select_group()'>
                    271: END
1.146     matthew   272:     } else {
                    273:         $closebutton = '';
                    274:         $importbutton = '';
1.98      harris41  275:     }
1.124     matthew   276:     ##
1.146     matthew   277:     ## Sanity checks on form elements
1.124     matthew   278:     ##
1.243     albertel  279:     if (!defined($env{'form.viewselect'})) {
1.248     www       280: 	$env{'form.viewselect'} ="summary";
1.146     matthew   281:     }
1.243     albertel  282:     $env{'form.phase'} = 'disp_basic' if (! exists($env{'form.phase'}));
                    283:     $env{'form.show'} = 20 if (! exists($env{'form.show'}));
1.209     matthew   284:     #
1.243     albertel  285:     $env{'form.searchmode'} = 'basic' if (! exists($env{'form.searchmode'}));
                    286:     if ($env{'form.phase'} eq 'adv_search' ||
                    287:         $env{'form.phase'} eq 'disp_adv') {
                    288:         $env{'form.searchmode'} = 'advanced';
                    289:     } elsif ($env{'form.phase'} eq 'course_search') {
                    290:         $env{'form.searchmode'} = 'course_search';
1.209     matthew   291:     }
                    292:     #
1.243     albertel  293:     if ($env{'form.searchmode'} eq 'advanced') {
1.209     matthew   294:         &Apache::lonhtmlcommon::add_breadcrumb
                    295:             ({href=>'/adm/searchcat?phase=disp_adv&'.
1.243     albertel  296:                   'catalogmode='.$env{'form.catalogmode'}.
                    297:                   '&launch='.$env{'form.launch'}.
                    298:                   '&mode='.$env{'form.mode'},
1.209     matthew   299:                   text=>"Advanced Search",
                    300:                   bug=>'Searching',});
1.243     albertel  301:     } elsif ($env{'form.searchmode'} eq 'course search') {
1.209     matthew   302:         &Apache::lonhtmlcommon::add_breadcrumb
                    303:             ({href=>'/adm/searchcat?phase=disp_adv&'.
1.243     albertel  304:                   'catalogmode='.$env{'form.catalogmode'}.
                    305:                   '&launch='.$env{'form.launch'}.
                    306:                   '&mode='.$env{'form.mode'},
1.209     matthew   307:                   text=>"Course Search",
                    308:                   bug=>'Searching',});
                    309:     }
1.146     matthew   310:     ##
                    311:     ## Switch on the phase
                    312:     ##
1.243     albertel  313:     if ($env{'form.phase'} eq 'disp_basic') {
1.196     matthew   314:         &print_basic_search_form($r,$closebutton,$hidden_fields);
1.243     albertel  315:     } elsif ($env{'form.phase'} eq 'disp_adv') {
1.196     matthew   316:         &print_advanced_search_form($r,$closebutton,$hidden_fields);
1.243     albertel  317:     } elsif ($env{'form.phase'} eq 'results') {
1.196     matthew   318:         &display_results($r,$importbutton,$closebutton,$diropendb);
1.243     albertel  319:     } elsif ($env{'form.phase'} =~ /^(sort|run_search)$/) {
1.146     matthew   320:         my ($query,$customquery,$customshow,$libraries,$pretty_string) =
                    321:             &get_persistent_data($persistent_db_file,
                    322:                  ['query','customquery','customshow',
                    323:                   'libraries','pretty_string']);
1.243     albertel  324:         if ($env{'form.phase'} eq 'sort') {
1.151     matthew   325:             &print_sort_form($r,$pretty_string);
1.243     albertel  326:         } elsif ($env{'form.phase'} eq 'run_search') {
1.151     matthew   327:             &run_search($r,$query,$customquery,$customshow,
                    328:                         $libraries,$pretty_string);
                    329:         }
1.243     albertel  330:     } elsif ($env{'form.phase'} eq 'course_search') {
1.167     www       331:         &course_search($r);
1.243     albertel  332:     } elsif(($env{'form.phase'} eq 'basic_search') ||
                    333:             ($env{'form.phase'} eq 'adv_search')) {
1.228     matthew   334:         #
                    335:         # We are running a search, try to parse it
                    336:         my ($query,$customquery,$customshow,$libraries) = 
                    337:             (undef,undef,undef,undef);
                    338:         my $pretty_string;
1.243     albertel  339:         if ($env{'form.phase'} eq 'basic_search') {
1.228     matthew   340:             ($query,$pretty_string,$libraries) = 
                    341:                 &parse_basic_search($r,$closebutton,$hidden_fields);
                    342:             return OK if (! defined($query));
1.243     albertel  343:             &make_persistent({ basicexp => $env{'form.basicexp'}},
1.228     matthew   344:                              $persistent_db_file);
                    345:         } else {                      # Advanced search
                    346:             ($query,$customquery,$customshow,$libraries,$pretty_string) 
                    347:                 = &parse_advanced_search($r,$closebutton,$hidden_fields);
                    348:             return OK if (! defined($query));
                    349:         }
                    350:         &make_persistent({ query => $query,
                    351:                            customquery => $customquery,
                    352:                            customshow => $customshow,
                    353:                            libraries => $libraries,
                    354:                            pretty_string => $pretty_string },
                    355:                          $persistent_db_file);
                    356:         #
1.146     matthew   357:         # Set up table
                    358:         if (! defined(&create_results_table())) {
1.198     www       359: 	    my $errorstring=&Apache::lonmysql::get_error();
1.211     matthew   360:             &Apache::lonnet::logthis('lonsearchcat.pm: Unable to create '.
                    361:                                      'needed table.  lonmysql error:'.
                    362:                                      $errorstring);
1.256   ! albertel  363: 
        !           364: 	    my $msg = 
        !           365: 		'Unable to create table in which to store search results. '.
        !           366: 		'The search has been aborted.';
        !           367: 	    return &error_page($r,$msg);
1.146     matthew   368:         }
1.243     albertel  369:         delete($env{'form.launch'});
1.146     matthew   370:         if (! &make_form_data_persistent($r,$persistent_db_file)) {
1.256   ! albertel  371: 	    my $msg=
        !           372: 		'Unable to properly store search information. '.
        !           373: 		'The search has been aborted.';
        !           374:             return &error_page($r,$msg);
        !           375: 	}
1.145     matthew   376:         ##
1.146     matthew   377:         ## Print out the frames interface
1.145     matthew   378:         ##
1.228     matthew   379:         if (defined($query)) {
                    380:             &print_frames_interface($r);
                    381:         }
1.124     matthew   382:     }
                    383:     return OK;
                    384: } 
1.98      harris41  385: 
1.256   ! albertel  386: sub error_page {
        !           387:     my ($r,$msg) = @_;
        !           388:     $r->print(&Apache::loncommon::start_page('Search Error').
        !           389: 	      &mt($msg).
        !           390: 	      &Apache::loncommon::end_page());
        !           391:     return OK;
        !           392: }
        !           393: 
1.221     matthew   394: #
                    395: # The mechanism used to store values away and retrieve them does not
                    396: # handle the case of missing environment variables being significant.
                    397: #
                    398: # This routine sets non existant checkbox form elements to ''.
                    399: #
                    400: sub clean_up_environment {
1.243     albertel  401:     if ($env{'form.phase'} eq 'basic_search') {
                    402:         if (! exists($env{'form.related'})) {
                    403:             $env{'form.related'} = '';
1.221     matthew   404:         }
1.243     albertel  405:         if (! exists($env{'form.domains'})) {
                    406:             $env{'form.domains'} = '';
1.221     matthew   407:         }
1.243     albertel  408:     } elsif ($env{'form.phase'} eq 'adv_search') {
1.221     matthew   409:         foreach my $field ('title','keywords','notes',
                    410:                            'abstract','standards','mime') {
1.243     albertel  411:             if (! exists($env{'form.'.$field.'_related'})) {
                    412:                 $env{'form.'.$field.'_related'} = '';
1.221     matthew   413:             }
                    414:         }
1.243     albertel  415:     } elsif ($env{'form.phase'} eq 'course_search') {
                    416:         if (! exists($env{'form.crsrelated'})) {
                    417:             $env{'form.crsrelated'} = '';
1.221     matthew   418:         }
                    419:     }
                    420: }
                    421: 
1.223     matthew   422: sub hidden_field {
                    423:     my ($name,$value) = @_;
                    424:     if (! defined($value)) {
1.243     albertel  425:         $value = $env{'form.'.$name};
1.223     matthew   426:     }
                    427:     return '<input type="hidden" name="'.$name.'" value="'.$value.'" />'.$/;
                    428: }
                    429: 
1.124     matthew   430: ######################################################################
                    431: ######################################################################
1.196     matthew   432: ##
                    433: ##   Course Search
                    434: ##
                    435: ######################################################################
                    436: ######################################################################
                    437: {   # Scope the course search to avoid global variables
                    438: #
                    439: # Variables For course search
1.236     albertel  440: my %alreadyseen;
1.196     matthew   441: my %hash;
                    442: my $totalfound;
1.124     matthew   443: 
1.235     albertel  444: sub make_symb {
                    445:     my ($id)=@_;
                    446:     my ($mapid,$resid)=split(/\./,$id);
                    447:     my $map=$hash{'map_id_'.$mapid};
                    448:     my $res=$hash{'src_'.$id};
                    449:     my $symb=&Apache::lonnet::encode_symb($map,$resid,$res);
                    450:     return $symb;
                    451: }
                    452: 
1.167     www       453: sub course_search {
                    454:     my $r=shift;
1.243     albertel  455:     my $pretty_search_string = '<b>'.$env{'form.courseexp'}.'</b>';
                    456:     my $search_string = $env{'form.courseexp'};
1.167     www       457:     my @New_Words;
1.236     albertel  458:     undef(%alreadyseen);
1.243     albertel  459:     if ($env{'form.crsrelated'}) {
                    460:         ($search_string,@New_Words) = &related_version($env{'form.courseexp'});
1.167     www       461:         if (@New_Words) {
1.200     www       462:             $pretty_search_string .= ' '.&mt("with related words").": <b>@New_Words</b>.";
1.167     www       463:         } else {
1.200     www       464:             $pretty_search_string .= ' '.&mt('with no related words').".";
1.167     www       465:         }
                    466:     }
1.243     albertel  467:     my $fulltext=$env{'form.crsfulltext'};
                    468:     my $discuss=$env{'form.crsdiscuss'};
1.167     www       469:     my @allwords=($search_string,@New_Words);
1.169     www       470:     $totalfound=0;
1.256   ! albertel  471:     $r->print(&Apache::loncommon::start_page('Course Search').
        !           472: 	      '<hr /><center><font size="+2" face="arial">'.
        !           473: 	      $pretty_search_string.'</font></center>'.
        !           474: 	      '<hr /><b>'.&mt('Course content').':</b><br />');
1.167     www       475:     $r->rflush();
                    476: # ======================================================= Go through the course
1.169     www       477:     my $c=$r->connection;
1.243     albertel  478:     if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.".db",
1.196     matthew   479:             &GDBM_READER(),0640)) {
1.235     albertel  480:         foreach (sort(keys(%hash))) {
1.196     matthew   481:             if ($c->aborted()) { last; }
1.235     albertel  482:             if (($_=~/^src\_(.+)$/)) {
1.243     albertel  483: 		if ($hash{'randomout_'.$1} & !$env{'request.role.adv'}) {
1.235     albertel  484: 		    next; 
                    485: 		}
                    486: 		my $symb=&make_symb($1);
                    487:                 &checkonthis($r,$1,$hash{$_},0,&Apache::lonnet::gettitle($symb),
                    488: 			     $fulltext,$symb,@allwords);
1.196     matthew   489:             }
                    490:         }
                    491:         untie(%hash);
                    492:     }
1.169     www       493:     unless ($totalfound) {
1.231     raeburn   494: 	$r->print('<p>'.&mt('No matches found in resources').'.</p>');
1.169     www       495:     }
1.231     raeburn   496: 
                    497: # Check discussions if requested
                    498:     if ($discuss) {
                    499:         my $totaldiscussions = 0;
                    500:         $r->print('<br /><br /><b>'.&mt('Discussion postings').':</b><br />'); 
                    501:         my $navmap = Apache::lonnavmaps::navmap->new();
                    502:         my @allres=$navmap->retrieveResources();
                    503:         my %discussiontime = &Apache::lonnet::dump('discussiontimes',
1.243     albertel  504:                                $env{'course.'.$env{'request.course.id'}.'.domain'},
                    505:                                $env{'course.'.$env{'request.course.id'}.'.num'});
1.231     raeburn   506:         foreach my $resource (@allres) {
                    507:             my $result = '';
                    508:             my $applies = 0;
                    509:             my $symb = $resource->symb();
                    510:             my $ressymb = $symb;
                    511:             if ($symb =~ m#(___adm/\w+/\w+)/(\d+)/bulletinboard$#) {
                    512:                 $ressymb = 'bulletin___'.$2.$1.'/'.$2.'/bulletinboard';
                    513:                 unless ($ressymb =~ m#bulletin___\d+___adm/wrapper#) {
                    514:                     $ressymb=~s#(bulletin___\d+___)#$1adm/wrapper/#;
                    515:                 }
                    516:             }
                    517:             if (defined($discussiontime{$ressymb})) { 
1.243     albertel  518:                 my %contrib = &Apache::lonnet::restore($ressymb,$env{'request.course.id'},
                    519:                      $env{'course.'.$env{'request.course.id'}.'.domain'},
                    520:                      $env{'course.'.$env{'request.course.id'}.'.num'});
1.231     raeburn   521:                 if ($contrib{'version'}) {
                    522:                     for (my $id=1;$id<=$contrib{'version'};$id++) {
                    523:                         unless (($contrib{'hidden'}=~/\.$id\./) || ($contrib{'deleted'}=~/\.$id\./)) { 
                    524:                             if ($contrib{$id.':subject'}) {
                    525:                                 $result .= $contrib{$id.':subject'};
                    526:                             }
                    527:                             if ($contrib{$id.':message'}) {
                    528:                                 $result .= $contrib{$id.':message'};
                    529:                             }
                    530:                             if ($contrib{$id,':attachmenturl'}) {
                    531:                                 if ($contrib{$id,':attachmenturl'} =~ m-/([^/]+)$-) {
                    532:                                     $result .= $1;
                    533:                                 }
                    534:                             }
                    535:                             $applies = &checkwords($result,$applies,@allwords);
                    536:                         }
                    537:                     }
                    538:                 }
                    539:             }
                    540: # Does this discussion apply?
                    541:             if ($applies) {
                    542:                 my ($map,$ind,$url)=&Apache::lonnet::decode_symb($ressymb);
                    543:                 my $disctype = &mt('resource');
                    544:                 if ($url =~ m#/bulletinboard$#) {
                    545:                     if ($url =~m#^adm/wrapper/adm/.*/bulletinboard$#) {
                    546:                         $url =~s#^adm/wrapper##;
                    547:                     }
                    548:                     $disctype = &mt('bulletin board');
                    549:                 } else {
                    550:                     $url = '/res/'.$url;
                    551:                 }
                    552:                 if ($url =~ /\?/) {
                    553:                     $url .= '&symb=';
                    554:                 } else {
                    555:                     $url .= '?symb=';
                    556:                 }
                    557:                 $url .= &Apache::lonnet::escape($resource->symb());
                    558:                 my $title = $resource->compTitle();
                    559:                 $r->print('<br /><a href="'.$url.'" target="cat">'.
                    560:                      ($title?$title:$url).'</a>&nbsp;&nbsp;-&nbsp;'.$disctype.'<br />');
                    561:                 $totaldiscussions++;
                    562:             } else {
                    563:                 $r->print(' .');
                    564:             }
                    565:         }
                    566:         unless ($totaldiscussions) {
                    567:             $r->print('<p>'.&mt('No matches found in postings').'.</p>');
                    568:         }
                    569:     }
                    570:  
1.167     www       571: # =================================================== Done going through course
1.256   ! albertel  572:     $r->print(&Apache::loncommon::end_page());
1.167     www       573: }
                    574: 
                    575: # =============================== This pulls up a resource and its dependencies
                    576: 
                    577: sub checkonthis {
1.235     albertel  578:     my ($r,$id,$url,$level,$title,$fulltext,$symb,@allwords)=@_;
1.236     albertel  579:     $alreadyseen{$id}=1;
                    580:     if (&Apache::loncommon::connection_aborted($r)) { return; }
1.167     www       581:     $r->rflush();
1.235     albertel  582:     
                    583:     my $result=$title.' ';
1.243     albertel  584:     if ($env{'request.role.adv'} || !$hash{'encrypted_'.$id}) {
1.235     albertel  585: 	$result.=&Apache::lonnet::metadata($url,'title').' '.
                    586: 	    &Apache::lonnet::metadata($url,'subject').' '.
                    587: 	    &Apache::lonnet::metadata($url,'abstract').' '.
                    588: 	    &Apache::lonnet::metadata($url,'keywords');
                    589:     }
                    590:     my ($extension)=($url=~/\.(\w+)$/);
                    591:     if (&Apache::loncommon::fileembstyle($extension) eq 'ssi' &&
                    592: 	($url) && ($fulltext)) {
                    593: 	$result.=&Apache::lonnet::ssi_body($url.'?symb='.&Apache::lonnet::escape($symb));
1.167     www       594:     }
                    595:     $result=~s/\s+/ /gs;
1.231     raeburn   596:     my $applies = 0;
                    597:     $applies = &checkwords($result,$applies,@allwords);
1.167     www       598: # Does this resource apply?
                    599:     if ($applies) {
                    600:        $r->print('<br />');
                    601:        for (my $i=0;$i<=$level*5;$i++) {
                    602:            $r->print('&nbsp;');
                    603:        }
1.235     albertel  604:        my $href=$url;
1.243     albertel  605:        if ($hash{'encrypted_'.$id} && !$env{'request.role.adv'}) {
1.235     albertel  606: 	   $href=&Apache::lonenc::encrypted($href)
                    607: 	       .'?symb='.&Apache::lonenc::encrypted($symb);
                    608:        } else {
                    609: 	   $href.='?symb='.&Apache::lonnet::escape($symb);
                    610:        }
                    611:        $r->print('<a href="'.$href.'" target="cat">'.($title?$title:$url).
                    612: 		 '</a><br />');
1.169     www       613:        $totalfound++;
                    614:     } elsif ($fulltext) {
                    615:        $r->print(' .');
1.167     www       616:     }
1.169     www       617:     $r->rflush();
1.167     www       618: # Check also the dependencies of this one
                    619:     my $dependencies=
                    620:                 &Apache::lonnet::metadata($url,'dependencies');
1.237     albertel  621:     foreach (split(/\,/,$dependencies)) {
                    622:        if (($_=~/^\/res\//) && (!$alreadyseen{$id})) { 
1.235     albertel  623:           &checkonthis($r,$id,$_,$level+1,'',$fulltext,undef,@allwords);
1.167     www       624:        }
                    625:     }
                    626: }
                    627: 
1.231     raeburn   628: sub checkwords {
                    629:     my ($result,$applies,@allwords) = @_;
                    630:     foreach (@allwords) {
                    631:         if ($_=~/\w/) {
                    632:             if ($result=~/$_/si) {
                    633:                 $applies++;
                    634:             }
                    635:         }
                    636:     }
                    637:     return $applies;
                    638: }
                    639: 
1.196     matthew   640: sub untiehash {
                    641:     if (tied(%hash)) {
                    642:         untie(%hash);
                    643:     }
                    644: }
                    645: 
                    646: } # End of course search scoping
                    647: 
1.207     matthew   648: 
1.167     www       649: ######################################################################
                    650: ######################################################################
                    651: 
1.124     matthew   652: =pod 
                    653: 
1.146     matthew   654: =item &print_basic_search_form() 
1.124     matthew   655: 
1.204     matthew   656: Prints the form for the basic search.  Sorry the name is so cryptic.
1.124     matthew   657: 
                    658: =cut
                    659: 
                    660: ######################################################################
                    661: ######################################################################
1.204     matthew   662: sub print_basic_search_form {
1.196     matthew   663:     my ($r,$closebutton,$hidden_fields) = @_;
1.243     albertel  664:     my $result = ($env{'form.catalogmode'} ne 'groupsearch');
1.256   ! albertel  665:     my $bread_crumb =
1.229     matthew   666:         &Apache::lonhtmlcommon::breadcrumbs(undef,'Searching','Search_Basic',
1.227     matthew   667:                                    undef,undef,
1.243     albertel  668:                                    $env{'form.catalogmode'} ne 'groupsearch');
1.256   ! albertel  669:     my $scrout = &Apache::loncommon::start_page('Search').$bread_crumb;
1.243     albertel  670:     if (&Apache::lonnet::allowed('bre',$env{'request.role.domain'})) {
1.213     matthew   671:         # Define interface components
1.233     matthew   672:         my $userelatedwords= '<label>'.
1.213     matthew   673:             &mt('[_1] use related words',
                    674:                 &Apache::lonhtmlcommon::checkbox
1.243     albertel  675:                 ('related',$env{'form.related'},'related')).'</label>';
1.233     matthew   676:         my $onlysearchdomain='<label>'.
1.213     matthew   677:             &mt('[_1] only search domain [_2]',
1.221     matthew   678:                 &Apache::lonhtmlcommon::checkbox('domains',
1.243     albertel  679:                                                  $env{'form.domains'},
1.221     matthew   680:                                                  $r->dir_config('lonDefDomain')
                    681:                                                  ),
                    682:                 $r->dir_config('lonDefDomain')
1.233     matthew   683:                 ).'</label>';
1.248     www       684:         my $inclext= '<label>'.
                    685:             &mt('[_1] include external resources',
                    686:                 &Apache::lonhtmlcommon::checkbox
                    687:                 ('inclext',$env{'form.inclext'})).'</label>';
1.213     matthew   688:         my $adv_search_link = 
                    689:             '<a href="/adm/searchcat?'.
                    690:             'phase=disp_adv&'.
1.243     albertel  691:             'catalogmode='.$env{'form.catalogmode'}.
                    692:             '&launch='.$env{'form.launch'}.
                    693:             '&mode='.$env{'form.mode'}.
1.213     matthew   694:             '">'.&mt('Advanced Search').'</a>';
                    695:         #
                    696:         $scrout.='<form name="loncapa_search" method="post" '.
                    697:             'action="/adm/searchcat">'.
                    698:             '<input type="hidden" name="phase" value="basic_search" />'.
                    699:             $hidden_fields;
                    700:         #
                    701:         $scrout .= '<center>'.$/;
1.243     albertel  702:         if ($env{'request.course.id'}) {
1.213     matthew   703:             $scrout .= '<h1>'.&mt('LON-CAPA Catalog Search').'</h1>';
                    704:         } else {
                    705:             # No need to tell them they are searching
                    706:             $scrout.= ('<br />'x2);
                    707:         }
                    708:         $scrout.='<table>'.
                    709:             '<tr><td align="center" valign="top">'.
1.228     matthew   710:             &Apache::lonhtmlcommon::textbox
                    711:             ('basicexp',
1.243     albertel  712:              &HTML::Entities::encode($env{'form.basicexp'},'<>&"'),50
1.228     matthew   713:              ).
                    714:              '<br />'.
1.213     matthew   715:             '<font size="-1">'.&searchhelp().'</font>'.'</td>'.
                    716:             '<td><font size="-1">'.
                    717:             '<nobr>'.('&nbsp;'x3).$adv_search_link.'</nobr>'.'<br />'.
                    718:             '<nobr>'.('&nbsp;'x1).$userelatedwords.'</nobr>'.'<br />'.
                    719:             '<nobr>'.('&nbsp;'x1).$onlysearchdomain.'</nobr>'.'<br />'.
1.248     www       720:             '<nobr>'.('&nbsp;'x1).$inclext.'</nobr>'.'<br />'.
                    721:              '</font></td>'.
1.213     matthew   722:             '</tr>'.$/;
                    723:         #
                    724:         $scrout .= '<tr><td align="center" colspan="2">'.
                    725:             '<font size="-1">'.
                    726:             '<input type="submit" name="basicsubmit" '.
                    727:             'value="'.&mt('Search').'" />'.
1.223     matthew   728:             ('&nbsp;'x2).$closebutton.('&nbsp;'x2).
                    729:             &viewoptions().
1.213     matthew   730:             '</font>'.
                    731:             '</td></tr>'.$/;
                    732:         $scrout .= '</table>'.$/.'</center>'.'</form>';
1.180     matthew   733:     }
1.243     albertel  734:     if ($env{'request.course.id'}) {
1.213     matthew   735: 	my %lt=&Apache::lonlocal::texthash('srch' => 'Search',
1.187     www       736:                                            'header' => 'Course Search',
                    737: 	 'note' => 'Enter terms or phrases, then press "Search" below',
1.200     www       738: 	 'use' => 'use related words',
1.231     raeburn   739: 	 'full' =>'fulltext search (time consuming)',
                    740:          'disc' => 'search discussion postings (resources and bulletin boards)',
1.187     www       741: 					   );
1.180     matthew   742:         $scrout.=(<<ENDCOURSESEARCH);
1.213     matthew   743: <form name="loncapa_search" method="post" action="/adm/searchcat">
                    744: <center>
1.180     matthew   745: <hr />
1.187     www       746: <h1>$lt{'header'}</h1>    
1.167     www       747: <input type="hidden" name="phase" value="course_search" />
                    748: $hidden_fields
                    749: <p>
1.187     www       750: $lt{'note'}.
1.167     www       751: </p>
                    752: <p>
                    753: <table>
                    754: <tr><td>
                    755: ENDCOURSESEARCH
1.180     matthew   756:         $scrout.='&nbsp;'.
1.200     www       757:             &Apache::lonhtmlcommon::textbox('courseexp',
1.243     albertel  758:                                   $env{'form.courseexp'},40);
1.180     matthew   759:         my $crscheckbox = 
1.200     www       760:             &Apache::lonhtmlcommon::checkbox('crsfulltext',
1.243     albertel  761:                                    $env{'form.crsfulltext'});
1.180     matthew   762:         my $relcheckbox = 
1.200     www       763:             &Apache::lonhtmlcommon::checkbox('crsrelated',
1.243     albertel  764: 				   $env{'form.crsrelated'});
1.231     raeburn   765:         my $discheckbox = 
                    766:             &Apache::lonhtmlcommon::checkbox('crsdiscuss',
1.243     albertel  767:                                    $env{'form.crsrelated'});
1.180     matthew   768:         $scrout.=(<<ENDENDCOURSE);
1.167     www       769: </td></tr>
1.234     matthew   770: <tr><td><label>$relcheckbox $lt{'use'}</label></td><td></td></tr>
                    771: <tr><td><label>$crscheckbox $lt{'full'}</label></td><td></td></tr>
                    772: <tr><td><label>$discheckbox $lt{'disc'}</label></td><td></td></tr>
1.167     www       773: </table><p>
1.187     www       774: &nbsp;<input type="submit" name="coursesubmit" value='$lt{'srch'}' />
1.167     www       775: </p>
1.213     matthew   776: </center>
                    777: </form>
1.167     www       778: ENDENDCOURSE
1.180     matthew   779:     }
1.256   ! albertel  780:     $scrout .= &Apache::loncommon::end_page();
1.146     matthew   781:     $r->print($scrout);
                    782:     return;
1.124     matthew   783: }
                    784: ######################################################################
                    785: ######################################################################
                    786: 
                    787: =pod 
                    788: 
                    789: =item &advanced_search_form() 
                    790: 
1.204     matthew   791: Prints the advanced search form.
1.124     matthew   792: 
                    793: =cut
                    794: 
                    795: ######################################################################
                    796: ######################################################################
1.146     matthew   797: sub print_advanced_search_form{
1.196     matthew   798:     my ($r,$closebutton,$hidden_fields) = @_;
1.256   ! albertel  799:     my $bread_crumb = 
1.229     matthew   800:         &Apache::lonhtmlcommon::breadcrumbs(undef,'Searching',
                    801:                                             'Search_Advanced',
                    802:                                             undef,undef,
1.243     albertel  803:                                   $env{'form.catalogmode'} ne 'groupsearch');
1.200     www       804:     my %lt=&Apache::lonlocal::texthash('srch' => 'Search',
                    805: 				       'reset' => 'Reset',
                    806: 				       'help' => 'Help');
1.217     matthew   807:     my $advanced_buttons=<<"END";
1.200     www       808: <input type="submit" name="advancedsubmit" value='$lt{"srch"}' />
                    809: <input type="reset" name="reset" value='$lt{"reset"}' />
1.129     matthew   810: $closebutton
                    811: END
1.256   ! albertel  812:     my $scrout= &Apache::loncommon::start_page('Advanced Catalog Search');
1.207     matthew   813:     $scrout .= <<"ENDHEADER";
1.256   ! albertel  814: $bread_crumb
1.200     www       815: <form method="post" action="/adm/searchcat" name="advsearch">
1.217     matthew   816: <p>
1.129     matthew   817: $advanced_buttons
1.124     matthew   818: ENDHEADER
1.208     matthew   819:     $scrout.=('&nbsp;'x2).&viewoptions().'</p>'.$hidden_fields. 
                    820:         '<input type="hidden" name="phase" value="adv_search" />';
1.200     www       821:     my %fields=&Apache::lonmeta::fieldnames();
1.208     matthew   822:     #
1.217     matthew   823:     $scrout .= '<h3>'.&mt('Standard Metadata').'</h3>';
                    824:     $scrout .= "<table>\n";
                    825:     $scrout .= '<tr><td>&nbsp;</td><td colspan="2"><font size="-1">'.
                    826:         ('&nbsp;'x2).&searchhelp()."</font></td></tr>\n";
1.208     matthew   827:     my %related_word_search = 
1.217     matthew   828:         ('title'    => 1,
                    829:          'author'   => 0,
                    830:          'owner'    => 0,
                    831:          'authorspace'  => 0,
                    832:          'modifyinguser'=> 0,
                    833:          'keywords' => 1,
                    834:          'notes'    => 1,
                    835:          'abstract' => 1,
                    836:          'standards'=> 1,
                    837:          'mime'     => 1,
1.246     albertel  838: 	 'subject'  => 1,
1.208     matthew   839:          );
1.209     matthew   840:     #
1.246     albertel  841:     foreach my $field ('title','author','subject','owner','authorspace',
                    842: 		       'modifyinguser','keywords','notes','abstract',
                    843: 		       'standards','mime') {
1.208     matthew   844: 	$scrout.='<tr><td align="right">'.&titlefield($fields{$field}).'</td><td>'.
                    845: 	    &Apache::lonmeta::prettyinput($field,
1.243     albertel  846:                                           $env{'form.'.$field},
1.208     matthew   847:                                           $field,
                    848:                                           'advsearch',
                    849: 					  $related_word_search{$field},
                    850:                                           '</td><td align="left">',
1.243     albertel  851:                                           $env{'form.'.$field.'_related'},
1.208     matthew   852:                                           50);
                    853:         if ($related_word_search{$field}) {
                    854:             $scrout .= 'related words';
                    855:         } else {
                    856:             $scrout .= '</td><td>&nbsp;';
                    857:         }
                    858:         $scrout .= '</td></tr>'.$/;
                    859:     }
                    860:     foreach my $field ('lowestgradelevel','highestgradelevel') {
                    861: 	$scrout.='<tr>'.
                    862:             '<td align="right">'.&titlefield($fields{$field}).'</td>'.
                    863:             '<td colspan="2">'.
                    864: 	    &Apache::lonmeta::prettyinput($field,
1.243     albertel  865:                                           $env{'form.'.$field},
1.208     matthew   866:                                           $field,
                    867:                                           'advsearch',
                    868: 					  0).
                    869:                                           '</td></tr>'.$/;
1.200     www       870:     }
1.208     matthew   871:     $scrout.='<tr><td align="right">'.
                    872: 	&titlefield(&mt('MIME Type Category')).'</td><td colspan="2">'. 
1.202     www       873: 	    &Apache::loncommon::filecategoryselect('category',
1.243     albertel  874: 						   $env{'form.category'}).
1.208     matthew   875: 	    '</td></tr>'.$/;
                    876:     $scrout.='<tr><td align="right" valign="top">'.
                    877: 	&titlefield(&mt('Domains')).'</td><td colspan="2">'. 
1.202     www       878: 	    &Apache::loncommon::domain_select('domains',
1.243     albertel  879: 						   $env{'form.domains'},1).
1.248     www       880: 						   '<br /><label>'.
                    881:             &mt('[_1] include external resources',
                    882:                 &Apache::lonhtmlcommon::checkbox
                    883:                 ('inclext',$env{'form.inclext'})).'</label></td></tr>'.$/;
1.217     matthew   884:     #
                    885:     # Misc metadata
                    886:     $scrout.='<tr><td align="right" valign="top">'.
                    887: 	&titlefield(&mt('Copyright/Distribution')).'</td><td colspan="2">'.
                    888:         &Apache::lonmeta::selectbox('copyright',
1.243     albertel  889:                                     $env{'form.copyright'},
1.217     matthew   890:                                     \&Apache::loncommon::copyrightdescription,
                    891:                                     ( undef,
                    892:                                       &Apache::loncommon::copyrightids)
                    893:                                     ).'</td></tr>'.$/;
                    894:     $scrout.='<tr><td align="right" valign="top">'.
                    895: 	&titlefield(&mt('Language')).'</td><td colspan="2">'.
                    896:         &Apache::lonmeta::selectbox('language',
1.243     albertel  897:                                     $env{'form.language'},
1.217     matthew   898:                                     \&Apache::loncommon::languagedescription,
                    899:                                     ('any',&Apache::loncommon::languageids)
                    900:                                     ).'</td></tr>';
                    901:     $scrout .= "</table>\n";    
                    902:     #
                    903:     # Dynamic metadata
                    904:     $scrout .= '<h3>'.&mt('Problem Statistics').'</h3>';
                    905:     $scrout .= "<table>\n";
                    906:     $scrout .= '<tr><td>&nbsp;</td><td align="center">'.&mt('Minimum').'</td>'.
                    907:         '<td align="center">'.&mt('Maximum').'</td></tr>'."\n";
                    908:     foreach my $statistic 
1.222     matthew   909:         ({ name=>'count',
                    910:            description=>'Network-wide number of accesses (hits)',},
                    911:          { name=>'stdno',
                    912:            description=>
                    913:                'Total number of students who have worked on this problem',},
1.217     matthew   914:          { name => 'avetries',
1.222     matthew   915:            description=>'Average number of tries till solved',},
1.217     matthew   916:          { name => 'difficulty',
                    917:            description=>'Degree of difficulty',},
                    918:          { name => 'disc',
                    919:            description=>'Degree of discrimination'}) {
                    920:         $scrout .= '<tr><td align="right">'.
                    921:             &titlefield(&mt($statistic->{'description'})).
                    922:             '</td><td align="center">'.
                    923:             '<input type="text" name="'.$statistic->{'name'}.'_min" '.
                    924:             'value="" size="6" />'.
                    925:             '</td><td align="center">'.
                    926:             '<input type="text" name="'.$statistic->{'name'}.'_max" '.
                    927:             'value="" size="6" />'.
                    928:             '</td></tr>'.$/;
                    929:     }
                    930:     $scrout .= "</table>\n";
                    931:     $scrout .= '<h3>'.&mt('Evaluation Data').'</h3>';
                    932:     $scrout .= "<table>\n";
                    933:     $scrout .= '<tr><td>&nbsp;</td><td align="center">'.&mt('Minimum').'</td>'.
                    934:         '<td align="center">'.&mt('Maximum').'</td></tr>'."\n";
                    935:     foreach my $evaluation
                    936:         ( { name => 'clear',
                    937:             description => 'Material presented in clear way'},
                    938:           { name =>'depth',
                    939:             description => 'Material covered with sufficient depth'},
                    940:           { name => 'helpful',
                    941:             description => 'Material is helpful'},
                    942:           { name => 'correct',
                    943:             description => 'Material appears to be correct'},
                    944:           { name => 'technical',
                    945:             description => 'Resource is technically correct'}){
                    946:         $scrout .= '<tr><td align="right">'.
                    947:             &titlefield(&mt($evaluation->{'description'})).
                    948:             '</td><td align="center">'.
                    949:             '<input type="text" name="'.$evaluation->{'name'}.'_min" '.
                    950:             'value="" size="6" />'.
                    951:             '</td><td align="center">'.
                    952:             '<input type="text" name="'.$evaluation->{'name'}.'_max" '.
                    953:             'value="" size="6" />'.
                    954:             '</td></tr>'.$/;
                    955:     }
                    956:     $scrout .= "</table>\n";
1.216     matthew   957:     #
                    958:     # Creation/Modification date limits
1.217     matthew   959:     $scrout .= '<h3>'.&mt('Creation and Modification dates').'</h3>';
1.216     matthew   960:     $scrout .= "\n<table>\n";
                    961:     my $cafter = 
                    962:         &Apache::lonhtmlcommon::date_setter('advsearch',         # formname
                    963:                                             'creationdate1', # fieldname
                    964:                                             0,           # current value
                    965:                                             '',          # special 
                    966:                                             1,           # includeempty
                    967:                                             '',          # state
                    968:                                             1,           # no_hh_mm_ss
                    969:                                             );
                    970:     my $cbefore = 
                    971:         &Apache::lonhtmlcommon::date_setter('advsearch',         # formname
                    972:                                             'creationdate2', # fieldname
                    973:                                             0,           # current value
                    974:                                             '',          # special 
                    975:                                             1,           # includeempty
                    976:                                             '',          # state
                    977:                                             1,           # no_hh_mm_ss
                    978:                                             );
                    979:     $scrout .= &mt('<tr><td align="right">Created between</td>'.
                    980:                    '<td>[_1]</td></tr>'.
                    981:                    '<tr><td align="right">and </td>'.
                    982:                    '<td>[_2]</td></tr>',$cafter,$cbefore);
                    983:     my $lafter = 
                    984:         &Apache::lonhtmlcommon::date_setter('advsearch',
                    985:                                             'revisiondate1', 
                    986:                                             0,           # current value
                    987:                                             '',          # special 
                    988:                                             1,           # includeempty
                    989:                                             '',          # state
                    990:                                             1,           # no_hh_mm_ss
                    991:                                             );
                    992:     my $lbefore = 
                    993:         &Apache::lonhtmlcommon::date_setter('advsearch',
                    994:                                             'revisiondate2',
                    995:                                             0,           # current value
                    996:                                             '',          # special 
                    997:                                             1,           # includeempty
                    998:                                             '',          # state
                    999:                                             1,           # no_hh_mm_ss
                   1000:                                             );
                   1001:     $scrout .= &mt('<tr><td align="right">Last modified between </td>'.
                   1002:                    '<td>[_1]</td></tr>'.
                   1003:                    '<tr><td align="right">and</td>'.
                   1004:                    '<td>[_2]</td></tr>',$lafter,$lbefore);
1.202     www      1005:     $scrout.="</table>\n";
1.124     matthew  1006:     $scrout.=<<ENDDOCUMENT;
1.129     matthew  1007: $advanced_buttons
1.8       harris41 1008: </form>
                   1009: ENDDOCUMENT
1.256   ! albertel 1010:     $scrout .= &Apache::loncommon::end_page();
1.146     matthew  1011:     $r->print($scrout);
                   1012:     return;
1.124     matthew  1013: }
1.204     matthew  1014: 
1.200     www      1015: ######################################################################
                   1016: ######################################################################
                   1017: 
                   1018: =pod 
                   1019: 
1.204     matthew  1020: =item &titlefield()
1.200     www      1021: 
                   1022: Inputs: title text
                   1023: 
                   1024: Outputs: titletext with font wrapper
                   1025: 
                   1026: =cut
                   1027: 
                   1028: ######################################################################
                   1029: ######################################################################
                   1030: sub titlefield {
                   1031:     my $title=shift;
1.208     matthew  1032:     return $title;
1.200     www      1033: }
1.204     matthew  1034: 
1.200     www      1035: ######################################################################
                   1036: ######################################################################
                   1037: 
                   1038: =pod 
                   1039: 
1.204     matthew  1040: =item viewoptiontext()
1.200     www      1041: 
                   1042: Inputs: codename for view option
                   1043: 
                   1044: Outputs: displayed text
                   1045: 
                   1046: =cut
                   1047: 
                   1048: ######################################################################
                   1049: ######################################################################
                   1050: sub viewoptiontext {
                   1051:     my $code=shift;
1.204     matthew  1052:     my %desc=&Apache::lonlocal::texthash
                   1053:         ('detailed' => "Detailed Citation View",
                   1054:          'xml' => 'XML/SGML',
                   1055:          'compact' => 'Compact View',
                   1056:          'fielded' => 'Fielded Format',
1.255     www      1057:          'summary' => 'Summary View',
                   1058:          'summarypreview' => 'Summary Preview',
                   1059:          'detailedpreview' => 'Detailed Citation Preview');
1.200     www      1060:     return $desc{$code};
                   1061: }
1.204     matthew  1062: 
                   1063: ######################################################################
1.200     www      1064: ######################################################################
                   1065: 
                   1066: =pod 
                   1067: 
1.204     matthew  1068: =item viewoptions()
1.200     www      1069: 
                   1070: Inputs: none
                   1071: 
                   1072: Outputs: text for box with view options
                   1073: 
                   1074: =cut
                   1075: 
                   1076: ######################################################################
                   1077: ######################################################################
                   1078: sub viewoptions {
1.223     matthew  1079:     my $scrout;
1.243     albertel 1080:     if (! defined($env{'form.viewselect'})) { 
                   1081:         $env{'form.viewselect'}='detailed'; 
1.208     matthew  1082:     }
1.200     www      1083:     $scrout.=&Apache::lonmeta::selectbox('viewselect',
1.243     albertel 1084: 			$env{'form.viewselect'},
1.200     www      1085: 			\&viewoptiontext,
                   1086: 			sort(keys(%Views)));
1.208     matthew  1087:     $scrout.= '&nbsp;&nbsp;';
1.214     matthew  1088:     my $countselect = &Apache::lonmeta::selectbox('show',
1.243     albertel 1089:                                                   $env{'form.show'},
1.214     matthew  1090:                                                   undef,
                   1091:                                                   (10,20,50,100,1000,10000));
                   1092:     $scrout .= ('&nbsp;'x2).&mt('[_1] Records per Page',$countselect).
                   1093:         '</nobr>'.$/;
1.200     www      1094:     return $scrout;
1.201     www      1095: }
                   1096: 
                   1097: ######################################################################
1.204     matthew  1098: ######################################################################
1.201     www      1099: 
                   1100: =pod 
                   1101: 
1.204     matthew  1102: =item searchhelp()
1.201     www      1103: 
                   1104: Inputs: none
                   1105: 
                   1106: Outputs: return little blurb on how to enter searches
                   1107: 
                   1108: =cut
                   1109: 
                   1110: ######################################################################
                   1111: ######################################################################
                   1112: sub searchhelp {
1.228     matthew  1113:     return &mt('Enter words and quoted phrases');
1.200     www      1114: }
1.8       harris41 1115: 
1.121     matthew  1116: ######################################################################
                   1117: ######################################################################
                   1118: 
                   1119: =pod 
                   1120: 
1.204     matthew  1121: =item &get_persistent_form_data()
1.145     matthew  1122: 
1.146     matthew  1123: Inputs: filename of database
                   1124: 
                   1125: Outputs: returns undef on database errors.
                   1126: 
                   1127: This function is the reverse of &make_persistent() for form data.
1.145     matthew  1128: Retrieve persistent data from %persistent_db.  Retrieved items will have their
1.243     albertel 1129: values unescaped.  If a form value already exists in $env, it will not be
1.146     matthew  1130: overwritten.  Form values that are array references may have values appended
                   1131: to them.
1.145     matthew  1132: 
                   1133: =cut
                   1134: 
                   1135: ######################################################################
                   1136: ######################################################################
1.146     matthew  1137: sub get_persistent_form_data {
                   1138:     my $filename = shift;
1.147     matthew  1139:     return 0 if (! -e $filename);
1.146     matthew  1140:     return undef if (! tie(%persistent_db,'GDBM_File',$filename,
1.148     matthew  1141:                            &GDBM_READER(),0640));
1.146     matthew  1142:     #
                   1143:     # These make sure we do not get array references printed out as 'values'.
1.161     matthew  1144:     my %arrays_allowed = ('form.domains'=>1);
1.146     matthew  1145:     #
                   1146:     # Loop through the keys, looking for 'form.'
                   1147:     foreach my $name (keys(%persistent_db)) {
                   1148:         next if ($name !~ /^form./);
1.182     matthew  1149:         # Kludgification begins!
                   1150:         if ($name eq 'form.domains' && 
1.243     albertel 1151:             $env{'form.searchmode'} eq 'basic' &&
                   1152:             $env{'form.phase'} ne 'disp_basic') {
1.182     matthew  1153:             next;
                   1154:         }
                   1155:         # End kludge (hopefully)
1.243     albertel 1156:         next if (exists($env{$name}));
1.146     matthew  1157:         my @values = map { 
                   1158:             &Apache::lonnet::unescape($_);
                   1159:         } split(',',$persistent_db{$name});
                   1160:         next if (@values <1);
1.152     matthew  1161:         if ($arrays_allowed{$name}) {
1.243     albertel 1162:             $env{$name} = [@values];
1.146     matthew  1163:         } else {
1.243     albertel 1164:             $env{$name} = $values[0] if ($values[0]);
1.146     matthew  1165:         }
                   1166:     }
                   1167:     untie (%persistent_db);
                   1168:     return 1;
                   1169: }
1.181     matthew  1170: 
1.146     matthew  1171: ######################################################################
                   1172: ######################################################################
                   1173: 
                   1174: =pod 
                   1175: 
1.204     matthew  1176: =item &get_persistent_data()
1.146     matthew  1177: 
                   1178: Inputs: filename of database, ref to array of values to recover.
                   1179: 
                   1180: Outputs: array of values.  Returns undef on error.
                   1181: 
                   1182: This function is the reverse of &make_persistent();
                   1183: Retrieve persistent data from %persistent_db.  Retrieved items will have their
                   1184: values unescaped.  If the item contains commas (before unescaping), the
                   1185: returned value will be an array pointer. 
                   1186: 
                   1187: =cut
                   1188: 
                   1189: ######################################################################
                   1190: ######################################################################
                   1191: sub get_persistent_data {
                   1192:     my $filename = shift;
                   1193:     my @Vars = @{shift()};
                   1194:     my @Values;   # Return array
                   1195:     return undef if (! -e $filename);
                   1196:     return undef if (! tie(%persistent_db,'GDBM_File',$filename,
1.148     matthew  1197:                            &GDBM_READER(),0640));
1.146     matthew  1198:     foreach my $name (@Vars) {
                   1199:         if (! exists($persistent_db{$name})) {
                   1200:             push @Values, undef;
                   1201:             next;
                   1202:         }
                   1203:         my @values = map { 
                   1204:             &Apache::lonnet::unescape($_);
                   1205:         } split(',',$persistent_db{$name});
1.152     matthew  1206:         if (@values <= 1) {
1.146     matthew  1207:             push @Values,$values[0];
1.145     matthew  1208:         } else {
1.146     matthew  1209:             push @Values,\@values;
1.145     matthew  1210:         }
                   1211:     }
1.146     matthew  1212:     untie (%persistent_db);
                   1213:     return @Values;
1.145     matthew  1214: }
                   1215: 
                   1216: ######################################################################
                   1217: ######################################################################
                   1218: 
                   1219: =pod 
                   1220: 
1.121     matthew  1221: =item &make_persistent() 
                   1222: 
1.146     matthew  1223: Inputs: Hash of values to save, filename of persistent database.
                   1224: 
                   1225: Store variables away to the %persistent_db.
1.145     matthew  1226: Values will be escaped.  Values that are array pointers will have their
1.205     www      1227: elements escaped and concatenated in a comma separated string.  
1.122     matthew  1228: 
1.121     matthew  1229: =cut
                   1230: 
                   1231: ######################################################################
                   1232: ######################################################################
1.98      harris41 1233: sub make_persistent {
1.133     matthew  1234:     my %save = %{shift()};
1.146     matthew  1235:     my $filename = shift;
                   1236:     return undef if (! tie(%persistent_db,'GDBM_File',
1.148     matthew  1237:                            $filename,&GDBM_WRCREAT(),0640));
1.146     matthew  1238:     foreach my $name (keys(%save)) {
1.145     matthew  1239:         my @values = (ref($save{$name}) ? @{$save{$name}} : ($save{$name}));
                   1240:         # We handle array references, but not recursively.
                   1241:         my $store = join(',', map { &Apache::lonnet::escape($_); } @values );
                   1242:         $persistent_db{$name} = $store;
1.109     harris41 1243:     }
1.146     matthew  1244:     untie(%persistent_db);
                   1245:     return 1;
                   1246: }
                   1247: 
                   1248: ######################################################################
                   1249: ######################################################################
                   1250: 
                   1251: =pod 
                   1252: 
                   1253: =item &make_form_data_persistent() 
                   1254: 
                   1255: Inputs: filename of persistent database.
                   1256: 
                   1257: Store most form variables away to the %persistent_db.
                   1258: Values will be escaped.  Values that are array pointers will have their
1.205     www      1259: elements escaped and concatenated in a comma separated string.  
1.146     matthew  1260: 
                   1261: =cut
                   1262: 
                   1263: ######################################################################
                   1264: ######################################################################
                   1265: sub make_form_data_persistent {
                   1266:     my $r = shift;
                   1267:     my $filename = shift;
                   1268:     my %save;
1.243     albertel 1269:     foreach (keys(%env)) {
1.150     matthew  1270:         next if (!/^form/ || /submit/);
1.243     albertel 1271:         $save{$_} = $env{$_};
1.146     matthew  1272:     }
1.152     matthew  1273:     return &make_persistent(\%save,$filename);
1.98      harris41 1274: }
                   1275: 
1.122     matthew  1276: ######################################################################
                   1277: ######################################################################
                   1278: 
                   1279: =pod 
                   1280: 
1.134     matthew  1281: =item &parse_advanced_search()
                   1282: 
                   1283: Parse advanced search form and return the following:
                   1284: 
                   1285: =over 4
                   1286: 
                   1287: =item $query Scalar containing an SQL query.
1.126     matthew  1288: 
1.134     matthew  1289: =item $customquery Scalar containing a custom query.
                   1290: 
                   1291: =item $customshow Scalar containing commands to show custom metadata.
                   1292: 
                   1293: =item $libraries_to_query Reference to array of domains to search.
                   1294: 
                   1295: =back
1.122     matthew  1296: 
                   1297: =cut
                   1298: 
                   1299: ######################################################################
                   1300: ######################################################################
1.134     matthew  1301: sub parse_advanced_search {
1.196     matthew  1302:     my ($r,$closebutton,$hidden_fields)=@_;
1.216     matthew  1303:     my @BasicFields = ('title','author','subject','keywords','url','version',
1.227     matthew  1304:                        'notes','abstract','extension','owner','authorspace',
1.216     matthew  1305: #                       'custommetadata','customshow',
                   1306:                        'modifyinguser','standards','mime');
1.222     matthew  1307:     my @StatsFields = &statfields();
                   1308:     my @EvalFields = &evalfields();
1.32      harris41 1309:     my $fillflag=0;
1.230     matthew  1310:     my $pretty_search_string = "";
1.64      harris41 1311:     # Clean up fields for safety
1.216     matthew  1312:     for my $field (@BasicFields,
                   1313:                    'creationdatestart_month','creationdatestart_day',
1.64      harris41 1314: 		   'creationdatestart_year','creationdateend_month',
                   1315: 		   'creationdateend_day','creationdateend_year',
                   1316: 		   'lastrevisiondatestart_month','lastrevisiondatestart_day',
                   1317: 		   'lastrevisiondatestart_year','lastrevisiondateend_month',
1.216     matthew  1318: 		   'lastrevisiondateend_day','lastrevisiondateend_year') {
1.243     albertel 1319: 	$env{'form.'.$field}=~s/[^\w\/\s\(\)\=\-\"\']//g;
1.64      harris41 1320:     }
1.117     matthew  1321:     foreach ('mode','form','element') {
                   1322: 	# is this required?  Hmmm.
1.243     albertel 1323: 	next if (! exists($env{'form.'.$_}));
                   1324: 	$env{'form.'.$_}=&Apache::lonnet::unescape($env{'form.'.$_});
                   1325: 	$env{'form.'.$_}=~s/[^\w\/\s\(\)\=\-\"\']//g;
1.117     matthew  1326:     }
1.131     matthew  1327:     # Preprocess the category form element.
1.243     albertel 1328:     $env{'form.category'} = 'any' if (! defined($env{'form.category'}) ||
                   1329:                                       ref($env{'form.category'}));
1.161     matthew  1330:     #
1.90      harris41 1331:     # Check to see if enough information was filled in
1.222     matthew  1332:     foreach my $field (@BasicFields) {
1.243     albertel 1333: 	if (&filled($env{'form.'.$field})) {
1.32      harris41 1334: 	    $fillflag++;
                   1335: 	}
                   1336:     }
1.222     matthew  1337:     foreach my $field (@StatsFields,@EvalFields) {
1.243     albertel 1338:         if (&filled($env{'form.'.$field.'_max'})) {
1.222     matthew  1339:             $fillflag++;
                   1340:         }
1.243     albertel 1341:         if (&filled($env{'form.'.$field.'_min'})) {
1.222     matthew  1342:             $fillflag++;
                   1343:         }
                   1344:     }
                   1345: 
1.216     matthew  1346:     for my $field ('lowestgradelevel','highestgradelevel') {
1.243     albertel 1347:         if ( $env{'form.'.$field} =~ /^\d+$/ &&
                   1348:              $env{'form.'.$field} > 0) {
1.216     matthew  1349:             $fillflag++;
                   1350:         }
                   1351:     }
1.212     matthew  1352:     if (! $fillflag) {
1.204     matthew  1353: 	&output_blank_field_error($r,$closebutton,
                   1354:                                   'phase=disp_adv',$hidden_fields);
1.134     matthew  1355: 	return ;
1.32      harris41 1356:     }
1.90      harris41 1357:     # Turn the form input into a SQL-based query
1.39      harris41 1358:     my $query='';
1.45      harris41 1359:     my @queries;
1.143     matthew  1360:     my $font = '<font color="#800000" face="helvetica">';
1.90      harris41 1361:     # Evaluate logical expression AND/OR/NOT phrase fields.
1.216     matthew  1362:     foreach my $field (@BasicFields) {
1.243     albertel 1363: 	next if (!defined($env{'form.'.$field}) || $env{'form.'.$field} eq '');
1.228     matthew  1364:         my ($error,$SQLQuery) = 
1.243     albertel 1365:             &process_phrase_input($env{'form.'.$field},
                   1366:                                   $env{'form.'.$field.'_related'},$field);
1.228     matthew  1367:         if (defined($error)) {
                   1368:             &output_unparsed_phrase_error($r,$closebutton,'phase=disp_adv',
                   1369:                                          $hidden_fields,$field);
                   1370:             return;
                   1371:         } else {
                   1372:             $pretty_search_string .= 
1.243     albertel 1373:                 $font.$field.'</font>: '.$env{'form.'.$field};
                   1374:             if ($env{'form.'.$field.'_related'}) {
1.228     matthew  1375:                 my @Words = 
                   1376:                     &Apache::loncommon::get_related_words
1.243     albertel 1377:                     ($env{'form.'.$field});
1.228     matthew  1378:                 if (@Words) {
                   1379:                     $pretty_search_string.= ' with related words: '.
                   1380:                         join(', ',@Words[0..4]);
1.143     matthew  1381:                 } else {
1.228     matthew  1382:                     $pretty_search_string.= ' with related words.';
1.143     matthew  1383:                 }
1.142     matthew  1384:             }
1.228     matthew  1385:             $pretty_search_string .= '<br />';
                   1386:             push (@queries,$SQLQuery);
1.131     matthew  1387:         }
1.44      harris41 1388:     }
1.161     matthew  1389:     #
                   1390:     # Make the 'mime' from 'form.category' and 'form.extension'
                   1391:     #
                   1392:     my $searchphrase;
1.243     albertel 1393:     if (exists($env{'form.category'})    && 
                   1394:         $env{'form.category'} !~ /^\s*$/ &&
                   1395:         $env{'form.category'} ne 'any')     {
1.161     matthew  1396:         my @extensions = &Apache::loncommon::filecategorytypes
1.243     albertel 1397:                                                    ($env{'form.category'});
1.161     matthew  1398:         if (scalar(@extensions) > 0) {
                   1399:             $searchphrase = join(' OR ',@extensions);
                   1400:         }
                   1401:     }
                   1402:     if (defined($searchphrase)) {
1.228     matthew  1403:         my ($error,$SQLsearch) = &process_phrase_input($searchphrase,0,'mime');
                   1404:         push @queries,$SQLsearch;
1.161     matthew  1405:         $pretty_search_string .=$font.'mime</font> contains <b>'.
                   1406:             $searchphrase.'</b><br />';
1.135     matthew  1407:     }
1.204     matthew  1408:     #
1.90      harris41 1409:     # Evaluate option lists
1.243     albertel 1410:     if ($env{'form.lowestgradelevel'}        &&
                   1411:         $env{'form.lowestgradelevel'} ne '0' &&
                   1412:         $env{'form.lowestgradelevel'} =~ /^\d+$/) {
1.216     matthew  1413: 	push(@queries,
1.243     albertel 1414:              '(lowestgradelevel>='.$env{'form.lowestgradelevel'}.')');
1.216     matthew  1415:         $pretty_search_string.="lowestgradelevel>=".
1.243     albertel 1416:             $env{'form.lowestgradelevel'}."<br />\n";
1.216     matthew  1417:     }
1.243     albertel 1418:     if ($env{'form.highestgradelevel'}        &&
                   1419:         $env{'form.highestgradelevel'} ne '0' &&
                   1420:         $env{'form.highestgradelevel'} =~ /^\d+$/) {
1.216     matthew  1421: 	push(@queries,
1.243     albertel 1422:              '(highestgradelevel<='.$env{'form.highestgradelevel'}.')');
1.216     matthew  1423:         $pretty_search_string.="highestgradelevel<=".
1.243     albertel 1424:             $env{'form.highestgradelevel'}."<br />\n";
1.216     matthew  1425:     }
1.243     albertel 1426:     if ($env{'form.language'} and $env{'form.language'} ne 'any') {
                   1427: 	push @queries,"(language like \"$env{'form.language'}\")";
1.143     matthew  1428:         $pretty_search_string.=$font."language</font>= ".
1.243     albertel 1429:             &Apache::loncommon::languagedescription($env{'form.language'}).
1.143     matthew  1430:                 "<br />\n";
1.58      harris41 1431:     }
1.243     albertel 1432:     if ($env{'form.copyright'} and $env{'form.copyright'} ne 'any') {
                   1433: 	push @queries,"(copyright like \"$env{'form.copyright'}\")";
1.143     matthew  1434:         $pretty_search_string.=$font."copyright</font> = ".
1.243     albertel 1435:             &Apache::loncommon::copyrightdescription($env{'form.copyright'}).
1.230     matthew  1436:                 "<br />\n";
1.58      harris41 1437:     }
1.143     matthew  1438:     #
1.217     matthew  1439:     # Statistics
                   1440:     foreach my $field (@StatsFields,@EvalFields) {
                   1441:         my ($min,$max);
1.243     albertel 1442:         if (exists($env{'form.'.$field.'_min'}) && 
                   1443:             $env{'form.'.$field.'_min'} ne '') {
                   1444:             $min = $env{'form.'.$field.'_min'};
                   1445:         }
                   1446:         if (exists($env{'form.'.$field.'_max'}) &&
                   1447:             $env{'form.'.$field.'_max'} ne '') {
                   1448:             $max = $env{'form.'.$field.'_max'};
1.217     matthew  1449:         }
                   1450:         next if (! defined($max) && ! defined($min));
                   1451:         if (defined($min) && defined($max)) {
                   1452:             ($min,$max) = sort {$a <=>$b} ($min,$max);
                   1453:         }
                   1454:         if (defined($min) && $min =~ /^(\d+\.\d+|\d+|\.\d+)$/) {
                   1455:             push(@queries,'('.$field.'>'.$min.')');
                   1456:             $pretty_search_string.=$font.$field.'</font>&gt;'.$min.'<br />';
                   1457:         }
                   1458:         if (defined($max) && $max =~ /^(\d+\.\d+|\d+|\.\d+)$/) {
                   1459:             push(@queries,'('.$field.'<'.$max.')');
                   1460:             $pretty_search_string.=$font.$field.'</font>&lt;'.$max.'<br />';
                   1461:         }
                   1462:     }
                   1463:     #
1.90      harris41 1464:     # Evaluate date windows
1.216     matthew  1465:     my $cafter =
                   1466:         &Apache::lonhtmlcommon::get_date_from_form('creationdate1');
                   1467:     my $cbefore = 
                   1468:         &Apache::lonhtmlcommon::get_date_from_form('creationdate2');
                   1469:     if ($cafter > $cbefore) {
                   1470:         my $tmp = $cafter;
                   1471:         $cafter = $cbefore;
                   1472:         $cbefore = $tmp;
                   1473:     }
                   1474:     my $mafter = 
                   1475:         &Apache::lonhtmlcommon::get_date_from_form('revisiondate1');
                   1476:     my $mbefore =
                   1477:         &Apache::lonhtmlcommon::get_date_from_form('revisiondate2');
                   1478:     if ($mafter > $mbefore) {
                   1479:         my $tmp = $mafter;
                   1480:         $mafter = $mbefore;
                   1481:         $mbefore = $tmp;
                   1482:     }
                   1483:     my ($datequery,$error,$prettydate)=&build_date_queries($cafter,$cbefore,
                   1484:                                                            $mafter,$mbefore);
                   1485:     if (defined($error)) {
                   1486:         &output_date_error($r,$error,$closebutton,$hidden_fields);
                   1487:     } elsif (defined($datequery)) {
1.143     matthew  1488:         # Here is where you would set up pretty_search_string to output
                   1489:         # date query information.
1.216     matthew  1490:         $pretty_search_string .= '<br />'.$prettydate.'<br />';
1.60      harris41 1491: 	push @queries,$datequery;
                   1492:     }
1.204     matthew  1493:     #
1.90      harris41 1494:     # Process form information for custom metadata querying
1.134     matthew  1495:     my $customquery=undef;
1.204     matthew  1496:     ##
                   1497:     ## The custom metadata search was removed q long time ago mostly 
                   1498:     ## because I was unable to figureout exactly how it worked and could
                   1499:     ## not imagine people actually using it.  MH
                   1500:     ##
1.243     albertel 1501:     # if ($env{'form.custommetadata'}) {
1.204     matthew  1502:     #    $pretty_search_string .=$font."Custom Metadata Search</font>: <b>".
1.243     albertel 1503:     #    $env{'form.custommetadata'}."</b><br />\n";
1.204     matthew  1504:     #    $customquery=&build_custommetadata_query('custommetadata',
1.243     albertel 1505:     #                                             $env{'form.custommetadata'});
1.204     matthew  1506:     # }
1.134     matthew  1507:     my $customshow=undef;
1.243     albertel 1508:     # if ($env{'form.customshow'}) {
1.204     matthew  1509:     # $pretty_search_string .=$font."Custom Metadata Display</font>: <b>".
1.243     albertel 1510:     #                         $env{'form.customshow'}."</b><br />\n";
                   1511:     #    $customshow=$env{'form.customshow'};
1.204     matthew  1512:     #    $customshow=~s/[^\w\s]//g;
                   1513:     #    my @fields=split(/\s+/,$customshow);
                   1514:     #    $customshow=join(" ",@fields);
                   1515:     # }
                   1516:     ##
1.132     matthew  1517:     ## Deal with restrictions to given domains
                   1518:     ## 
1.254     www      1519:     my ($libraries_to_query,$pretty_domains_string) = &parse_domain_restrictions();
                   1520:     if ($pretty_domains_string) {
1.251     www      1521:        $pretty_search_string .= $pretty_domains_string."<br />\n";
                   1522:     }
1.180     matthew  1523:     #
                   1524:     if (@queries) {
1.228     matthew  1525: 	$query="SELECT * FROM metadata WHERE (".join(") AND (",@queries).')';
1.180     matthew  1526:     } elsif ($customquery) {
                   1527:         $query = '';
                   1528:     }
1.241     matthew  1529:     #&Apache::lonnet::logthis('advanced query = '.$/.$query);
1.180     matthew  1530:     return ($query,$customquery,$customshow,$libraries_to_query,
                   1531:             $pretty_search_string);
                   1532: }
                   1533: 
                   1534: sub parse_domain_restrictions {
1.132     matthew  1535:     my $libraries_to_query = undef;
1.243     albertel 1536:     # $env{'form.domains'} can be either a scalar or an array reference.
1.132     matthew  1537:     # We need an array.
1.243     albertel 1538:     if (! exists($env{'form.domains'}) || $env{'form.domains'} eq '') {
1.240     matthew  1539:         return (undef,'',undef);
1.180     matthew  1540:     }
1.245     albertel 1541:     my @allowed_domains = &Apache::loncommon::get_env_multiple('form.domains');
1.204     matthew  1542:     #
1.132     matthew  1543:     my %domain_hash = ();
1.143     matthew  1544:     my $pretty_domains_string;
1.132     matthew  1545:     foreach (@allowed_domains) {
                   1546:         $domain_hash{$_}++;
                   1547:     }
1.143     matthew  1548:     if ($domain_hash{'any'}) {
1.152     matthew  1549:         $pretty_domains_string = "In all LON-CAPA domains.";
1.143     matthew  1550:     } else {
                   1551:         if (@allowed_domains > 1) {
1.152     matthew  1552:             $pretty_domains_string = "In LON-CAPA domains:";
1.143     matthew  1553:         } else {
1.152     matthew  1554:             $pretty_domains_string = "In LON-CAPA domain ";
1.143     matthew  1555:         }
                   1556:         foreach (sort @allowed_domains) {
1.152     matthew  1557:             $pretty_domains_string .= "<b>".$_."</b> ";
1.132     matthew  1558:         }
1.143     matthew  1559:         foreach (keys(%Apache::lonnet::libserv)) {
                   1560:             if (exists($domain_hash{$Apache::lonnet::hostdom{$_}})) {
                   1561:                 push @$libraries_to_query,$_;
                   1562:             }
1.132     matthew  1563:         }
                   1564:     }
1.239     matthew  1565:     return ($libraries_to_query,
1.254     www      1566:             $pretty_domains_string);
1.18      harris41 1567: }
                   1568: 
1.122     matthew  1569: ######################################################################
                   1570: ######################################################################
                   1571: 
                   1572: =pod 
                   1573: 
1.134     matthew  1574: =item &parse_basic_search() 
1.122     matthew  1575: 
1.134     matthew  1576: Parse the basic search form and return a scalar containing an sql query.
1.126     matthew  1577: 
1.122     matthew  1578: =cut
                   1579: 
                   1580: ######################################################################
                   1581: ######################################################################
1.134     matthew  1582: sub parse_basic_search {
1.145     matthew  1583:     my ($r,$closebutton)=@_;
1.204     matthew  1584:     #
1.64      harris41 1585:     # Clean up fields for safety
                   1586:     for my $field ('basicexp') {
1.243     albertel 1587: 	$env{"form.$field"}=~s/[^\w\s\'\"\!\(\)\-]//g;
1.64      harris41 1588:     }
1.117     matthew  1589:     foreach ('mode','form','element') {
                   1590: 	# is this required?  Hmmm.
1.243     albertel 1591: 	next unless (exists($env{"form.$_"}));
                   1592: 	$env{"form.$_"}=&Apache::lonnet::unescape($env{"form.$_"});
                   1593: 	$env{"form.$_"}=~s/[^\w\/\s\(\)\=\-\"\']//g;
1.117     matthew  1594:     }
1.254     www      1595:     my ($libraries_to_query,$pretty_domains_string) = &parse_domain_restrictions();
1.204     matthew  1596:     #
                   1597:     # Check to see if enough of a query is filled in
1.243     albertel 1598:     my $search_string = $env{'form.basicexp'};
1.220     matthew  1599:     if (! &filled($search_string)) {
1.151     matthew  1600: 	&output_blank_field_error($r,$closebutton,'phase=disp_basic');
1.24      harris41 1601: 	return OK;
                   1602:     }
1.228     matthew  1603:     my $pretty_search_string=$search_string;
1.224     matthew  1604:     my @Queries;
1.228     matthew  1605:     my $searchfield = 'concat_ws(" ",'.join(',',
                   1606:                                             ('title','author','subject',
                   1607:                                              'notes','abstract','keywords')
                   1608:                                             ).')';
                   1609:     my ($error,$SQLQuery) = &process_phrase_input($search_string,
1.243     albertel 1610:                                                     $env{'form.related'},
1.228     matthew  1611:                                                     $searchfield);
                   1612:     if ($error) {
                   1613:         &output_unparsed_phrase_error($r,$closebutton,'phase=disp_basic',
                   1614:                                       '','basicexp');
                   1615:         return;
1.141     matthew  1616:     }
1.228     matthew  1617:     push(@Queries,$SQLQuery);
                   1618:     #foreach my $q (@Queries) {
                   1619:     #    &Apache::lonnet::logthis('    '.$q);
                   1620:     #}
1.224     matthew  1621:     my $final_query = 'SELECT * FROM metadata WHERE '.join(" AND ",@Queries);
1.204     matthew  1622:     #
1.180     matthew  1623:     if (defined($pretty_domains_string) && $pretty_domains_string ne '') {
                   1624:         $pretty_search_string .= ' '.$pretty_domains_string;
                   1625:     }
1.143     matthew  1626:     $pretty_search_string .= "<br />\n";
1.225     matthew  1627:     $pretty_search_string =~ s:^<br /> and ::;
1.241     matthew  1628:     #&Apache::lonnet::logthis('simple search final query = '.$/.$final_query);
1.183     matthew  1629:     return ($final_query,$pretty_search_string,
1.180     matthew  1630:             $libraries_to_query);
1.22      harris41 1631: }
                   1632: 
1.228     matthew  1633: 
                   1634: ###############################################################
                   1635: ###############################################################
                   1636: 
                   1637: my @Phrases;
                   1638: 
                   1639: sub concat {
                   1640:     my ($item) = @_;
                   1641:     my $results = '';
                   1642:     foreach (@$item) {
                   1643:         if (ref($_) eq 'ARRAY') {
                   1644:             $results .= join(' ',@$_);
                   1645:         }
                   1646:     }
                   1647:     return $results;
                   1648: }
                   1649: 
1.224     matthew  1650: sub process_phrase_input {
1.228     matthew  1651:     my ($phrase,$related,$field)=@_;
                   1652:     #&Apache::lonnet::logthis('phrase = :'.$phrase.':');
                   1653:     my $grammar = <<'ENDGRAMMAR';
                   1654:     searchphrase:
                   1655:         expression /^\Z/ {
                   1656:             # &Apache::lonsearchcat::print_item(\@item,0);
                   1657:             [@item];
                   1658:         }
                   1659:     expression:
                   1660:         phrase(s)   {
                   1661:             [@item];
                   1662:         }
                   1663:     phrase:
                   1664:         orword {
                   1665:             [@item];
                   1666:         }
                   1667:       | andword {
                   1668:             [@item];
                   1669:         }
                   1670:       | minusword {
                   1671:             unshift(@::Phrases,$item[1]->[0]);
                   1672:             unshift(@::Phrases,$item[1]->[1]);
                   1673:             [@item];
                   1674:         }
                   1675:       | word {
                   1676:             unshift(@::Phrases,$item[1]);
                   1677:             [@item];
                   1678:         } 
                   1679:     #
                   1680:     orword:
                   1681:         word 'OR' phrase {
                   1682:             unshift(@::Phrases,'OR');
                   1683:             unshift(@::Phrases,$item[1]);
                   1684:             [@item];
                   1685:         }
                   1686:         | word 'or' phrase {
                   1687:             unshift(@::Phrases,'OR');
                   1688:             unshift(@::Phrases,$item[1]);
                   1689:             [@item];
                   1690:         }    
                   1691:         | minusword 'OR' phrase {
                   1692:             unshift(@::Phrases,'OR');
                   1693:             unshift(@::Phrases,$item[1]->[0]);
                   1694:             unshift(@::Phrases,$item[1]->[1]);
                   1695:             [@item];
                   1696:         }
                   1697:         | minusword 'or' phrase {
                   1698:             unshift(@::Phrases,'OR');
                   1699:             unshift(@::Phrases,$item[1]->[0]);
                   1700:             unshift(@::Phrases,$item[1]->[1]);
                   1701:             [@item];
                   1702:         }    
                   1703:     andword:
                   1704:         word phrase {
                   1705:             unshift(@::Phrases,'AND');
                   1706:             unshift(@::Phrases,$item[1]);
                   1707:             [@item];
                   1708:         }
                   1709:         | minusword phrase {
                   1710:             unshift(@::Phrases,'AND');
                   1711:             unshift(@::Phrases,$item[1]->[0]);
                   1712:             unshift(@::Phrases,$item[1]->[1]);
                   1713:             [@item];
                   1714:         }
                   1715:     #
                   1716:     minusword:
                   1717:         '-' word {
                   1718:             [$item[2],'NOT'];
                   1719:         }
                   1720:     word:
                   1721:         "'" term(s) "'" {
                   1722:           &Apache::lonsearchcat::concat(\@item);
                   1723:         }
                   1724:       | '"' term(s) '"' {
                   1725:           &Apache::lonsearchcat::concat(\@item);
                   1726:         }
                   1727:       | term {
                   1728:             $item[1];
                   1729:         }
                   1730:     term:
                   1731:         /[\w\Q:!@#$%^&*()+_=|{}<>,.;\\\/?\E]+/ {
                   1732:             $item[1];
                   1733:         }
                   1734: ENDGRAMMAR
                   1735:     #
                   1736:     # The end result of parsing the phrase with the grammar is an array
                   1737:     # @::Phrases.
                   1738:     # $phrase = "gene splicing" or cat -> "gene splicing","OR","cat"
                   1739:     # $phrase = "genetic engineering" -dna ->
                   1740:     #                      "genetic engineering","AND","NOT","dna"
                   1741:     # $phrase = cat or dog -poodle -> "cat","OR","dog","AND","NOT","poodle"
                   1742:     undef(@::Phrases);
                   1743:     my $p = new Parse::RecDescent($grammar);
                   1744:     if (! defined($p->searchphrase($phrase))) {
                   1745:         &Apache::lonnet::logthis('lonsearchcat:unable to process:'.$phrase);
                   1746:         return 'Unable to process phrase '.$phrase;
                   1747:     }
                   1748:     #
                   1749:     # Go through the phrases and make sense of them.  
                   1750:     # Apply modifiers NOT OR and AND to the phrases.
                   1751:     my @NewPhrases;
                   1752:     while(@::Phrases) {
                   1753:         my $phrase = shift(@::Phrases);
                   1754:         # &Apache::lonnet::logthis('phrase = '.$phrase);
                   1755:         my $phrasedata;
                   1756:         if ($phrase =~ /^(NOT|OR|AND)$/) {
                   1757:             if ($phrase eq 'OR') {
                   1758:                 $phrasedata->{'or'}++;
                   1759:                 if (! @::Phrases) { $phrasedata = undef; last; }
                   1760:                 $phrase = shift(@::Phrases);
                   1761:             } elsif ($phrase eq 'AND') {
                   1762:                 $phrasedata->{'and'}++;
                   1763:                 if (! @::Phrases) { $phrasedata = undef; last; }
                   1764:                 $phrase = shift(@::Phrases);
1.224     matthew  1765:             }
1.228     matthew  1766:             if ($phrase eq 'NOT') {
                   1767:                 $phrasedata->{'negate'}++;
                   1768:                 if (! @::Phrases) { $phrasedata = undef; last; }
                   1769:                 $phrase = shift(@::Phrases);
1.224     matthew  1770:             }
1.228     matthew  1771:         }
                   1772:         $phrasedata->{'phrase'} = $phrase;
                   1773:         if ($related) {
                   1774:             my @NewWords;
                   1775:             (undef,@NewWords) = &related_version($phrasedata->{'phrase'});
                   1776:             $phrasedata->{'related_words'} = \@NewWords;
                   1777:         }
                   1778:         push(@NewPhrases,$phrasedata);
                   1779:     }
                   1780:     #
                   1781:     # Actually build the sql query from the phrases
                   1782:     my $SQLQuery;
                   1783:     foreach my $phrase (@NewPhrases) {
                   1784:         my $query;
                   1785:         if ($phrase->{'negate'}) {
                   1786:             $query .= $field.' NOT LIKE "%'.$phrase->{'phrase'}.'%"';
1.224     matthew  1787:         } else {
1.228     matthew  1788:             $query .= $field.' LIKE "%'.$phrase->{'phrase'}.'%"';
                   1789:         }
                   1790:         foreach my $related (@{$phrase->{'related_words'}}) {
                   1791:             if ($phrase->{'negate'}) {
                   1792:                 $query .= ' AND '.$field.' NOT LIKE "%'.$related.'%"';
                   1793:             } else {
                   1794:                 $query .= ' OR '.$field.' LIKE "%'.$related.'%"';
                   1795:             }
                   1796:         }
                   1797:         if ($SQLQuery) {
                   1798:             if ($phrase->{'or'}) {
                   1799:                 $SQLQuery .= ' OR ('.$query.')';
                   1800:             } else {
                   1801:                 $SQLQuery .= ' AND ('.$query.')';
1.224     matthew  1802:             }
1.228     matthew  1803:         } else {
                   1804:             $SQLQuery = '('.$query.')';
1.224     matthew  1805:         }
                   1806:     }
                   1807:     #
1.228     matthew  1808:     # &Apache::lonnet::logthis("SQLQuery = $SQLQuery");
1.224     matthew  1809:     #
1.228     matthew  1810:     return undef,$SQLQuery;
1.224     matthew  1811: }
                   1812: 
1.122     matthew  1813: ######################################################################
                   1814: ######################################################################
                   1815: 
                   1816: =pod 
                   1817: 
1.204     matthew  1818: =item &related_version()
1.142     matthew  1819: 
                   1820: Modifies an input string to include related words.  Words in the string
                   1821: are replaced with parenthesized lists of 'OR'd words.  For example
                   1822: "torque" is replaced with "(torque OR word1 OR word2 OR ...)".  
                   1823: 
                   1824: Note: Using this twice on a string is probably silly.
                   1825: 
                   1826: =cut
                   1827: 
                   1828: ######################################################################
                   1829: ######################################################################
                   1830: sub related_version {
1.224     matthew  1831:     my ($word) = @_;
                   1832:     return (undef) if (lc($word) =~ /\b(or|and|not)\b/);
                   1833:     my @Words = &Apache::loncommon::get_related_words($word);
                   1834:     # Only use 4 related words
                   1835:     @Words = ($#Words>4? @Words[0..4] : @Words);
                   1836:     my $result = join " OR ", ($word,@Words);
                   1837:     return $result,sort(@Words);
1.142     matthew  1838: }
                   1839: 
1.98      harris41 1840: 
1.122     matthew  1841: ######################################################################
                   1842: ######################################################################
                   1843: 
                   1844: =pod 
                   1845: 
                   1846: =item &build_custommetadata_query() 
                   1847: 
1.126     matthew  1848: Constructs a custom metadata query using a rather heinous regular
                   1849: expression.
                   1850: 
1.122     matthew  1851: =cut
                   1852: 
                   1853: ######################################################################
                   1854: ######################################################################
1.98      harris41 1855: sub build_custommetadata_query {
                   1856:     my ($field_name,$logic_statement)=@_;
                   1857:     my $q=new Text::Query('abc',
                   1858: 			  -parse => 'Text::Query::ParseAdvanced',
                   1859: 			  -build => 'Text::Query::BuildAdvancedString');
                   1860:     $q->prepare($logic_statement);
                   1861:     my $matchexp=${$q}{'-parse'}{'-build'}{'matchstring'};
                   1862:     # quick fix to change literal into xml tag-matching
                   1863:     # will eventually have to write a separate builder module
1.122     matthew  1864:     # wordone=wordtwo becomes\<wordone\>[^\<] *wordtwo[^\<]*\<\/wordone\>
                   1865:     $matchexp =~ s/(\w+)\\=([\w\\\+]+)?# wordone=wordtwo is changed to 
                   1866:                  /\\<$1\\>?#           \<wordone\>
                   1867:                    \[\^\\<\]?#        [^\<]         
                   1868:                    \*$2\[\^\\<\]?#           *wordtwo[^\<]
                   1869:                    \*\\<\\\/$1\\>?#                        *\<\/wordone\>
                   1870:                    /g;
1.98      harris41 1871:     return $matchexp;
                   1872: }
                   1873: 
1.22      harris41 1874: 
1.122     matthew  1875: ######################################################################
                   1876: ######################################################################
                   1877: 
                   1878: =pod 
                   1879: 
                   1880: =item &build_date_queries() 
                   1881: 
1.126     matthew  1882: Builds a SQL logic query to check time/date entries.
                   1883: Also reports errors (check for /^Incorrect/).
                   1884: 
1.122     matthew  1885: =cut
                   1886: 
                   1887: ######################################################################
                   1888: ######################################################################
1.98      harris41 1889: sub build_date_queries {
1.216     matthew  1890:     my ($cafter,$cbefore,$mafter,$mbefore) = @_;
                   1891:     my ($result,$error,$pretty_string);
                   1892:     #
                   1893:     # Verify the input
                   1894:     if (! defined($cafter) && ! defined($cbefore) &&
                   1895:         ! defined($mafter) && ! defined($mbefore)) {
                   1896:         # This is an okay situation, so return undef for the error
                   1897:         return (undef,undef,undef);
                   1898:     }
                   1899:     if ((defined($cafter)  && ! defined($cbefore)) ||
                   1900:         (defined($cbefore) && ! defined($cafter))) {
                   1901:         # This is bad, so let them know
                   1902:         $error = &mt('Incorrect entry for the creation date.  '.
                   1903:                     'You must specify both the beginning and ending dates.');
                   1904:     }
                   1905:     if (! defined($error) && 
                   1906:         ((defined($mafter)  && ! defined($mbefore)) ||
                   1907:         (defined($mbefore) && ! defined($mafter)))) {
                   1908:         # This is also bad, so let them know
                   1909:         $error = &mt('Incorrect entry for the last revision date.  '.
                   1910:                      'You must specify both the beginning and ending dates.');
1.98      harris41 1911:     }
1.216     matthew  1912:     if (! defined($error)) {
                   1913:         #
                   1914:         # Build the queries
                   1915:         my @queries;
                   1916:         if (defined($cbefore) && defined($cafter)) {
                   1917:             my (undef,undef,undef,$caday,$camon,$cayear) = localtime($cafter);
                   1918:             my (undef,undef,undef,$cbday,$cbmon,$cbyear) = localtime($cbefore);
                   1919:             # Correct for year being relative to 1900
                   1920:             $cayear+=1900; $cbyear+=1900;
                   1921:             my $cquery=
                   1922:                 '(creationdate BETWEEN '.
                   1923:                 "'".$cayear.'-'.$camon.'-'.$caday."'".
                   1924:                 ' AND '.
                   1925:                 "'".$cbyear.'-'.$cbmon.'-'.$cbday." 23:59:59')";
                   1926:             $pretty_string .= '<br />' if (defined($pretty_string));
                   1927:             $pretty_string .= 
                   1928:                 &mt('created between [_1] and [_2]',
                   1929:                     &Apache::lonlocal::locallocaltime($cafter),
                   1930:                     &Apache::lonlocal::locallocaltime($cbefore+24*60*60-1));
                   1931:             push(@queries,$cquery);
                   1932:             $pretty_string =~ s/ 00:00:00//g;
                   1933:         }
                   1934:         if (defined($mbefore) && defined($mafter)) {
                   1935:             my (undef,undef,undef,$maday,$mamon,$mayear) = localtime($mafter);
                   1936:             my (undef,undef,undef,$mbday,$mbmon,$mbyear) = localtime($mbefore);
                   1937:             # Correct for year being relative to 1900
                   1938:             $mayear+=1900; $mbyear+=1900;
                   1939:             my $mquery=
                   1940:                 '(lastrevisiondate BETWEEN '.
                   1941:                 "'".$mayear.'-'.$mamon.'-'.$maday."'".
                   1942:                 ' AND '.
                   1943:                 "'".$mbyear.'-'.$mbmon.'-'.$mbday." 23:59:59')";
                   1944:             push(@queries,$mquery);
                   1945:             $pretty_string .= '<br />' if (defined($pretty_string));
                   1946:             $pretty_string .= 
                   1947:                 &mt('last revised between [_1] and [_2]',
                   1948:                     &Apache::lonlocal::locallocaltime($mafter),
                   1949:                     &Apache::lonlocal::locallocaltime($mbefore+24*60*60-1));
                   1950:             $pretty_string =~ s/ 00:00:00//g;
                   1951:         }
                   1952:         if (@queries) {
                   1953:             $result .= join(" AND ",@queries);
                   1954:         }
1.98      harris41 1955:     }
1.216     matthew  1956:     return ($result,$error,$pretty_string);
1.18      harris41 1957: }
1.6       harris41 1958: 
1.122     matthew  1959: ######################################################################
                   1960: ######################################################################
                   1961: 
1.144     matthew  1962: =pod
                   1963: 
                   1964: =item &copyright_check()
                   1965: 
1.204     matthew  1966: Inputs: $Metadata, a hash pointer of metadata for a resource.
                   1967: 
                   1968: Returns: 1 if the resource is available to the user making the query, 
                   1969:          0 otherwise.
                   1970: 
1.144     matthew  1971: =cut
                   1972: 
                   1973: ######################################################################
                   1974: ######################################################################
                   1975: sub copyright_check {
                   1976:     my $Metadata = shift;
                   1977:     # Check copyright tags and skip results the user cannot use
                   1978:     my (undef,undef,$resdom,$resname) = split('/',
                   1979:                                               $Metadata->{'url'});
                   1980:     # Check for priv
                   1981:     if (($Metadata->{'copyright'} eq 'priv') && 
1.243     albertel 1982:         (($env{'user.name'} ne $resname) &&
                   1983:          ($env{'user.domain'} ne $resdom))) {
1.144     matthew  1984:         return 0;
                   1985:     }
                   1986:     # Check for domain
                   1987:     if (($Metadata->{'copyright'} eq 'domain') &&
1.243     albertel 1988:         ($env{'user.domain'} ne $resdom)) {
1.144     matthew  1989:         return 0;
                   1990:     }
                   1991:     return 1;
                   1992: }
                   1993: 
1.151     matthew  1994: ######################################################################
                   1995: ######################################################################
                   1996: 
                   1997: =pod
                   1998: 
1.204     matthew  1999: =item &ensure_db_and_table()
1.151     matthew  2000: 
                   2001: Ensure we can get lonmysql to connect to the database and the table we
                   2002: need exists.
                   2003: 
                   2004: Inputs: $r, table id
                   2005: 
                   2006: Returns: undef on error, 1 if the table exists.
                   2007: 
                   2008: =cut
                   2009: 
                   2010: ######################################################################
                   2011: ######################################################################
                   2012: sub ensure_db_and_table {
                   2013:     my ($r,$table) = @_;
                   2014:     ##
                   2015:     ## Sanity check the table id.
                   2016:     ##
                   2017:     if (! defined($table) || $table eq '' || $table =~ /\D/ ) {
                   2018:         $r->print("Unable to retrieve search results.  ".
                   2019:                   "Unable to determine the table results were stored in.  ".
1.256   ! albertel 2020: 		  &Apache::loncommon::end_page());
1.151     matthew  2021:         return undef;
                   2022:     }
                   2023:     ##
                   2024:     ## Make sure we can connect and the table exists.
                   2025:     ##
                   2026:     my $connection_result = &Apache::lonmysql::connect_to_db();
                   2027:     if (!defined($connection_result)) {
                   2028:         $r->print("Unable to connect to the MySQL database where your results".
1.256   ! albertel 2029:                   " are stored.".
        !          2030: 		  &Apache::loncommon::end_page());
1.151     matthew  2031:         &Apache::lonnet::logthis("lonsearchcat: unable to get lonmysql to".
                   2032:                                  " connect to database.");
                   2033:         &Apache::lonnet::logthis(&Apache::lonmysql::get_error());
                   2034:         return undef;
                   2035:     }
                   2036:     my $table_check = &Apache::lonmysql::check_table($table);
                   2037:     if (! defined($table_check)) {
1.256   ! albertel 2038:         $r->print("A MySQL error has occurred.</form>".
        !          2039: 		  &Apache::loncommon::end_page());
1.151     matthew  2040:         &Apache::lonnet::logthis("lonmysql was unable to determine the status".
                   2041:                                  " of table ".$table);
                   2042:         return undef;
                   2043:     } elsif (! $table_check) {
                   2044:         $r->print("The table of results could not be found.");
                   2045:         &Apache::lonnet::logthis("The user requested a table, ".$table.
                   2046:                                  ", that could not be found.");
                   2047:         return undef;
                   2048:     }
                   2049:     return 1;
                   2050: }
                   2051: 
                   2052: ######################################################################
                   2053: ######################################################################
                   2054: 
                   2055: =pod
                   2056: 
1.204     matthew  2057: =item &print_sort_form()
                   2058: 
                   2059: The sort feature is not implemented at this time.  This form just prints 
                   2060: a link to change the search query.
1.151     matthew  2061: 
                   2062: =cut
                   2063: 
                   2064: ######################################################################
                   2065: ######################################################################
                   2066: sub print_sort_form {
                   2067:     my ($r,$pretty_query_string) = @_;
1.224     matthew  2068:     my $bodytag=&Apache::loncommon::bodytag(undef,undef,undef,1).
                   2069:         &Apache::lonhtmlcommon::breadcrumbs
                   2070:         (undef,'Searching','Searching',undef,undef,
1.243     albertel 2071:          $env{'form.catalogmode'} ne 'groupsearch');
1.224     matthew  2072: 
1.151     matthew  2073:     ##
1.187     www      2074:     my %SortableFields=&Apache::lonlocal::texthash( 
                   2075:          id        => 'Default',
1.151     matthew  2076:          title     => 'Title',
                   2077:          author    => 'Author',
                   2078:          subject   => 'Subject',
                   2079:          url       => 'URL',
                   2080:          version   => 'Version Number',
                   2081:          mime      => 'Mime type',
                   2082:          lang      => 'Language',
                   2083:          owner     => 'Owner/Publisher',
                   2084:          copyright => 'Copyright',
                   2085:          hostname  => 'Host',
                   2086:          creationdate     => 'Creation Date',
1.187     www      2087:          lastrevisiondate => 'Revision Date'
1.151     matthew  2088:      );
                   2089:     ##
1.243     albertel 2090:     my $table = $env{'form.table'};
1.151     matthew  2091:     return if (! &ensure_db_and_table($r,$table));
                   2092:     ##
                   2093:     ## Get the number of results 
                   2094:     ##
                   2095:     my $total_results = &Apache::lonmysql::number_of_rows($table);
                   2096:     if (! defined($total_results)) {
1.256   ! albertel 2097:         $r->print("A MySQL error has occurred.</form>".
        !          2098: 		  &Apache::loncommon::end_page());
1.151     matthew  2099:         &Apache::lonnet::logthis("lonmysql was unable to determine the number".
                   2100:                                  " of rows in table ".$table);
                   2101:         &Apache::lonnet::logthis(&Apache::lonmysql::get_error());
                   2102:         return;
                   2103:     }
                   2104:     my $result;
1.256   ! albertel 2105:     my $html     = &Apache::lonxml::xmlbegin();
        !          2106:     my $head     = &Apache::lonxml::headtag('Results');
        !          2107:     my $end_head = &Apache::loncommon::endheadtag();
1.151     matthew  2108:     $result.=<<END;
1.238     albertel 2109: $html
1.256   ! albertel 2110: $head
1.151     matthew  2111: <script>
                   2112:     function change_sort() {
                   2113:         var newloc = "/adm/searchcat?phase=results";
1.243     albertel 2114:         newloc += "&persistent_db_id=$env{'form.persistent_db_id'}";
1.151     matthew  2115:         newloc += "&sortby=";
                   2116:         newloc += document.forms.statusform.elements.sortby.value;
                   2117:         parent.resultsframe.location= newloc;
                   2118:     }
                   2119: </script>
1.256   ! albertel 2120: $end_head
1.155     matthew  2121: $bodytag
1.151     matthew  2122: <form name="statusform" action="" method="post">
1.153     matthew  2123: <input type="hidden" name="Queue" value="" />
1.151     matthew  2124: END
                   2125: 
                   2126: #<h2>Sort Results</h2>
                   2127: #Sort by: <select size="1" name="sortby" onchange="javascript:change_sort();">
1.243     albertel 2128: #    $env{'form.sortby'} = 'id' if (! defined($env{'form.sortby'}));
1.151     matthew  2129: #    foreach (keys(%SortableFields)) {
                   2130: #        $result.="<option name=\"$_\"";
1.243     albertel 2131: #        if ($_ eq $env{'form.sortby'}) {
1.151     matthew  2132: #            $result.=" selected ";
                   2133: #        }
                   2134: #        $result.=" >$SortableFields{$_}</option>\n";
                   2135: #    }
                   2136: #    $result.="</select>\n";
                   2137:     my $revise = &revise_button();
                   2138:     $result.=<<END;
                   2139: <p>
                   2140: There are $total_results matches to your query. $revise
                   2141: </p><p>
                   2142: Search:$pretty_query_string
                   2143: </p>
                   2144: </form>
                   2145: END
1.256   ! albertel 2146:     $r->print($result.&Apache::loncommon::end_page());
1.151     matthew  2147:     return;
                   2148: }
                   2149: 
1.144     matthew  2150: #####################################################################
                   2151: #####################################################################
                   2152: 
                   2153: =pod
                   2154: 
                   2155: =item MySQL Table Description
                   2156: 
                   2157: MySQL table creation requires a precise description of the data to be
                   2158: stored.  The use of the correct types to hold data is vital to efficient
                   2159: storage and quick retrieval of records.  The columns must be described in
                   2160: the following format:
                   2161: 
                   2162: =cut
                   2163: 
1.170     matthew  2164: #####################################################################
                   2165: #####################################################################
1.204     matthew  2166: #
                   2167: # These should probably be scoped but I don't have time right now...
                   2168: #
                   2169: my @Datatypes;
                   2170: my @Fullindicies;
1.147     matthew  2171:     
1.144     matthew  2172: ######################################################################
                   2173: ######################################################################
                   2174: 
                   2175: =pod
                   2176: 
1.146     matthew  2177: =item &create_results_table()
                   2178: 
                   2179: Creates the table of search results by calling lonmysql.  Stores the
1.243     albertel 2180: table id in $env{'form.table'}
1.146     matthew  2181: 
                   2182: Inputs: none.
                   2183: 
                   2184: Returns: the identifier of the table on success, undef on error.
                   2185: 
                   2186: =cut
                   2187: 
                   2188: ######################################################################
                   2189: ######################################################################
1.204     matthew  2190: sub set_up_table_structure {
                   2191:     my ($datatypes,$fullindicies) = 
                   2192:         &LONCAPA::lonmetadata::describe_metadata_storage();
1.212     matthew  2193:     # Copy the table description before modifying it...
                   2194:     @Datatypes = @{$datatypes};
                   2195:     unshift(@Datatypes,{name => 'id',  
1.204     matthew  2196:         type => 'MEDIUMINT',
                   2197:         restrictions => 'UNSIGNED NOT NULL',
                   2198:         primary_key  => 'yes',
                   2199:         auto_inc     => 'yes' });
                   2200:     @Fullindicies = @{$fullindicies};
                   2201:     return;
                   2202: }
                   2203: 
1.146     matthew  2204: sub create_results_table {
1.204     matthew  2205:     &set_up_table_structure();
1.146     matthew  2206:     my $table = &Apache::lonmysql::create_table
1.170     matthew  2207:         ( { columns => \@Datatypes,
1.172     matthew  2208:             FULLTEXT => [{'columns' => \@Fullindicies},],
1.146     matthew  2209:         } );
                   2210:     if (defined($table)) {
1.243     albertel 2211:         $env{'form.table'} = $table;
1.146     matthew  2212:         return $table;
                   2213:     } 
                   2214:     return undef; # Error...
                   2215: }
1.148     matthew  2216: 
1.146     matthew  2217: ######################################################################
                   2218: ######################################################################
                   2219: 
                   2220: =pod
                   2221: 
1.150     matthew  2222: =item Search Status update functions
1.144     matthew  2223: 
1.150     matthew  2224: Each of the following functions changes the values of one of the
                   2225: input fields used to display the search status to the user.  The names
                   2226: should be explanatory.
1.144     matthew  2227: 
1.150     matthew  2228: Inputs: Apache request handler ($r), text to display.
1.148     matthew  2229: 
1.150     matthew  2230: Returns: Nothing.
1.148     matthew  2231: 
                   2232: =over 4
                   2233: 
                   2234: =item &update_count_status()
                   2235: 
1.150     matthew  2236: =item &update_status()
1.148     matthew  2237: 
1.150     matthew  2238: =item &update_seconds()
1.148     matthew  2239: 
                   2240: =back
                   2241: 
                   2242: =cut
                   2243: 
                   2244: ######################################################################
                   2245: ######################################################################
                   2246: sub update_count_status {
                   2247:     my ($r,$text) = @_;
                   2248:     $text =~ s/\'/\\\'/g;
                   2249:     $r->print
                   2250:         ("<script>document.statusform.count.value = ' $text'</script>\n");
                   2251:     $r->rflush();
                   2252: }
                   2253: 
1.150     matthew  2254: sub update_status {
1.148     matthew  2255:     my ($r,$text) = @_;
                   2256:     $text =~ s/\'/\\\'/g;
                   2257:     $r->print
1.150     matthew  2258:         ("<script>document.statusform.status.value = ' $text'</script>\n");
1.148     matthew  2259:     $r->rflush();
                   2260: }
                   2261: 
1.214     matthew  2262: {
1.250     www      2263:     my $max_time  = 300;  # seconds for the search to complete
1.214     matthew  2264:     my $start_time = 0;
                   2265:     my $last_time = 0;
                   2266: 
                   2267: sub reset_timing {
                   2268:     $start_time = 0;
                   2269:     $last_time = 0;
                   2270: }
                   2271: 
                   2272: sub time_left {
                   2273:     if ($start_time == 0) {
                   2274:         $start_time = time;
                   2275:     }
                   2276:     my $time_left = $max_time - (time - $start_time);
                   2277:     $time_left = 0 if ($time_left < 0);
                   2278:     return $time_left;
                   2279: }
                   2280: 
1.150     matthew  2281: sub update_seconds {
1.214     matthew  2282:     my ($r) = @_;
                   2283:     my $time = &time_left();
                   2284:     if (($last_time-$time) > 0) {
                   2285:         $r->print("<script>".
                   2286:                   "document.statusform.seconds.value = '$time'".
                   2287:                   "</script>\n");
                   2288:         $r->rflush();
                   2289:     }
                   2290:     $last_time = $time;
                   2291: }
                   2292: 
1.148     matthew  2293: }
                   2294: 
                   2295: ######################################################################
                   2296: ######################################################################
                   2297: 
                   2298: =pod
                   2299: 
1.204     matthew  2300: =item &revise_button()
1.151     matthew  2301: 
                   2302: Inputs: None
                   2303: 
                   2304: Returns: html string for a 'revise search' button.
                   2305: 
                   2306: =cut
                   2307: 
                   2308: ######################################################################
                   2309: ######################################################################
                   2310: sub revise_button {
                   2311:     my $revise_phase = 'disp_basic';
1.243     albertel 2312:     $revise_phase = 'disp_adv' if ($env{'form.searchmode'} eq 'advanced');
1.151     matthew  2313:     my $newloc = '/adm/searchcat'.
1.243     albertel 2314:         '?persistent_db_id='.$env{'form.persistent_db_id'}.
1.158     matthew  2315:             '&cleargroupsort=1'.
1.151     matthew  2316:             '&phase='.$revise_phase;
                   2317:     my $result = qq{<input type="button" value="Revise search" name="revise"} .
                   2318:         qq{ onClick="parent.location='$newloc';" /> };
                   2319:     return $result;
                   2320: }
                   2321: 
                   2322: ######################################################################
                   2323: ######################################################################
                   2324: 
                   2325: =pod
                   2326: 
1.204     matthew  2327: =item &run_search()
                   2328: 
                   2329: Executes a search query by sending it the the other servers and putting the
                   2330: results into MySQL.
1.144     matthew  2331: 
                   2332: =cut
                   2333: 
                   2334: ######################################################################
                   2335: ######################################################################
                   2336: sub run_search {
1.146     matthew  2337:     my ($r,$query,$customquery,$customshow,$serverlist,$pretty_string) = @_;
1.196     matthew  2338:     my $bodytag=&Apache::loncommon::bodytag(undef,undef,undef,1);
1.227     matthew  2339:     $bodytag.=&Apache::lonhtmlcommon::breadcrumbs
                   2340:         (undef,'Searching','Searching',undef,undef,
1.243     albertel 2341:          $env{'form.catalogmode'} ne 'groupsearch');
1.150     matthew  2342:     my $connection = $r->connection;
1.144     matthew  2343:     #
1.146     matthew  2344:     # Print run_search header
                   2345:     #
1.256   ! albertel 2346:     my $html = &Apache::lonxml::xmlbegin();
        !          2347:     my $head = &Apache::loncommon::head('Search Status');
1.151     matthew  2348:     $r->print(<<END);
1.238     albertel 2349: $html
1.256   ! albertel 2350: $head
1.155     matthew  2351: $bodytag
1.151     matthew  2352: <form name="statusform" action="" method="post">
                   2353: <input type="hidden" name="Queue" value="" />
                   2354: END
1.230     matthew  2355:     # Remove leading and trailing <br />
                   2356:     $pretty_string =~ s:^\s*<br />::i;
                   2357:     $pretty_string =~ s:(<br />)*\s*$::im;
                   2358:     my @Lines = split("<br />",$pretty_string);
                   2359:     # I keep getting blank items at the end of the list, hence the following:
                   2360:     while ($Lines[-1] =~ /^\s*$/ && @Lines) {
                   2361:         pop(@Lines);
                   2362:     }
1.152     matthew  2363:     if (@Lines > 2) {
1.230     matthew  2364:         $pretty_string = join '<br />',(@Lines[0..2],'....<br />');
1.151     matthew  2365:     }
1.214     matthew  2366:     $r->print(&mt("Search: [_1]",$pretty_string));
1.146     matthew  2367:     $r->rflush();
                   2368:     #
1.145     matthew  2369:     # Determine the servers we need to contact.
1.144     matthew  2370:     my @Servers_to_contact;
                   2371:     if (defined($serverlist)) {
1.152     matthew  2372:         if (ref($serverlist) eq 'ARRAY') {
                   2373:             @Servers_to_contact = @$serverlist;
                   2374:         } else {
                   2375:             @Servers_to_contact = ($serverlist);
                   2376:         }
1.144     matthew  2377:     } else {
                   2378:         @Servers_to_contact = sort(keys(%Apache::lonnet::libserv));
                   2379:     }
                   2380:     my %Server_status;
1.214     matthew  2381:     #
                   2382:     # Check on the mysql table we will use to store results.
1.243     albertel 2383:     my $table =$env{'form.table'};
1.150     matthew  2384:     if (! defined($table) || $table eq '' || $table =~ /\D/ ) {
1.147     matthew  2385:         $r->print("Unable to determine table id to store search results in.".
1.256   ! albertel 2386:                   "The search has been aborted.".
        !          2387: 		  &Apache::loncommon::end_page());
1.147     matthew  2388:         return;
                   2389:     }
                   2390:     my $table_status = &Apache::lonmysql::check_table($table);
                   2391:     if (! defined($table_status)) {
1.256   ! albertel 2392:         $r->print("Unable to determine status of table.".
        !          2393: 		  &Apache::loncommon::end_page());
1.147     matthew  2394:         &Apache::lonnet::logthis("Bogus table id of $table for ".
1.243     albertel 2395:                                  "$env{'user.name'} @ $env{'user.domain'}");
1.147     matthew  2396:         &Apache::lonnet::logthis("lonmysql error = ".
1.144     matthew  2397:                                  &Apache::lonmysql::get_error());
1.147     matthew  2398:         return;
                   2399:     }
                   2400:     if (! $table_status) {
1.204     matthew  2401:         &Apache::lonnet::logthis("lonmysql error = ".
                   2402:                                  &Apache::lonmysql::get_error());
                   2403:         &Apache::lonnet::logthis("lonmysql debug = ".
                   2404:                                  &Apache::lonmysql::get_debug());
                   2405:         &Apache::lonnet::logthis('table status = "'.$table_status.'"');
1.147     matthew  2406:         $r->print("The table id,$table, we tried to use is invalid.".
1.256   ! albertel 2407:                   "The search has been aborted.".
        !          2408: 		  &Apache::loncommon::end_page());
1.144     matthew  2409:         return;
                   2410:     }
1.145     matthew  2411:     ##
1.146     matthew  2412:     ## Prepare for the big loop.
1.144     matthew  2413:     my $hitcountsum;
                   2414:     my $server; 
                   2415:     my $status;
1.151     matthew  2416:     my $revise = &revise_button();
1.148     matthew  2417:     $r->print(<<END);
                   2418: <table>
1.151     matthew  2419: <tr><th>Status</th><th>Total Matches</th><th>Time Remaining</th><th></th></tr>
1.148     matthew  2420: <tr>
1.240     matthew  2421: <td><input type="text" name="status"  value="" size="50" /></td>
1.150     matthew  2422: <td><input type="text" name="count"   value="" size="10" /></td>
                   2423: <td><input type="text" name="seconds" value="" size="8" /></td>
1.151     matthew  2424: <td>$revise</td>
1.148     matthew  2425: </tr>
                   2426: </table>
                   2427: </form>
                   2428: END
                   2429:     $r->rflush();
1.214     matthew  2430:     &reset_timing();
                   2431:     &update_seconds($r);
                   2432:     &update_status($r,&mt('contacting [_1]',$Servers_to_contact[0]));
                   2433:     while (&time_left() &&
1.144     matthew  2434:            ((@Servers_to_contact) || keys(%Server_status))) {
1.214     matthew  2435:         &update_seconds($r);
                   2436:         #
                   2437:         # Send out a search request
1.144     matthew  2438:         if (@Servers_to_contact) {
                   2439:             # Contact one server
                   2440:             my $server = shift(@Servers_to_contact);
1.214     matthew  2441:             &update_status($r,&mt('contacting [_1]',$server));
1.144     matthew  2442:             my $reply=&Apache::lonnet::metadata_query($query,$customquery,
                   2443:                                                       $customshow,[$server]);
                   2444:             ($server) = keys(%$reply);
                   2445:             $Server_status{$server} = $reply->{$server};
                   2446:         } else {
1.150     matthew  2447:             # wait a sec. to give time for files to be written
                   2448:             # This sleep statement is here instead of outside the else 
                   2449:             # block because we do not want to pause if we have servers
                   2450:             # left to contact.  
1.183     matthew  2451:             if (scalar (keys(%Server_status))) {
                   2452:                 &update_status($r,
1.214     matthew  2453:                        &mt('waiting on [_1]',join(' ',keys(%Server_status))));
1.183     matthew  2454:             }
1.150     matthew  2455:             sleep(1)1.144     matthew  2456:         }
1.159     matthew  2457:         #
                   2458:         # Loop through the servers we have contacted but do not
                   2459:         # have results from yet, looking for results.
1.228     matthew  2460:         foreach my $server (keys(%Server_status)) {
1.150     matthew  2461:             last if ($connection->aborted());
1.214     matthew  2462:             &update_seconds($r);
1.228     matthew  2463:             my $status = $Server_status{$server};
1.144     matthew  2464:             if ($status eq 'con_lost') {
                   2465:                 delete ($Server_status{$server});
                   2466:                 next;
                   2467:             }
1.242     albertel 2468:             $status=~s|/||g; 
                   2469:        	    my $datafile=$r->dir_config('lonDaemons').'/tmp/'.$status;
1.144     matthew  2470:             if (-e $datafile && ! -e "$datafile.end") {
1.214     matthew  2471:                 &update_status($r,&mt('Receiving results from [_1]',$server));
1.144     matthew  2472:                 next;
                   2473:             }
1.150     matthew  2474:             last if ($connection->aborted());
1.144     matthew  2475:             if (-e "$datafile.end") {
1.214     matthew  2476:                 &update_status($r,&mt('Reading results from [_1]',$server));
1.144     matthew  2477:                 if (-z "$datafile") {
                   2478:                     delete($Server_status{$server});
                   2479:                     next;
                   2480:                 }
                   2481:                 my $fh;
                   2482:                 if (!($fh=Apache::File->new($datafile))) { 
1.146     matthew  2483:                     $r->print("Unable to open search results file for ".
1.145     matthew  2484:                                   "server $server.  Omitting from search");
1.150     matthew  2485:                     delete($Server_status{$server}); 
                   2486:                    next;
1.144     matthew  2487:                 }
                   2488:                 # Read in the whole file.
                   2489:                 while (my $result = <$fh>) {
1.150     matthew  2490:                     last if ($connection->aborted());
1.214     matthew  2491:                     #
                   2492:                     # Records are stored one per line
1.144     matthew  2493:                     chomp($result);
1.214     matthew  2494:                     next if (! $result);
                   2495:                     #
1.144     matthew  2496:                     # Parse the result.
                   2497:                     my %Fields = &parse_raw_result($result,$server);
                   2498:                     $Fields{'hostname'} = $server;
1.214     matthew  2499:                     #
1.248     www      2500:                     # Skip if external and we did not want that
                   2501:                     next if ((! $env{'form.inclext'}) && ($Fields{'url'}=~/^\/ext\//));
1.214     matthew  2502:                     # Skip based on copyright
1.144     matthew  2503:                     next if (! &copyright_check(\%Fields));
1.248     www      2504: 
1.214     matthew  2505:                     #
1.144     matthew  2506:                     # Store the result in the mysql database
                   2507:                     my $result = &Apache::lonmysql::store_row($table,\%Fields);
                   2508:                     if (! defined($result)) {
1.146     matthew  2509:                         $r->print(&Apache::lonmysql::get_error());
1.144     matthew  2510:                     }
1.214     matthew  2511:                     #
1.144     matthew  2512:                     $hitcountsum ++;
1.214     matthew  2513:                     &update_seconds($r);
1.150     matthew  2514:                     if ($hitcountsum % 50 == 0) {
                   2515:                         &update_count_status($r,$hitcountsum);
                   2516:                     }
1.214     matthew  2517:                 }
1.144     matthew  2518:                 $fh->close();
                   2519:                 # $server is only deleted if the results file has been 
                   2520:                 # found and (successfully) opened.  This may be a bad idea.
                   2521:                 delete($Server_status{$server});
                   2522:             }
1.150     matthew  2523:             last if ($connection->aborted());
1.148     matthew  2524:             &update_count_status($r,$hitcountsum);
1.144     matthew  2525:         }
1.150     matthew  2526:         last if ($connection->aborted());
1.214     matthew  2527:         &update_seconds($r);
1.144     matthew  2528:     }
1.214     matthew  2529:     &update_status($r,&mt('Search Complete [_1]',$server));
                   2530:     &update_seconds($r);
1.204     matthew  2531:     #
1.214     matthew  2532:     &Apache::lonmysql::disconnect_from_db(); # This is unneccessary
1.204     matthew  2533:     #
1.144     matthew  2534:     # We have run out of time or run out of servers to talk to and
1.214     matthew  2535:     # results to get, so let the client know the top frame needs to be
                   2536:     # loaded from /adm/searchcat
1.256   ! albertel 2537:     $r->print(&Apache::loncommon::end_page());
1.243     albertel 2538: #    if ($env{'form.catalogmode'} ne 'groupsearch') {
1.153     matthew  2539:         $r->print("<script>".
                   2540:                       "window.location='/adm/searchcat?".
                   2541:                       "phase=sort&".
1.243     albertel 2542:                       "persistent_db_id=$env{'form.persistent_db_id'}';".
1.153     matthew  2543:                   "</script>");
1.224     matthew  2544: #    }
1.144     matthew  2545:     return;
                   2546: }
                   2547: 
                   2548: ######################################################################
                   2549: ######################################################################
1.204     matthew  2550: 
1.144     matthew  2551: =pod
                   2552: 
1.204     matthew  2553: =item &prev_next_buttons()
                   2554: 
                   2555: Returns html for the previous and next buttons on the search results page.
1.144     matthew  2556: 
                   2557: =cut
                   2558: 
                   2559: ######################################################################
                   2560: ######################################################################
1.146     matthew  2561: sub prev_next_buttons {
1.145     matthew  2562:     my ($current_min,$show,$total,$parms) = @_;
                   2563:     return '' if ($show eq 'all'); # No links if you get them all at once.
1.214     matthew  2564:     #
1.223     matthew  2565:     # Create buttons
                   2566:     my $buttons = '<input type="submit" name="prev" value="'.&mt('Prev').'" ';
                   2567:     $buttons .= '/>';
                   2568:     $buttons .= '&nbsp;'x3;
                   2569:     $buttons .= '<input type="submit" name="reload" '.
                   2570:         'value="'.&mt('Reload').'" />';
                   2571:     $buttons .= '&nbsp;'x3;
                   2572:     $buttons .= '<input type="submit" name="next" value="'.&mt('Next').'" ';
                   2573:     $buttons .= '/>';
                   2574:     return $buttons;
1.144     matthew  2575: }
1.204     matthew  2576: 
1.144     matthew  2577: ######################################################################
                   2578: ######################################################################
                   2579: 
                   2580: =pod
                   2581: 
1.204     matthew  2582: =item &display_results()
                   2583: 
                   2584: Prints the results out for selection and perusal.
1.144     matthew  2585: 
                   2586: =cut
                   2587: 
                   2588: ######################################################################
                   2589: ######################################################################
                   2590: sub display_results {
1.196     matthew  2591:     my ($r,$importbutton,$closebutton,$diropendb) = @_;
1.150     matthew  2592:     my $connection = $r->connection;
                   2593:     $r->print(&search_results_header($importbutton,$closebutton));
1.144     matthew  2594:     ##
                   2595:     ## Set viewing function
                   2596:     ##
1.243     albertel 2597:     my $viewfunction = $Views{$env{'form.viewselect'}};
1.144     matthew  2598:     if (!defined($viewfunction)) {
                   2599:         $r->print("Internal Error - Bad view selected.\n");
                   2600:         $r->rflush();
                   2601:         return;
                   2602:     }
                   2603:     ##
1.158     matthew  2604:     ## $checkbox_num is a count of the number of checkboxes output on the 
                   2605:     ## page this is used only during catalogmode=groupsearch.
                   2606:     my $checkbox_num = 0;
                   2607:     ##
1.144     matthew  2608:     ## Get the catalog controls setup
                   2609:     ##
1.146     matthew  2610:     my $action = "/adm/searchcat?phase=results";
                   2611:     ##
1.204     matthew  2612:     ## Deal with groupsearch by opening the groupsearch db file.
1.243     albertel 2613:     if ($env{'form.catalogmode'} eq 'groupsearch') {
1.146     matthew  2614:         if (! tie(%groupsearch_db,'GDBM_File',$diropendb,
1.148     matthew  2615:                   &GDBM_WRCREAT(),0640)) {
1.256   ! albertel 2616:             $r->print('Unable to store import results.</form>'.
        !          2617: 		      &Apache::loncommon::end_page());
1.146     matthew  2618:             $r->rflush();
                   2619:             return;
                   2620:         } 
1.144     matthew  2621:     }
1.145     matthew  2622:     ##
                   2623:     ## Prepare the table for querying
1.243     albertel 2624:     my $table = $env{'form.table'};
1.151     matthew  2625:     return if (! &ensure_db_and_table($r,$table));
1.145     matthew  2626:     ##
                   2627:     ## Get the number of results 
                   2628:     my $total_results = &Apache::lonmysql::number_of_rows($table);
                   2629:     if (! defined($total_results)) {
1.256   ! albertel 2630:         $r->print("A MySQL error has occurred.</form>".
        !          2631: 		  &Apache::loncommon::end_page());
1.145     matthew  2632:         &Apache::lonnet::logthis("lonmysql was unable to determine the number".
                   2633:                                  " of rows in table ".$table);
                   2634:         &Apache::lonnet::logthis(&Apache::lonmysql::get_error());
                   2635:         return;
                   2636:     }
                   2637:     ##
                   2638:     ## Determine how many results we need to get
1.243     albertel 2639:     $env{'form.start'} = 1  if (! exists($env{'form.start'}));
                   2640:     $env{'form.show'}  = 20 if (! exists($env{'form.show'}));
                   2641:     if (exists($env{'form.prev'})) {
                   2642:         $env{'form.start'} -= $env{'form.show'};
                   2643:     } elsif (exists($env{'form.next'})) {
                   2644:         $env{'form.start'} += $env{'form.show'};
                   2645:     }
                   2646:     $env{'form.start'} = 1 if ($env{'form.start'}<1);
                   2647:     $env{'form.start'} = $total_results if ($env{'form.start'}>$total_results);
                   2648:     my $min = $env{'form.start'};
1.145     matthew  2649:     my $max;
1.243     albertel 2650:     if ($env{'form.show'} eq 'all') {
1.145     matthew  2651:         $max = $total_results ;
                   2652:     } else {
1.243     albertel 2653:         $max = $min + $env{'form.show'} - 1;
1.146     matthew  2654:         $max = $total_results if ($max > $total_results);
1.145     matthew  2655:     }
                   2656:     ##
1.223     matthew  2657:     ## Output form elements
                   2658:     $r->print(&hidden_field('table').
                   2659:               &hidden_field('phase').
                   2660:               &hidden_field('persistent_db_id').
                   2661:               &hidden_field('start')
                   2662:               );
1.232     matthew  2663:     #
                   2664:     # Build sorting selector
1.241     matthew  2665:     my @fields = 
                   2666:         (
                   2667:          {key=>'default' },
                   2668:          {key=>'title' },
                   2669:          {key =>'author' },
                   2670:          {key =>'subject'},
                   2671:          {key =>'url',desc=>'URL'},
                   2672:          {key =>'keywords'},
                   2673:          {key =>'language'},
                   2674:          {key =>'creationdate'},
                   2675:          {key =>'lastrevisiondate'},
                   2676:          {key =>'owner'},
                   2677:          {key =>'copyright'},
                   2678:          {key =>'authorspace'},
                   2679:          {key =>'lowestgradelevel'},
                   2680:          {key =>'highestgradelevel'},
                   2681:          {key =>'standards',desc=>'Standards'},
                   2682:          {key =>'count',desc=>'Number of accesses'},
                   2683:          {key =>'stdno',desc=>'Students Attempting'},
                   2684:          {key =>'avetries',desc=>'Average Number of Tries'},
                   2685:          {key =>'difficulty',desc=>'Mean Degree of Difficulty'},
                   2686:          {key =>'disc',desc=>'Mean Degree of Discrimination'},
                   2687:          {key =>'clear',desc=>'Evaluation: Clear'},
                   2688:          {key =>'technical',desc=>'Evaluation: Technically Correct'},
                   2689:          {key =>'correct',desc=>'Evaluation: Material is Correct'},
                   2690:          {key =>'helpful',desc=>'Evaluation: Material is Helpful'},
                   2691:          {key =>'depth',desc=>'Evaluation: Material has Depth'},
                   2692:          );
                   2693:     my %fieldnames = &Apache::lonmeta::fieldnames();
                   2694:     my @field_order;
                   2695:     foreach my $field_data (@fields) {
                   2696:         push(@field_order,$field_data->{'key'});
                   2697:         if (! exists($field_data->{'desc'})) {
                   2698:             $field_data->{'desc'}=$fieldnames{$field_data->{'key'}};
                   2699:         } else {
                   2700:             if (! defined($field_data->{'desc'})) {
                   2701:                 $field_data->{'desc'} = ucfirst($field_data->{'key'});
                   2702:             }
                   2703:             $field_data->{'desc'} = &mt($field_data->{'desc'});
                   2704:         }
                   2705:     }
                   2706:     my %sort_fields = map {$_->{'key'},$_->{'desc'}} @fields;
                   2707:     $sort_fields{'select_form_order'} = \@field_order;
1.248     www      2708:     $env{'form.sortorder'} = 'desc' if (! exists($env{'form.sortorder'}));
                   2709:     $env{'form.sortfield'} = 'count' if (! exists($env{'form.sortfield'}));
                   2710:     if (! exists($env{'form.sortorder'})) {
                   2711: 	if ($env{'form.sortfield'}=~/^(count|stdno|disc|clear|technical|correct|helpful)$/) {
                   2712: 	    $env{'form.sortorder'}='desc';
                   2713: 	} else {
                   2714: 	    $env{'form.sortorder'}='asc';
                   2715: 	}
                   2716:     }
1.241     matthew  2717:     my $sortform = &mt('Sort by [_1] [_2]',
1.244     albertel 2718:                        &Apache::loncommon::select_form($env{'form.sortfield'},
1.232     matthew  2719:                                                       'sortfield',
1.241     matthew  2720:                                                       %sort_fields),
1.244     albertel 2721:                        &Apache::loncommon::select_form($env{'form.sortorder'},
1.241     matthew  2722:                                                       'sortorder',
                   2723:                                                       (asc =>&mt('Ascending'),
                   2724:                                                        desc=>&mt('Descending')
                   2725:                                                        ))
                   2726:                        );
1.223     matthew  2727:     ##
1.145     matthew  2728:     ## Output links (if necessary) for 'prev' and 'next' pages.
1.146     matthew  2729:     $r->print
1.232     matthew  2730:         ('<table width="100%"><tr><td width="25%" align="right">'.
1.241     matthew  2731:          '<nobr>'.$sortform.'</nobr>'.
1.232     matthew  2732:          '</td><td width="25%" align="right">'.
1.243     albertel 2733:          &prev_next_buttons($min,$env{'form.show'},$total_results).
1.223     matthew  2734:          '</td><td align="right">'.
                   2735:          &viewoptions().'</td></tr></table>'
1.146     matthew  2736:          );
1.150     matthew  2737:     if ($total_results == 0) {
1.256   ! albertel 2738:         $r->print('<meta HTTP-EQUIV="Refresh" CONTENT="2" />'.
1.187     www      2739:                   '<h3>'.&mt('There are currently no results').'.</h3>'.
1.256   ! albertel 2740:                   "</form>".
        !          2741: 		  &Apache::loncommon::end_page());
1.150     matthew  2742:         return;
                   2743:     } else {
1.232     matthew  2744:         $r->print('<center>'.
                   2745:                   mt('Results [_1] to [_2] out of [_3]',
                   2746:                      $min,$max,$total_results).
                   2747:                   "</center>\n");
1.150     matthew  2748:     }
1.145     matthew  2749:     ##
                   2750:     ## Get results from MySQL table
1.232     matthew  2751:     my $sort_command  = 'id>='.$min.' AND id<='.$max;
1.241     matthew  2752:     my $order;
1.244     albertel 2753:     if (exists($env{'form.sortorder'})) {
                   2754:         if ($env{'form.sortorder'} eq 'asc') {
1.241     matthew  2755:             $order = 'ASC';
1.244     albertel 2756:         } elsif ($env{'form.sortorder'} eq 'desc') {
1.241     matthew  2757:             $order = 'DESC';
                   2758:         } else {
                   2759:             $order = '';
                   2760:         }
                   2761:     } else {
                   2762:         $order = '';
                   2763:     }
1.244     albertel 2764:     if ($env{'form.sortfield'} ne 'default' && 
                   2765:         exists($sort_fields{$env{'form.sortfield'}})) {
                   2766:         $sort_command = $env{'form.sortfield'}.' IS NOT NULL '.
                   2767:             'ORDER BY '.$env{'form.sortfield'}.' '.$order.
1.249     www      2768:             '  LIMIT '.($min-1).','.($max-$min+1);
1.232     matthew  2769:     }
                   2770:     my @Results = &Apache::lonmysql::get_rows($table,$sort_command);
1.145     matthew  2771:     ##
                   2772:     ## Loop through the results and output them.
1.144     matthew  2773:     foreach my $row (@Results) {
1.150     matthew  2774:         if ($connection->aborted()) {
1.162     www      2775:             &cleanup();
1.150     matthew  2776:             return;
                   2777:         }
1.144     matthew  2778:         my %Fields = %{&parse_row(@$row)};
1.145     matthew  2779:         my $output="<p>\n";
1.210     matthew  2780:         if (! defined($Fields{'title'}) || $Fields{'title'} eq '') {
                   2781:             $Fields{'title'} = 'Untitled';
                   2782:         }
1.158     matthew  2783:         my $prefix=&catalogmode_output($Fields{'title'},$Fields{'url'},
                   2784:                                        $Fields{'id'},$checkbox_num++);
1.144     matthew  2785:         # Render the result into html
1.150     matthew  2786:         $output.= &$viewfunction($prefix,%Fields);
1.145     matthew  2787:         # Print them out as they come in.
1.144     matthew  2788:         $r->print($output);
                   2789:         $r->rflush();
                   2790:     }
                   2791:     if (@Results < 1) {
1.187     www      2792:         $r->print(&mt("There were no results matching your query"));
1.147     matthew  2793:     } else {
                   2794:         $r->print
1.148     matthew  2795:             ('<center>'.
1.243     albertel 2796:              &prev_next_buttons($min,$env{'form.show'},$total_results,
                   2797:                                 "table=".$env{'form.table'}.
1.147     matthew  2798:                                 "&phase=results".
                   2799:                                 "&persistent_db_id=".
1.243     albertel 2800:                                 $env{'form.persistent_db_id'})
1.148     matthew  2801:              ."</center>\n"
1.147     matthew  2802:              );
1.144     matthew  2803:     }
1.256   ! albertel 2804:     $r->print("</form>".&Apache::loncommon::end_page());
1.144     matthew  2805:     $r->rflush();
1.150     matthew  2806:     untie %groupsearch_db if (tied(%groupsearch_db));
1.144     matthew  2807:     return;
                   2808: }
                   2809: 
                   2810: ######################################################################
                   2811: ######################################################################
                   2812: 
                   2813: =pod
                   2814: 
1.158     matthew  2815: =item &catalogmode_output($title,$url,$fnum,$checkbox_num)
1.145     matthew  2816: 
                   2817: Returns html needed for the various catalog modes.  Gets inputs from
1.243     albertel 2818: $env{'form.catalogmode'}.  Stores data in %groupsearch_db.
1.145     matthew  2819: 
                   2820: =cut
                   2821: 
                   2822: ######################################################################
                   2823: ######################################################################
                   2824: sub catalogmode_output {
                   2825:     my $output = '';
1.158     matthew  2826:     my ($title,$url,$fnum,$checkbox_num) = @_;
1.243     albertel 2827:     if ($env{'form.catalogmode'} eq 'interactive') {
1.150     matthew  2828:         $title=~ s/\'/\\\'/g;
1.243     albertel 2829:         if ($env{'form.catalogmode'} eq 'interactive') {
1.145     matthew  2830:             $output.=<<END 
                   2831: <font size='-1'><INPUT TYPE="button" NAME="returnvalues" VALUE="SELECT"
                   2832: onClick="javascript:select_data('$title','$url')">
                   2833: </font>
                   2834: END
                   2835:         }
1.243     albertel 2836:     } elsif ($env{'form.catalogmode'} eq 'groupsearch') {
1.145     matthew  2837:         $groupsearch_db{"pre_${fnum}_link"}=$url;
                   2838:         $groupsearch_db{"pre_${fnum}_title"}=$title;
                   2839:         $output.=<<END;
                   2840: <font size='-1'>
                   2841: <input type="checkbox" name="returnvalues" value="SELECT"
1.158     matthew  2842: onClick="javascript:queue($checkbox_num,$fnum)" />
1.145     matthew  2843: </font>
                   2844: END
                   2845:     }
                   2846:     return $output;
                   2847: }
                   2848: ######################################################################
                   2849: ######################################################################
                   2850: 
                   2851: =pod
                   2852: 
1.204     matthew  2853: =item &parse_row()
1.144     matthew  2854: 
                   2855: Parse a row returned from the database.
                   2856: 
                   2857: =cut
                   2858: 
                   2859: ######################################################################
                   2860: ######################################################################
                   2861: sub parse_row {
                   2862:     my @Row = @_;
                   2863:     my %Fields;
1.204     matthew  2864:     if (! scalar(@Datatypes)) {
                   2865:         &set_up_table_structure();
                   2866:     }
1.144     matthew  2867:     for (my $i=0;$i<=$#Row;$i++) {
1.170     matthew  2868:         $Fields{$Datatypes[$i]->{'name'}}=&Apache::lonnet::unescape($Row[$i]);
1.144     matthew  2869:     }
                   2870:     $Fields{'language'} = 
1.198     www      2871:         &Apache::loncommon::languagedescription($Fields{'language'});
1.144     matthew  2872:     $Fields{'copyrighttag'} =
                   2873:         &Apache::loncommon::copyrightdescription($Fields{'copyright'});
                   2874:     $Fields{'mimetag'} =
                   2875:         &Apache::loncommon::filedescription($Fields{'mime'});
                   2876:     return \%Fields;
                   2877: }
1.126     matthew  2878: 
                   2879: ###########################################################
                   2880: ###########################################################
                   2881: 
                   2882: =pod
                   2883: 
                   2884: =item &parse_raw_result()
                   2885: 
                   2886: Takes a line from the file of results and parse it.  Returns a hash 
1.198     www      2887: with keys according to column labels
1.126     matthew  2888: 
                   2889: In addition, the following tags are set by calling the appropriate 
1.198     www      2890: lonnet function: 'language', 'copyrighttag', 'mimetag'.
1.126     matthew  2891: 
                   2892: The 'title' field is set to "Untitled" if the title field is blank.
                   2893: 
                   2894: 'abstract' and 'keywords' are truncated to 200 characters.
                   2895: 
                   2896: =cut
                   2897: 
                   2898: ###########################################################
                   2899: ###########################################################
                   2900: sub parse_raw_result {
                   2901:     my ($result,$hostname) = @_;
1.204     matthew  2902:     # conclude from self to others regarding fields
1.206     matthew  2903:     my %Fields=&LONCAPA::lonmetadata::metadata_col_to_hash
                   2904:         (map {
                   2905:             &Apache::lonnet::unescape($_);
                   2906:         } (split(/\,/,$result)) );
1.126     matthew  2907:     return %Fields;
                   2908: }
                   2909: 
                   2910: ###########################################################
                   2911: ###########################################################
                   2912: 
                   2913: =pod
                   2914: 
                   2915: =item &handle_custom_fields()
                   2916: 
                   2917: =cut
                   2918: 
                   2919: ###########################################################
                   2920: ###########################################################
                   2921: sub handle_custom_fields {
                   2922:     my @results = @{shift()};
                   2923:     my $customshow='';
                   2924:     my $extrashow='';
                   2925:     my @customfields;
1.243     albertel 2926:     if ($env{'form.customshow'}) {
                   2927:         $customshow=$env{'form.customshow'};
1.126     matthew  2928:         $customshow=~s/[^\w\s]//g;
                   2929:         my @fields=map {
                   2930:             "<font color=\"#008000\">$_:</font><!-- $_ -->";
                   2931:         } split(/\s+/,$customshow);
                   2932:         @customfields=split(/\s+/,$customshow);
                   2933:         if ($customshow) {
                   2934:             $extrashow="<ul><li>".join("</li><li>",@fields)."</li></ul>\n";
                   2935:         }
                   2936:     }
                   2937:     my $customdata='';
                   2938:     my %customhash;
                   2939:     foreach my $result (@results) {
                   2940:         if ($result=~/^(custom\=.*)$/) { # grab all custom metadata
                   2941:             my $tmp=$result;
                   2942:             $tmp=~s/^custom\=//;
                   2943:             my ($k,$v)=map {&Apache::lonnet::unescape($_);
                   2944:                         } split(/\,/,$tmp);
                   2945:             $customhash{$k}=$v;
                   2946:         }
                   2947:     }
                   2948:     return ($extrashow,\@customfields,\%customhash);
1.41      harris41 2949: }
                   2950: 
1.122     matthew  2951: ######################################################################
                   2952: ######################################################################
                   2953: 
1.125     matthew  2954: =pod
                   2955: 
1.204     matthew  2956: =item &search_results_header()
1.125     matthew  2957: 
1.130     matthew  2958: Output the proper html headers and javascript code to deal with different 
                   2959: calling modes.
                   2960: 
1.243     albertel 2961: Takes most inputs directly from %env, except $mode.  
1.130     matthew  2962: 
                   2963: =over 4
                   2964: 
                   2965: =item $mode is either (at this writing) 'Basic' or 'Advanced'
                   2966: 
                   2967: =back
1.126     matthew  2968: 
1.130     matthew  2969: The following environment variables are checked:
1.126     matthew  2970: 
                   2971: =over 4
                   2972: 
                   2973: =item 'form.catalogmode' 
                   2974: 
                   2975: Checked for 'interactive' and 'groupsearch'.
                   2976: 
                   2977: =item 'form.mode'
                   2978: 
                   2979: Checked for existance & 'edit' mode.
                   2980: 
                   2981: =item 'form.form'
                   2982: 
1.191     albertel 2983: Contains the name of the form that has the input fields to set
                   2984: 
1.126     matthew  2985: =item 'form.element'
                   2986: 
1.191     albertel 2987: the name of the input field to put the URL into
                   2988: 
                   2989: =item 'form.titleelement'
                   2990: 
                   2991: the name of the input field to put the title into
                   2992: 
1.126     matthew  2993: =back
                   2994: 
1.125     matthew  2995: =cut
                   2996: 
                   2997: ######################################################################
                   2998: ######################################################################
                   2999: sub search_results_header {
1.150     matthew  3000:     my ($importbutton,$closebutton) = @_;
1.256   ! albertel 3001:     my $result = 
        !          3002: 	&Apache::lonxml::xmlbegin().
        !          3003: 	&Apache::loncommon::headtag();
        !          3004: 
1.125     matthew  3005:     # output beginning of search page
                   3006:     # conditional output of script functions dependent on the mode in
                   3007:     # which the search was invoked
1.243     albertel 3008:     if ($env{'form.catalogmode'} eq 'interactive'){
                   3009: 	if (! exists($env{'form.mode'}) || $env{'form.mode'} ne 'edit') {
1.125     matthew  3010:             $result.=<<SCRIPT;
                   3011: <script type="text/javascript">
                   3012:     function select_data(title,url) {
                   3013: 	changeTitle(title);
                   3014: 	changeURL(url);
1.150     matthew  3015: 	parent.close();
1.125     matthew  3016:     }
                   3017:     function changeTitle(val) {
1.153     matthew  3018: 	if (parent.opener.inf.document.forms.resinfo.elements.t) {
                   3019: 	    parent.opener.inf.document.forms.resinfo.elements.t.value=val;
1.125     matthew  3020: 	}
                   3021:     }
                   3022:     function changeURL(val) {
1.153     matthew  3023: 	if (parent.opener.inf.document.forms.resinfo.elements.u) {
                   3024: 	    parent.opener.inf.document.forms.resinfo.elements.u.value=val;
1.125     matthew  3025: 	}
                   3026:     }
                   3027: </script>
                   3028: SCRIPT
1.243     albertel 3029:         } elsif ($env{'form.mode'} eq 'edit') {
                   3030:             my $form = $env{'form.form'};
                   3031:             my $element = $env{'form.element'};
                   3032:             my $titleelement = $env{'form.titleelement'};
1.191     albertel 3033: 	    my $changetitle;
                   3034: 	    if (!$titleelement) {
                   3035: 		$changetitle='function changeTitle(val) {}';
                   3036: 	    } else {
                   3037: 		    $changetitle=<<END;
                   3038: function changeTitle(val) {
                   3039:     if (parent.targetwin.document) {
                   3040:         parent.targetwin.document.forms["$form"].elements["$titleelement"].value=val;
                   3041:     } else {
                   3042: 	var url = 'forms[\"$form\"].elements[\"$titleelement\"].value';
                   3043:         alert("Unable to transfer data to "+url);
                   3044:     }
                   3045: }
                   3046: END
                   3047:             }
                   3048: 
1.125     matthew  3049:             $result.=<<SCRIPT;
                   3050: <script type="text/javascript">
                   3051: function select_data(title,url) {
                   3052:     changeURL(url);
1.191     albertel 3053:     changeTitle(title);
1.150     matthew  3054:     parent.close();
1.125     matthew  3055: }
1.191     albertel 3056: $changetitle
1.125     matthew  3057: function changeURL(val) {
1.150     matthew  3058:     if (parent.targetwin.document) {
                   3059:         parent.targetwin.document.forms["$form"].elements["$element"].value=val;
1.125     matthew  3060:     } else {
                   3061: 	var url = 'forms[\"$form\"].elements[\"$element\"].value';
                   3062:         alert("Unable to transfer data to "+url);
                   3063:     }
                   3064: }
                   3065: </script>
                   3066: SCRIPT
                   3067:         }
                   3068:     }
1.243     albertel 3069:     $result.=<<SCRIPT if $env{'form.catalogmode'} eq 'groupsearch';
1.125     matthew  3070: <script type="text/javascript">
1.158     matthew  3071:     function queue(checkbox_num,val) {
1.185     matthew  3072:         if (document.forms.results.returnvalues.length != "undefined" &&
                   3073:             typeof(document.forms.results.returnvalues.length) == "number") {
                   3074:             if (document.forms.results.returnvalues[checkbox_num].checked) {
                   3075:                 parent.statusframe.document.forms.statusform.elements.Queue.value +='1a'+val+'b';
                   3076:             } else {
                   3077:                 parent.statusframe.document.forms.statusform.elements.Queue.value +='0a'+val+'b';
                   3078:             }
1.150     matthew  3079:         } else {
1.185     matthew  3080:             if (document.forms.results.returnvalues.checked) {
                   3081:                 parent.statusframe.document.forms.statusform.elements.Queue.value +='1a'+val+'b';
                   3082:             } else {
                   3083:                 parent.statusframe.document.forms.statusform.elements.Queue.value +='0a'+val+'b';
                   3084:             }
1.150     matthew  3085:         }
1.125     matthew  3086:     }
                   3087:     function select_group() {
1.150     matthew  3088: 	parent.window.location=
1.243     albertel 3089:     "/adm/groupsort?mode=$env{'form.mode'}&catalogmode=groupsearch&acts="+
1.150     matthew  3090: 	    parent.statusframe.document.forms.statusform.elements.Queue.value;
1.125     matthew  3091:     }
                   3092: </script>
                   3093: SCRIPT
1.256   ! albertel 3094: 
        !          3095:     my $end_head = &Apache::loncommon::endheadtag();
        !          3096:     my $bodytag  = &Apache::loncommon::bodytag(undef,undef,undef,1);
1.130     matthew  3097:     $result.=<<END;
1.256   ! albertel 3098: $end_head
1.155     matthew  3099: $bodytag
1.223     matthew  3100: <form name="results" method="post" action="/adm/searchcat" >
1.150     matthew  3101: <input type="hidden" name="Queue" value="" />
                   3102: $importbutton
1.130     matthew  3103: END
1.125     matthew  3104:     return $result;
                   3105: }
                   3106: 
                   3107: ######################################################################
                   3108: ######################################################################
1.146     matthew  3109: sub search_status_header {
1.256   ! albertel 3110:     my $bodytag = &Apache::loncommon::bodytag(undef,undef,undef,1);
        !          3111:     my $html    = &Apache::lonxml::xmlbegin();
        !          3112:     my $head    = &Apache::loncommon::head('Search Status');
1.146     matthew  3113:     return <<ENDSTATUS;
1.238     albertel 3114: $html
1.256   ! albertel 3115: $head
1.155     matthew  3116: $bodytag
1.146     matthew  3117: <h3>Search Status</h3>
                   3118: Sending search request to LON-CAPA servers.<br />
                   3119: ENDSTATUS
                   3120: }
                   3121: 
1.150     matthew  3122: sub results_link {
1.243     albertel 3123:     my $basic_link   = "/adm/searchcat?"."&table=".$env{'form.table'}.
                   3124:         "&persistent_db_id=".$env{'form.persistent_db_id'};
1.150     matthew  3125:     my $results_link = $basic_link."&phase=results".
1.151     matthew  3126:         "&pause=1"."&start=1";
1.150     matthew  3127:     return $results_link;
                   3128: }
                   3129: 
1.146     matthew  3130: ######################################################################
                   3131: ######################################################################
                   3132: sub print_frames_interface {
                   3133:     my $r = shift;
1.243     albertel 3134:     my $basic_link = "/adm/searchcat?"."&table=".$env{'form.table'}.
                   3135:         "&persistent_db_id=".$env{'form.persistent_db_id'};
1.146     matthew  3136:     my $run_search_link = $basic_link."&phase=run_search";
1.150     matthew  3137:     my $results_link = &results_link();
1.256   ! albertel 3138:     my $html     = &Apache::lonxml::xmlbegin();
        !          3139:     my $head     = &Apache::loncommon::headtag('LON-CAPA Digital Library Search Results');
        !          3140:     my $end_head = &Apache::loncommon::endheadtag();
1.146     matthew  3141:     my $result = <<"ENDFRAMES";
1.238     albertel 3142: $html
1.256   ! albertel 3143: $head
1.150     matthew  3144: <script>
                   3145: var targetwin = opener;
1.158     matthew  3146: var queue = '';
1.150     matthew  3147: </script>
1.256   ! albertel 3148: $end_head
1.176     www      3149: <frameset rows="150,*">
1.146     matthew  3150:     <frame name="statusframe"  src="$run_search_link">
                   3151:     <frame name="resultsframe" src="$results_link">
                   3152: </frameset>
                   3153: </html>
                   3154: ENDFRAMES
                   3155: 
                   3156:     $r->print($result);
                   3157:     return;
                   3158: }
                   3159: 
                   3160: ######################################################################
                   3161: ######################################################################
1.125     matthew  3162: 
1.224     matthew  3163: sub has_stat_data {
                   3164:     my ($values) = @_;
                   3165:     if ( (defined($values->{'count'})      && $values->{'count'}      ne '') ||
                   3166:          (defined($values->{'stdno'})      && $values->{'stdno'}      ne '') ||
                   3167:          (defined($values->{'disc'})       && $values->{'disc'}       ne '') ||
                   3168:          (defined($values->{'avetries'})   && $values->{'avetries'}   ne '') ||
                   3169:          (defined($values->{'difficulty'}) && $values->{'difficulty'} ne '')) {
                   3170:         return 1;
                   3171:     }
                   3172:     return 0;
                   3173: }
                   3174: 
                   3175: sub statfields {
                   3176:     return ('count','stdno','disc','avetries','difficulty');
                   3177: }
                   3178: 
                   3179: sub has_eval_data {
                   3180:     my ($values) = @_;
                   3181:     if ( (defined($values->{'clear'})     && $values->{'clear'}     ne '') ||
                   3182:          (defined($values->{'technical'}) && $values->{'technical'} ne '') ||
                   3183:          (defined($values->{'correct'})   && $values->{'correct'}   ne '') ||
                   3184:          (defined($values->{'helpful'})   && $values->{'helpful'}   ne '') ||
                   3185:          (defined($values->{'depth'})     && $values->{'depth'}     ne '')) {
                   3186:         return 1;
                   3187:     }
                   3188:     return 0;
                   3189: }
                   3190: 
                   3191: sub evalfields { 
                   3192:     return ('clear','technical','correct','helpful','depth');
                   3193: }
                   3194: 
                   3195: ######################################################################
                   3196: ######################################################################
                   3197: 
1.122     matthew  3198: =pod 
                   3199: 
                   3200: =item Metadata Viewing Functions
                   3201: 
                   3202: Output is a HTML-ified string.
1.204     matthew  3203: 
1.122     matthew  3204: Input arguments are title, author, subject, url, keywords, version,
                   3205: notes, short abstract, mime, language, creation date,
1.126     matthew  3206: last revision date, owner, copyright, hostname, and
1.122     matthew  3207: extra custom metadata to show.
                   3208: 
                   3209: =over 4
                   3210: 
                   3211: =item &detailed_citation_view() 
                   3212: 
                   3213: =cut
                   3214: 
                   3215: ######################################################################
                   3216: ######################################################################
1.50      harris41 3217: sub detailed_citation_view {
1.150     matthew  3218:     my ($prefix,%values) = @_;
1.218     matthew  3219:     my $result;
1.247     www      3220:     my $jumpurl=$values{'url'};
                   3221:     $jumpurl=~s/^\/ext\//http\:\/\//;
1.218     matthew  3222:     $result .= '<b>'.$prefix.
1.223     matthew  3223:         '<img src="'.&Apache::loncommon::icon($values{'url'}).' " />'.'&nbsp;'.
1.247     www      3224:         '<a href="'.$jumpurl.'" '.
1.218     matthew  3225:         'target="search_preview">'.$values{'title'}."</a></b>\n";
                   3226:     $result .= "<p>\n";
                   3227:     $result .= '<b>'.$values{'author'}.'</b>,'.
                   3228:         ' <i>'.$values{'owner'}.'</i><br />';
                   3229:     foreach my $field 
                   3230:         (
1.223     matthew  3231:          { name=>'url',
                   3232:            translate => '<b>URL:</b>&nbsp;[_1]',
                   3233:            special => 'url link',},
1.218     matthew  3234:          { name=>'subject',
                   3235:            translate => '<b>Subject:</b>&nbsp;[_1]',},
                   3236:          { name=>'keywords',
                   3237:            translate => '<b>Keywords:</b>&nbsp;[_1]',},
                   3238:          { name=>'notes',
                   3239:            translate => '<b>Notes:</b>&nbsp;[_1]',},
                   3240:          { name=>'mimetag',
                   3241:            translate => '<b>MIME Type:</b>&nbsp;[_1]',},
                   3242:          { name=>'standards',
                   3243:            translate => '<b>Standards:</b>[_1]',},
                   3244:          { name=>'copyrighttag',
                   3245:            translate => '<b>Copyright/Distribution:</b>&nbsp;[_1]',},
1.223     matthew  3246:          { name=>'count',
1.225     matthew  3247:            format => "%d",
1.223     matthew  3248:            translate => '<b>Access Count:</b>&nbsp;[_1]',},
1.218     matthew  3249:          { name=>'stdno',
1.225     matthew  3250:            format => "%d",
1.218     matthew  3251:            translate => '<b>Number of Students:</b>&nbsp;[_1]',},
                   3252:          { name=>'avetries',
1.225     matthew  3253:            format => "%.2f",
1.218     matthew  3254:            translate => '<b>Average Tries:</b>&nbsp;[_1]',},
                   3255:          { name=>'disc',
1.225     matthew  3256:            format => "%.2f",
1.218     matthew  3257:            translate => '<b>Degree of Discrimination:</b>&nbsp;[_1]',},
                   3258:          { name=>'difficulty',
1.225     matthew  3259:            format => "%.2f",
1.218     matthew  3260:            translate => '<b>Degree of Difficulty:</b>&nbsp;[_1]',},
                   3261:          { name=>'clear',
1.225     matthew  3262:            format => "%.2f",
1.218     matthew  3263:            translate => '<b>Clear:</b>&nbsp;[_1]',},
                   3264:          { name=>'depth',
1.225     matthew  3265:            format => "%.2f",
1.218     matthew  3266:            translate => '<b>Depth:</b>&nbsp;[_1]',},
                   3267:          { name=>'helpful',
1.225     matthew  3268:            format => "%.2f",
1.218     matthew  3269:            translate => '<b>Helpful:</b>&nbsp;[_1]',},
                   3270:          { name=>'correct',
1.225     matthew  3271:            format => "%.2f",
1.224     matthew  3272:            translate => '<b>Correct:</b>&nbsp;[_1]',},
1.218     matthew  3273:          { name=>'technical',
1.225     matthew  3274:            format => "%.2f",
1.218     matthew  3275:            translate => '<b>Technical:</b>&nbsp;[_1]',},
1.225     matthew  3276:          { name=>'comefrom_list',
                   3277:            type => 'list',
                   3278:            translate => 'Resources that lead up to this resource in maps',},
                   3279:          { name=>'goto_list',
                   3280:            type => 'list',
                   3281:            translate => 'Resources that follow this resource in maps',},
1.226     matthew  3282:          { name=>'sequsage_list',
1.225     matthew  3283:            type => 'list',
                   3284:            translate => 'Resources using or importing resource',},
1.218     matthew  3285:          ) {
1.225     matthew  3286:         next if (! exists($values{$field->{'name'}}) ||
                   3287:                  $values{$field->{'name'}} eq '');
                   3288:         if (exists($field->{'type'}) && $field->{'type'} eq 'list') {
                   3289:             $result .= '<b>'.&mt($field->{'translate'}).'</b><ul>';
                   3290:             foreach my $item (split(',',$values{$field->{'name'}})){
                   3291:                 $result .= '<li>'.
                   3292:                     '<a target="search_preview" '.
1.247     www      3293:                     'href="'.$jumpurl.'">'.$item.'</a></li>';
1.225     matthew  3294:             }
                   3295:             $result .= '</ul>';
                   3296:         } elsif (exists($field->{'format'}) && $field->{'format'} ne ''){
                   3297:             $result.= &mt($field->{'translate'},
                   3298:                           sprintf($field->{'format'},
1.230     matthew  3299:                                   $values{$field->{'name'}}))."<br />\n";
1.225     matthew  3300:         } else {
1.223     matthew  3301:             if ($field->{'special'} eq 'url link') {
                   3302:                 $result.= 
1.225     matthew  3303:                      &mt($field->{'translate'},
1.247     www      3304:                          '<a href="'.$jumpurl.'" '.
1.225     matthew  3305:                          'target="search_preview">'.
                   3306:                          $values{$field->{'name'}}.
                   3307:                          '</a>');
1.223     matthew  3308:             } else {
                   3309:                 $result.= &mt($field->{'translate'},
                   3310:                               $values{$field->{'name'}});
                   3311:             }
                   3312:             $result .= "<br />\n";
1.225     matthew  3313:         }
1.223     matthew  3314:     }
                   3315:     $result .= "</p>";
                   3316:     if (exists($values{'extrashow'}) && $values{'extrashow'} ne '') {
                   3317:         $result .= '<p>'.$values{'extrashow'}.'</p>';
                   3318:     }
                   3319:     if (exists($values{'shortabstract'}) && $values{'shortabstract'} ne '') {
                   3320:         $result .= '<p>'.$values{'shortabstract'}.'</p>';
1.218     matthew  3321:     }
                   3322:     $result .= '<hr align="left" width="200" noshade />'."\n";
1.50      harris41 3323:     return $result;
1.222     matthew  3324: }
                   3325: 
1.255     www      3326: sub detailed_citation_preview {
                   3327:     my ($prefix,%values)=@_;
                   3328:     return '<table><tr><td>'.
                   3329:            &detailed_citation_view($prefix,%values).
                   3330:            '</td><td>'.
                   3331:            &Apache::lonindexer::showpreview($values{'url'}).
                   3332:            '</td></tr></table><hr />';
                   3333: }
                   3334: 
                   3335: 
1.222     matthew  3336: ######################################################################
                   3337: ######################################################################
                   3338: 
1.122     matthew  3339: =pod 
                   3340: 
                   3341: =item &summary_view() 
                   3342: 
                   3343: =cut
                   3344: ######################################################################
                   3345: ######################################################################
1.50      harris41 3346: sub summary_view {
1.150     matthew  3347:     my ($prefix,%values) = @_;
1.192     albertel 3348:     my $icon=&Apache::loncommon::icon($values{'url'});
1.241     matthew  3349:     my $result=qq{$prefix<img src="$icon" />};
1.244     albertel 3350:     if (exists($env{'form.sortfield'}) && 
                   3351:         $env{'form.sortfield'} !~ /^(default|
1.241     matthew  3352:                                      author|
                   3353:                                      url|
                   3354:                                      title|
                   3355:                                      owner|
                   3356:                                      lastrevisiondate|
                   3357:                                      copyright)$/x) {
1.244     albertel 3358:         my $tmp = $values{$env{'form.sortfield'}};
1.241     matthew  3359:         if (! defined($tmp)) { $tmp = 'undefined'; }
                   3360:         $result .= '&nbsp;'.$tmp.'&nbsp;';
                   3361:     }
1.247     www      3362:     my $jumpurl=$values{'url'};
                   3363:     $jumpurl=~s/^\/ext\//http\:\/\//;
                   3364: 
1.241     matthew  3365:     $result.=<<END;
1.247     www      3366: <a href="$jumpurl" 
1.241     matthew  3367:    target='search_preview'>$values{'title'}</a><br />
                   3368: $values{'author'}, $values{'owner'} -- $values{'lastrevisiondate'}<br />
1.126     matthew  3369: $values{'copyrighttag'}<br />
                   3370: $values{'extrashow'}
1.50      harris41 3371: </p>
1.150     matthew  3372: <hr align='left' width='200' noshade />
1.50      harris41 3373: END
                   3374:     return $result;
                   3375: }
                   3376: 
1.255     www      3377: sub summary_preview {
                   3378:     my ($prefix,%values)=@_;
                   3379:     return '<table><tr><td>'.
                   3380:            &summary_view($prefix,%values).
                   3381:            '</td><td>'.
                   3382:            &Apache::lonindexer::showpreview($values{'url'}).
                   3383:            '</td></tr></table><hr />';
                   3384: }
                   3385: 
1.122     matthew  3386: ######################################################################
                   3387: ######################################################################
                   3388: 
                   3389: =pod 
                   3390: 
1.150     matthew  3391: =item &compact_view() 
                   3392: 
                   3393: =cut
                   3394: 
                   3395: ######################################################################
                   3396: ######################################################################
                   3397: sub compact_view {
                   3398:     my ($prefix,%values) = @_;
1.247     www      3399:     my $jumpurl=$values{'url'};
                   3400:     $jumpurl=~s/^\/ext\//http\:\/\//;
                   3401: 
1.223     matthew  3402:     my $result = 
1.241     matthew  3403:         $prefix.'<img src="'.&Apache::loncommon::icon($values{'url'}).'">';
1.244     albertel 3404:     if (exists($env{'form.sortfield'}) && 
                   3405:         $env{'form.sortfield'} !~ /^(default|author|url|title)$/) {
                   3406:         my $tmp = $values{$env{'form.sortfield'}};
1.241     matthew  3407:         if (! defined($tmp)) { $tmp = 'undefined'; }
                   3408:         $result .= '&nbsp;'.$tmp.'&nbsp;';
                   3409:     }
1.247     www      3410:     $result.='&nbsp;<a href="'.$jumpurl.'" target="search_preview">'.
1.223     matthew  3411:         $values{'title'}.'</a>'.('&nbsp;'x2).
1.247     www      3412:         '<b>'.$values{'author'}.'</b> ('.$values{'domain'}.')<br />';
1.150     matthew  3413:     return $result;
                   3414: }
                   3415: 
                   3416: 
                   3417: ######################################################################
                   3418: ######################################################################
                   3419: 
                   3420: =pod 
                   3421: 
1.122     matthew  3422: =item &fielded_format_view() 
                   3423: 
                   3424: =cut
                   3425: 
                   3426: ######################################################################
                   3427: ######################################################################
1.50      harris41 3428: sub fielded_format_view {
1.150     matthew  3429:     my ($prefix,%values) = @_;
1.192     albertel 3430:     my $icon=&Apache::loncommon::icon($values{'url'});
1.222     matthew  3431:     my %Translated = &Apache::lonmeta::fieldnames();
1.247     www      3432:     my $jumpurl=$values{'url'};
                   3433:     $jumpurl=~s/^\/ext\//http\:\/\//;
                   3434: 
1.50      harris41 3435:     my $result=<<END;
1.192     albertel 3436: $prefix <img src="$icon" />
1.222     matthew  3437: <dl>
                   3438: <dt>URL:</dt>
1.247     www      3439:     <dd><a href="$jumpurl" 
1.222     matthew  3440:          target='search_preview'>$values{'url'}</a></dd>
1.50      harris41 3441: END
1.239     matthew  3442:     foreach my $field ('title','author','domain','subject','keywords','notes',
1.222     matthew  3443:                        'mimetag','language','creationdate','lastrevisiondate',
                   3444:                        'owner','copyrighttag','hostname','abstract') {
                   3445:         $result .= (' 'x4).'<dt>'.$Translated{$field}.'</dt>'."\n".
                   3446:             (' 'x8).'<dd>'.$values{$field}.'</dd>'."\n";
                   3447:     }
                   3448:     if (&has_stat_data(\%values)) {
                   3449:         foreach my $field (&statfields()) {
                   3450:             $result .= (' 'x4).'<dt>'.$Translated{$field}.'</dt>'."\n".
                   3451:                 (' 'x8).'<dd>'.$values{$field}.'</dd>'."\n";
                   3452:         }
                   3453:     }
                   3454:     if (&has_eval_data(\%values)) {
                   3455:         foreach my $field (&evalfields()) {
                   3456:             $result .= (' 'x4).'<dt>'.$Translated{$field}.'</dt>'."\n".
                   3457:                 (' 'x8).'<dd>'.$values{$field}.'</dd>'."\n";
                   3458:         }
                   3459:     }
                   3460:     $result .= "</dl>\n";
                   3461:     $result .= $values{'extrashow'};
                   3462:     $result .= '<hr align="left" width="200" noshade />'."\n";
1.50      harris41 3463:     return $result;
                   3464: }
                   3465: 
1.122     matthew  3466: ######################################################################
                   3467: ######################################################################
                   3468: 
                   3469: =pod 
                   3470: 
                   3471: =item &xml_sgml_view() 
                   3472: 
                   3473: =back 
                   3474: 
                   3475: =cut
                   3476: 
                   3477: ######################################################################
                   3478: ######################################################################
1.50      harris41 3479: sub xml_sgml_view {
1.150     matthew  3480:     my ($prefix,%values) = @_;
1.222     matthew  3481:     my $xml = '<LonCapaResource>'."\n";
                   3482:     # The usual suspects
1.239     matthew  3483:     foreach my $field ('url','title','author','subject','keywords','notes','domain') {
1.222     matthew  3484:         $xml .= qq{<$field>$values{$field}</$field>}."\n";
                   3485:     }
                   3486:     #
                   3487:     $xml .= "<mimeInfo>\n";
                   3488:     foreach my $field ('mime','mimetag') {
                   3489:         $xml .= qq{<$field>$values{$field}</$field>}."\n";
                   3490:     }
                   3491:     $xml .= "</mimeInfo>\n";
                   3492:     #
                   3493:     $xml .= "<languageInfo>\n";
                   3494:     foreach my $field ('language','languagetag') {
                   3495:         $xml .= qq{<$field>$values{$field}</$field>}."\n";
                   3496:     }
                   3497:     $xml .= "</languageInfo>\n";
                   3498:     #
                   3499:     foreach my $field ('creationdate','lastrevisiondate','owner') {
                   3500:         $xml .= qq{<$field>$values{$field}</$field>}."\n";
                   3501:     }
                   3502:     #
                   3503:     $xml .= "<copyrightInfo>\n";
                   3504:     foreach my $field ('copyright','copyrighttag') {
                   3505:         $xml .= qq{<$field>$values{$field}</$field>}."\n";
                   3506:     }
                   3507:     $xml .= "</copyrightInfo>\n";
                   3508:     $xml .= qq{<repositoryLocation>$values{'hostname'}</repositoryLocation>}.
                   3509:         "\n";
                   3510:     $xml .= qq{<shortabstract>$values{'shortabstract'}</shortabstract>}."\n";
                   3511:     #
                   3512:     if (&has_stat_data(\%values)){
                   3513:         $xml .= "<problemstatistics>\n";
                   3514:         foreach my $field (&statfields()) {
                   3515:             $xml .= qq{<$field>$values{$field}</$field>}."\n";            
                   3516:         }
                   3517:         $xml .= "</problemstatistics>\n";
                   3518:     }
                   3519:     #
                   3520:     if (&has_eval_data(\%values)) {
                   3521:         $xml .= "<evaluation>\n";
                   3522:         foreach my $field (&evalfields) {
                   3523:             $xml .= qq{<$field>$values{$field}</$field>}."\n";            
                   3524:         }
                   3525:         $xml .= "</evaluation>\n";
                   3526:     }    
                   3527:     #
                   3528:     $xml .= "</LonCapaResource>\n";
1.212     matthew  3529:     $xml = &HTML::Entities::encode($xml,'<>&');
1.50      harris41 3530:     my $result=<<END;
1.150     matthew  3531: $prefix
1.56      harris41 3532: <pre>
1.212     matthew  3533: $xml
1.56      harris41 3534: </pre>
1.126     matthew  3535: $values{'extrashow'}
1.150     matthew  3536: <hr align='left' width='200' noshade />
1.50      harris41 3537: END
                   3538:     return $result;
1.60      harris41 3539: }
                   3540: 
1.122     matthew  3541: ######################################################################
                   3542: ######################################################################
                   3543: 
                   3544: =pod 
                   3545: 
                   3546: =item &filled() see if field is filled.
                   3547: 
                   3548: =cut
                   3549: 
                   3550: ######################################################################
                   3551: ######################################################################
1.98      harris41 3552: sub filled {
                   3553:     my ($field)=@_;
                   3554:     if ($field=~/\S/ && $field ne 'any') {
1.204     matthew  3555:         return 1;
                   3556:     } else {
                   3557:         return 0;
1.61      harris41 3558:     }
1.60      harris41 3559: }
                   3560: 
1.122     matthew  3561: ######################################################################
                   3562: ######################################################################
                   3563: 
                   3564: =pod 
                   3565: 
1.228     matthew  3566: =item &output_unparsed_phrase_error()
                   3567: 
                   3568: =cut
                   3569: 
                   3570: ######################################################################
                   3571: ######################################################################
                   3572: sub output_unparsed_phrase_error {
                   3573:     my ($r,$closebutton,$parms,$hidden_fields,$field)=@_;
                   3574:     my $errorstring;
                   3575:     if ($field eq 'basicexp') {
1.243     albertel 3576:         $errorstring = &mt('Unable to understand the search phrase <i>[_1]</i>.  Please modify your search.',$env{'form.basicexp'});
1.228     matthew  3577:     } else {
1.243     albertel 3578:         $errorstring = &mt('Unable to understand the search phrase <b>[_1]</b>:<i>[_2]</i>.',$field,$env{'form.'.$field});
1.228     matthew  3579:     }
                   3580:     my $heading = &mt('Unparsed Field');
                   3581:     my $revise  = &mt('Revise search request');
                   3582:     # make query information persistent to allow for subsequent revision
1.256   ! albertel 3583:     my $start_page = &Apache::loncommon::start_page('Search');
        !          3584:     my $end_page   = &Apache::loncommon::end_page();
1.228     matthew  3585:     $r->print(<<ENDPAGE);
1.256   ! albertel 3586: $start_page
1.228     matthew  3587: <form method="post" action="/adm/searchcat">
                   3588: $hidden_fields
                   3589: $closebutton
                   3590: <hr />
                   3591: <h2>$heading</h2>
                   3592: <p>
                   3593: $errorstring
                   3594: </p>
                   3595: <p>
1.243     albertel 3596: <a href="/adm/searchcat?$parms&persistent_db_id=$env{'form.persistent_db_id'}">$revise</a>
1.228     matthew  3597: </p>
1.256   ! albertel 3598: $end_page
1.228     matthew  3599: ENDPAGE
                   3600: }
                   3601: 
                   3602: ######################################################################
                   3603: ######################################################################
                   3604: 
                   3605: =pod 
                   3606: 
1.122     matthew  3607: =item &output_blank_field_error()
                   3608: 
1.151     matthew  3609: Output a complete page that indicates the user has not filled in enough
                   3610: information to do a search.
                   3611: 
                   3612: Inputs: $r (Apache request handle), $closebutton, $parms.
                   3613: 
                   3614: Returns: nothing
                   3615: 
                   3616: $parms is extra information to include in the 'Revise search request' link.
                   3617: 
1.122     matthew  3618: =cut
                   3619: 
                   3620: ######################################################################
                   3621: ######################################################################
1.98      harris41 3622: sub output_blank_field_error {
1.196     matthew  3623:     my ($r,$closebutton,$parms,$hidden_fields)=@_;
1.228     matthew  3624:     my $bodytag=&Apache::loncommon::bodytag('Search');
                   3625:     my $errormsg = &mt('You did not fill in enough information for the search to be started.  You need to fill in relevant fields on the search page in order for a query to be processed.');
                   3626:     my $revise = &mt('Revise Search Request');
                   3627:     my $heading = &mt('Unactionable Search Queary');
1.256   ! albertel 3628:     my $start_page = &Apache::loncommon::start_page('Search');
        !          3629:     my $end_page   = &Apache::loncommon::end_page();
1.228     matthew  3630:     $r->print(<<ENDPAGE);
1.256   ! albertel 3631: $start_page
1.98      harris41 3632: <form method="post" action="/adm/searchcat">
1.145     matthew  3633: $hidden_fields
1.98      harris41 3634: $closebutton
                   3635: <hr />
1.228     matthew  3636: <h2>$heading</h2>
1.98      harris41 3637: <p>
1.228     matthew  3638: $errormsg
                   3639: </p>
                   3640: <p>
1.243     albertel 3641: <a href="/adm/searchcat?$parms&persistent_db_id=$env{'form.persistent_db_id'}">$revise</a>&nbsp;
1.98      harris41 3642: </p>
1.256   ! albertel 3643: $end_page
1.228     matthew  3644: ENDPAGE
                   3645:     return;
1.98      harris41 3646: }
                   3647: 
1.122     matthew  3648: ######################################################################
                   3649: ######################################################################
                   3650: 
                   3651: =pod 
                   3652: 
                   3653: =item &output_date_error()
                   3654: 
                   3655: Output a full html page with an error message.
                   3656: 
1.145     matthew  3657: Inputs: 
                   3658: 
                   3659:     $r, the request pointer.
                   3660:     $message, the error message for the user.
                   3661:     $closebutton, the specialized close button needed for groupsearch.
                   3662: 
1.122     matthew  3663: =cut
                   3664: 
                   3665: ######################################################################
                   3666: ######################################################################
1.60      harris41 3667: sub output_date_error {
1.196     matthew  3668:     my ($r,$message,$closebutton,$hidden_fields)=@_;
1.60      harris41 3669:     # make query information persistent to allow for subsequent revision
1.256   ! albertel 3670:     my $start_page = &Apache::loncommon::start_page('Search');
        !          3671:     my $end_page   = &Apache::loncommon::end_page();
1.122     matthew  3672:     $r->print(<<RESULTS);
1.256   ! albertel 3673: $start_page
1.60      harris41 3674: <form method="post" action="/adm/searchcat">
1.145     matthew  3675: $hidden_fields
1.60      harris41 3676: <input type='button' value='Revise search request'
1.98      harris41 3677: onClick='this.form.submit();' />
1.60      harris41 3678: $closebutton
1.98      harris41 3679: <hr />
1.151     matthew  3680: <h3>Error</h3>
1.60      harris41 3681: <p>
                   3682: $message
                   3683: </p>
1.256   ! albertel 3684: $end_page
1.60      harris41 3685: RESULTS
1.101     harris41 3686: }
                   3687: 
1.122     matthew  3688: ######################################################################
                   3689: ######################################################################
                   3690: 
                   3691: =pod 
                   3692: 
                   3693: =item &start_fresh_session()
                   3694: 
1.142     matthew  3695: Cleans the global %groupsearch_db by removing all fields which begin with
1.122     matthew  3696: 'pre_' or 'store'.
                   3697: 
                   3698: =cut
                   3699: 
                   3700: ######################################################################
                   3701: ######################################################################
1.101     harris41 3702: sub start_fresh_session {
1.142     matthew  3703:     delete $groupsearch_db{'mode_catalog'};
                   3704:     foreach (keys %groupsearch_db) {
1.101     harris41 3705:         if ($_ =~ /^pre_/) {
1.142     matthew  3706:             delete $groupsearch_db{$_};
1.101     harris41 3707:         }
                   3708:         if ($_ =~ /^store/) {
1.142     matthew  3709: 	    delete $groupsearch_db{$_};
1.101     harris41 3710: 	}
1.109     harris41 3711:     }
1.3       harris41 3712: }
1.1       www      3713: 
                   3714: 1;
1.162     www      3715: 
                   3716: sub cleanup {
1.163     www      3717:     if (tied(%groupsearch_db)) {
                   3718:         unless (untie(%groupsearch_db)) {
                   3719: 	  &Apache::lonnet::logthis('Failed cleanup searchcat: groupsearch_db');
                   3720:         }
                   3721:     }
1.167     www      3722:     &untiehash();
1.162     www      3723:     &Apache::lonmysql::disconnect_from_db();
1.252     albertel 3724:     return OK;
1.162     www      3725: }
1.98      harris41 3726: 
1.1       www      3727: __END__
1.105     harris41 3728: 
1.121     matthew  3729: =pod
1.105     harris41 3730: 
1.121     matthew  3731: =back 
1.105     harris41 3732: 
                   3733: =cut

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