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