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