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