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