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