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