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