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