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