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