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