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