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