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

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

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