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