Diff for /loncom/interface/lonsearchcat.pm between versions 1.224 and 1.230.2.1

version 1.224, 2004/05/07 18:50:14 version 1.230.2.1, 2005/01/19 20:22:36
Line 75  use Apache::lonhtmlcommon; Line 75  use Apache::lonhtmlcommon;
 use Apache::lonlocal;  use Apache::lonlocal;
 use LONCAPA::lonmetadata();  use LONCAPA::lonmetadata();
 use HTML::Entities();  use HTML::Entities();
   use Parse::RecDescent;
   
 ######################################################################  ######################################################################
 ######################################################################  ######################################################################
Line 174  sub handler { Line 175  sub handler {
                    '&launch='.$ENV{'form.launch'}.                     '&launch='.$ENV{'form.launch'}.
                    '&mode='.$ENV{'form.mode'},                     '&mode='.$ENV{'form.mode'},
               text=>"Course and Catalog Search",                text=>"Course and Catalog Search",
                 target=>'_top',
               bug=>'Searching',});                bug=>'Searching',});
     } else {      } else {
         &Apache::lonhtmlcommon::add_breadcrumb          &Apache::lonhtmlcommon::add_breadcrumb
Line 182  sub handler { Line 184  sub handler {
                    '&launch='.$ENV{'form.launch'}.                     '&launch='.$ENV{'form.launch'}.
                    '&mode='.$ENV{'form.mode'},                     '&mode='.$ENV{'form.mode'},
               text=>"Catalog Search",                text=>"Catalog Search",
                 target=>'_top',
               bug=>'Searching',});                bug=>'Searching',});
     }      }
     #      #
Line 335  END Line 338  END
         &course_search($r);          &course_search($r);
     } elsif(($ENV{'form.phase'} eq 'basic_search') ||      } elsif(($ENV{'form.phase'} eq 'basic_search') ||
             ($ENV{'form.phase'} eq 'adv_search')) {              ($ENV{'form.phase'} eq 'adv_search')) {
           #
           # We are running a search, try to parse it
           my ($query,$customquery,$customshow,$libraries) = 
               (undef,undef,undef,undef);
           my $pretty_string;
           if ($ENV{'form.phase'} eq 'basic_search') {
               ($query,$pretty_string,$libraries) = 
                   &parse_basic_search($r,$closebutton,$hidden_fields);
               return OK if (! defined($query));
               &make_persistent({ basicexp => $ENV{'form.basicexp'}},
                                $persistent_db_file);
           } else {                      # Advanced search
               ($query,$customquery,$customshow,$libraries,$pretty_string) 
                   = &parse_advanced_search($r,$closebutton,$hidden_fields);
               return OK if (! defined($query));
           }
           &make_persistent({ query => $query,
                              customquery => $customquery,
                              customshow => $customshow,
                              libraries => $libraries,
                              pretty_string => $pretty_string },
                            $persistent_db_file);
           #
         # Set up table          # Set up table
         if (! defined(&create_results_table())) {          if (! defined(&create_results_table())) {
     my $errorstring=&Apache::lonmysql::get_error();      my $errorstring=&Apache::lonmysql::get_error();
Line 362  Unable to properly store search informat Line 388  Unable to properly store search informat
 END  END
             return OK;              return OK;
         }          }
         #  
         # We are running a search  
         my ($query,$customquery,$customshow,$libraries) =   
             (undef,undef,undef,undef);  
         my $pretty_string;  
         if ($ENV{'form.phase'} eq 'basic_search') {  
             ($query,$pretty_string,$libraries) =   
                 &parse_basic_search($r,$closebutton,$hidden_fields);  
         } else {                      # Advanced search  
             ($query,$customquery,$customshow,$libraries,$pretty_string)   
                 = &parse_advanced_search($r,$closebutton,$hidden_fields);  
             return OK if (! defined($query));  
         }  
         &make_persistent({ query => $query,  
                            customquery => $customquery,  
                            customshow => $customshow,  
                            libraries => $libraries,  
                            pretty_string => $pretty_string },  
                          $persistent_db_file);  
         ##          ##
         ## Print out the frames interface          ## Print out the frames interface
         ##          ##
         &print_frames_interface($r);          if (defined($query)) {
               &print_frames_interface($r);
           }
     }      }
     return OK;      return OK;
 }   } 
Line 435  sub hidden_field { Line 444  sub hidden_field {
 {   # Scope the course search to avoid global variables  {   # Scope the course search to avoid global variables
 #  #
 # Variables For course search  # Variables For course search
 my %alreadyseen;  
 my %hash;  my %hash;
 my $totalfound;  my $totalfound;
   
   sub make_symb {
       my ($id)=@_;
       my ($mapid,$resid)=split(/\./,$id);
       my $map=$hash{'map_id_'.$mapid};
       my $res=$hash{'src_'.$id};
       my $symb=&Apache::lonnet::encode_symb($map,$resid,$res);
       return $symb;
   }
   
 sub course_search {  sub course_search {
     my $r=shift;      my $r=shift;
     my $bodytag=&Apache::loncommon::bodytag('Course Search');      my $bodytag=&Apache::loncommon::bodytag('Course Search');
Line 460  sub course_search { Line 477  sub course_search {
       $bodytag.'<hr /><center><font size="+2" face="arial">'.$pretty_search_string.'</font></center><hr />');        $bodytag.'<hr /><center><font size="+2" face="arial">'.$pretty_search_string.'</font></center><hr />');
     $r->rflush();      $r->rflush();
 # ======================================================= Go through the course  # ======================================================= Go through the course
     undef %alreadyseen;  
     %alreadyseen=();  
     my $c=$r->connection;      my $c=$r->connection;
     if (tie(%hash,'GDBM_File',$ENV{'request.course.fn'}.".db",      if (tie(%hash,'GDBM_File',$ENV{'request.course.fn'}.".db",
             &GDBM_READER(),0640)) {              &GDBM_READER(),0640)) {
         foreach (keys %hash) {          foreach (sort(keys(%hash))) {
             if ($c->aborted()) { last; }              if ($c->aborted()) { last; }
             if (($_=~/^src\_(.+)$/) && (!$alreadyseen{$hash{$_}})) {              if (($_=~/^src\_(.+)$/)) {
                 &checkonthis($r,$hash{$_},0,$hash{'title_'.$1},$fulltext,   if ($hash{'randomout_'.$1} & !$ENV{'request.role.adv'}) {
                              @allwords);      next; 
    }
    my $symb=&make_symb($1);
                   &checkonthis($r,$1,$hash{$_},0,&Apache::lonnet::gettitle($symb),
        $fulltext,$symb,@allwords);
             }              }
         }          }
         untie(%hash);          untie(%hash);
Line 484  sub course_search { Line 503  sub course_search {
 # =============================== This pulls up a resource and its dependencies  # =============================== This pulls up a resource and its dependencies
   
 sub checkonthis {  sub checkonthis {
     my ($r,$url,$level,$title,$fulltext,@allwords)=@_;      my ($r,$id,$url,$level,$title,$fulltext,$symb,@allwords)=@_;
     $alreadyseen{$url}=1;  
     $r->rflush();      $r->rflush();
     my $result=&Apache::lonnet::metadata($url,'title').' '.      
                &Apache::lonnet::metadata($url,'subject').' '.      my $result=$title.' ';
                &Apache::lonnet::metadata($url,'abstract').' '.      if ($ENV{'request.role.adv'} || !$hash{'encrypted_'.$id}) {
                &Apache::lonnet::metadata($url,'keywords');   $result.=&Apache::lonnet::metadata($url,'title').' '.
     if (($url) && ($fulltext)) {      &Apache::lonnet::metadata($url,'subject').' '.
  $result.=&Apache::lonnet::ssi_body($url);      &Apache::lonnet::metadata($url,'abstract').' '.
       &Apache::lonnet::metadata($url,'keywords');
       }
       my ($extension)=($url=~/\.(\w+)$/);
       if (&Apache::loncommon::fileembstyle($extension) eq 'ssi' &&
    ($url) && ($fulltext)) {
    $result.=&Apache::lonnet::ssi_body($url.'?symb='.&Apache::lonnet::escape($symb));
     }      }
     $result=~s/\s+/ /gs;      $result=~s/\s+/ /gs;
     my $applies=0;      my $applies=0;
Line 509  sub checkonthis { Line 533  sub checkonthis {
        for (my $i=0;$i<=$level*5;$i++) {         for (my $i=0;$i<=$level*5;$i++) {
            $r->print('&nbsp;');             $r->print('&nbsp;');
        }         }
        $r->print('<a href="'.$url.'" target="cat">'.         my $href=$url;
  ($title?$title:$url).'</a><br />');         if ($hash{'encrypted_'.$id} && !$ENV{'request.role.adv'}) {
      $href=&Apache::lonenc::encrypted($href)
          .'?symb='.&Apache::lonenc::encrypted($symb);
          } else {
      $href.='?symb='.&Apache::lonnet::escape($symb);
          }
          $r->print('<a href="'.$href.'" target="cat">'.($title?$title:$url).
    '</a><br />');
        $totalfound++;         $totalfound++;
     } elsif ($fulltext) {      } elsif ($fulltext) {
        $r->print(' .');         $r->print(' .');
Line 520  sub checkonthis { Line 551  sub checkonthis {
     my $dependencies=      my $dependencies=
                 &Apache::lonnet::metadata($url,'dependencies');                  &Apache::lonnet::metadata($url,'dependencies');
     foreach (split(/\,/,$dependencies)) {      foreach (split(/\,/,$dependencies)) {
        if (($_=~/^\/res\//) && (!$alreadyseen{$_})) {         if (($_=~/^\/res\//)) {
           &checkonthis($r,$_,$level+1,'',$fulltext,@allwords);            &checkonthis($r,$id,$_,$level+1,'',$fulltext,undef,@allwords);
        }         }
     }      }
 }  }
Line 559  Prints the form for the basic search.  S Line 590  Prints the form for the basic search.  S
 ######################################################################  ######################################################################
 sub print_basic_search_form {  sub print_basic_search_form {
     my ($r,$closebutton,$hidden_fields) = @_;      my ($r,$closebutton,$hidden_fields) = @_;
       my $result = ($ENV{'form.catalogmode'} ne 'groupsearch');
     my $bodytag=&Apache::loncommon::bodytag('Search').      my $bodytag=&Apache::loncommon::bodytag('Search').
         &Apache::lonhtmlcommon::breadcrumbs(undef,'Searching','Searching',          &Apache::lonhtmlcommon::breadcrumbs(undef,'Searching','Search_Basic',
                                             undef,undef,! $ENV{'form.launch'});                                     undef,undef,
                                      $ENV{'form.catalogmode'} ne 'groupsearch');
     my $scrout = &search_html_header().$bodytag;      my $scrout = &search_html_header().$bodytag;
     if (&Apache::lonnet::allowed('bre',$ENV{'request.role.domain'})) {      if (&Apache::lonnet::allowed('bre',$ENV{'request.role.domain'})) {
         # Define interface components          # Define interface components
Line 599  sub print_basic_search_form { Line 632  sub print_basic_search_form {
         }          }
         $scrout.='<table>'.          $scrout.='<table>'.
             '<tr><td align="center" valign="top">'.              '<tr><td align="center" valign="top">'.
             &Apache::lonhtmlcommon::textbox('basicexp',              &Apache::lonhtmlcommon::textbox
                                             $ENV{'form.basicexp'},50).'<br />'.              ('basicexp',
                &HTML::Entities::encode($ENV{'form.basicexp'},'<>&"'),50
                ).
                '<br />'.
             '<font size="-1">'.&searchhelp().'</font>'.'</td>'.              '<font size="-1">'.&searchhelp().'</font>'.'</td>'.
             '<td><font size="-1">'.              '<td><font size="-1">'.
             '<nobr>'.('&nbsp;'x3).$adv_search_link.'</nobr>'.'<br />'.              '<nobr>'.('&nbsp;'x3).$adv_search_link.'</nobr>'.'<br />'.
Line 609  sub print_basic_search_form { Line 645  sub print_basic_search_form {
             '</font></td>'.              '</font></td>'.
             '</tr>'.$/;              '</tr>'.$/;
         #          #
 #        $scrout .= '<tr><td align="center">'.  
 #            '<font size="-1">'.  
 #            $userelatedwords.('&nbsp;'x3).  
 #            $onlysearchdomain.('&nbsp;'x2).$adv_search_link.  
 #            '</font>'.  
 #            '</td></tr>'.$/;  
         $scrout .= '<tr><td align="center" colspan="2">'.          $scrout .= '<tr><td align="center" colspan="2">'.
             '<font size="-1">'.              '<font size="-1">'.
             '<input type="submit" name="basicsubmit" '.              '<input type="submit" name="basicsubmit" '.
Line 690  sub print_advanced_search_form{ Line 720  sub print_advanced_search_form{
     my ($r,$closebutton,$hidden_fields) = @_;      my ($r,$closebutton,$hidden_fields) = @_;
     my $bodytag=&Apache::loncommon::bodytag('Advanced Catalog Search').      my $bodytag=&Apache::loncommon::bodytag('Advanced Catalog Search').
         &Apache::lonhtmlcommon::breadcrumbs(undef,'Searching',          &Apache::lonhtmlcommon::breadcrumbs(undef,'Searching',
                                             'Searching',                                              'Search_Advanced',
                                             undef,undef,                                              undef,undef,
                                             ! $ENV{'form.launch'});                                    $ENV{'form.catalogmode'} ne 'groupsearch');
   
     my %lt=&Apache::lonlocal::texthash('srch' => 'Search',      my %lt=&Apache::lonlocal::texthash('srch' => 'Search',
        'reset' => 'Reset',         'reset' => 'Reset',
        'help' => 'Help');         'help' => 'Help');
Line 774  ENDHEADER Line 803  ENDHEADER
     $scrout.='<tr><td align="right" valign="top">'.      $scrout.='<tr><td align="right" valign="top">'.
  &titlefield(&mt('Copyright/Distribution')).'</td><td colspan="2">'.   &titlefield(&mt('Copyright/Distribution')).'</td><td colspan="2">'.
         &Apache::lonmeta::selectbox('copyright',          &Apache::lonmeta::selectbox('copyright',
                                     '',,                                      $ENV{'form.copyright'},
                                     \&Apache::loncommon::copyrightdescription,                                      \&Apache::loncommon::copyrightdescription,
                                     ( undef,                                      ( undef,
                                       &Apache::loncommon::copyrightids)                                        &Apache::loncommon::copyrightids)
Line 782  ENDHEADER Line 811  ENDHEADER
     $scrout.='<tr><td align="right" valign="top">'.      $scrout.='<tr><td align="right" valign="top">'.
  &titlefield(&mt('Language')).'</td><td colspan="2">'.   &titlefield(&mt('Language')).'</td><td colspan="2">'.
         &Apache::lonmeta::selectbox('language',          &Apache::lonmeta::selectbox('language',
                                     'notset',,                                      $ENV{'form.language'},
                                     \&Apache::loncommon::languagedescription,                                      \&Apache::loncommon::languagedescription,
                                     ('any',&Apache::loncommon::languageids)                                      ('any',&Apache::loncommon::languageids)
                                     ).'</td></tr>';                                      ).'</td></tr>';
Line 997  Outputs: return little blurb on how to e Line 1026  Outputs: return little blurb on how to e
 ######################################################################  ######################################################################
 ######################################################################  ######################################################################
 sub searchhelp {  sub searchhelp {
     return &mt('Enter terms or phrases separated by AND, OR, or NOT');      return &mt('Enter words and quoted phrases');
 }  }
   
 ######################################################################  ######################################################################
Line 1188  Parse advanced search form and return th Line 1217  Parse advanced search form and return th
 sub parse_advanced_search {  sub parse_advanced_search {
     my ($r,$closebutton,$hidden_fields)=@_;      my ($r,$closebutton,$hidden_fields)=@_;
     my @BasicFields = ('title','author','subject','keywords','url','version',      my @BasicFields = ('title','author','subject','keywords','url','version',
                        'notes','abstract','extension','owner',                         'notes','abstract','extension','owner','authorspace',
 #                       'custommetadata','customshow',  #                       'custommetadata','customshow',
                        'modifyinguser','standards','mime');                         'modifyinguser','standards','mime');
     my @StatsFields = &statfields();      my @StatsFields = &statfields();
     my @EvalFields = &evalfields();      my @EvalFields = &evalfields();
     my $fillflag=0;      my $fillflag=0;
     my $pretty_search_string = "<br />\n";      my $pretty_search_string = "";
     # Clean up fields for safety      # Clean up fields for safety
     for my $field (@BasicFields,      for my $field (@BasicFields,
                    'creationdatestart_month','creationdatestart_day',                     'creationdatestart_month','creationdatestart_day',
Line 1204  sub parse_advanced_search { Line 1233  sub parse_advanced_search {
    'lastrevisiondatestart_year','lastrevisiondateend_month',     'lastrevisiondatestart_year','lastrevisiondateend_month',
    'lastrevisiondateend_day','lastrevisiondateend_year') {     'lastrevisiondateend_day','lastrevisiondateend_year') {
  $ENV{'form.'.$field}=~s/[^\w\/\s\(\)\=\-\"\']//g;   $ENV{'form.'.$field}=~s/[^\w\/\s\(\)\=\-\"\']//g;
         $ENV{'form.'.$field}=~s/(not\s*$|^\s*(and|or)|)//gi;  
     }      }
     foreach ('mode','form','element') {      foreach ('mode','form','element') {
  # is this required?  Hmmm.   # is this required?  Hmmm.
Line 1249  sub parse_advanced_search { Line 1277  sub parse_advanced_search {
     # Evaluate logical expression AND/OR/NOT phrase fields.      # Evaluate logical expression AND/OR/NOT phrase fields.
     foreach my $field (@BasicFields) {      foreach my $field (@BasicFields) {
  next if (!defined($ENV{'form.'.$field}) || $ENV{'form.'.$field} eq '');   next if (!defined($ENV{'form.'.$field}) || $ENV{'form.'.$field} eq '');
         foreach my $searchphrase(&process_phrase_input($ENV{'form.'.$field})){          my ($error,$SQLQuery) = 
             $pretty_search_string .= $font."$field</font> contains <b>".              &process_phrase_input($ENV{'form.'.$field},
                 $searchphrase."</b>";                                    $ENV{'form.'.$field.'_related'},$field);
           if (defined($error)) {
               &output_unparsed_phrase_error($r,$closebutton,'phase=disp_adv',
                                            $hidden_fields,$field);
               return;
           } else {
               $pretty_search_string .= 
                   $font.$field.'</font>: '.$ENV{'form.'.$field};
             if ($ENV{'form.'.$field.'_related'}) {              if ($ENV{'form.'.$field.'_related'}) {
                 my @New_Words;                  my @Words = 
                 ($searchphrase,@New_Words) = &related_version($searchphrase);                      &Apache::loncommon::get_related_words
                 if (@New_Words) {                      ($ENV{'form.'.$field});
                     $pretty_search_string .= " with related words: ".                  if (@Words) {
                         "<b>@New_Words</b>.";                      $pretty_search_string.= ' with related words: '.
                           join(', ',@Words[0..4]);
                 } else {                  } else {
                     $pretty_search_string .= " with no related words.";                      $pretty_search_string.= ' with related words.';
                 }                  }
             }              }
             $pretty_search_string .= "<br />\n";              $pretty_search_string .= '<br />';
             push @queries,&build_SQL_query($field,$searchphrase);              push (@queries,$SQLQuery);
         }          }
     }      }
     #      #
Line 1280  sub parse_advanced_search { Line 1316  sub parse_advanced_search {
         }          }
     }      }
     if (defined($searchphrase)) {      if (defined($searchphrase)) {
         push @queries,&build_SQL_query('mime',$searchphrase);          my ($error,$SQLsearch) = &process_phrase_input($searchphrase,0,'mime');
           push @queries,$SQLsearch;
         $pretty_search_string .=$font.'mime</font> contains <b>'.          $pretty_search_string .=$font.'mime</font> contains <b>'.
             $searchphrase.'</b><br />';              $searchphrase.'</b><br />';
     }      }
Line 1312  sub parse_advanced_search { Line 1349  sub parse_advanced_search {
  push @queries,"(copyright like \"$ENV{'form.copyright'}\")";   push @queries,"(copyright like \"$ENV{'form.copyright'}\")";
         $pretty_search_string.=$font."copyright</font> = ".          $pretty_search_string.=$font."copyright</font> = ".
             &Apache::loncommon::copyrightdescription($ENV{'form.copyright'}).              &Apache::loncommon::copyrightdescription($ENV{'form.copyright'}).
                 "<br \>\n";                  "<br />\n";
     }      }
     #      #
     # Statistics      # Statistics
Line 1400  sub parse_advanced_search { Line 1437  sub parse_advanced_search {
     $pretty_search_string .= $pretty_domains_string."<br />\n";      $pretty_search_string .= $pretty_domains_string."<br />\n";
     #      #
     if (@queries) {      if (@queries) {
  $query="SELET * FROM metadata WHERE ".join(" AND ",@queries);   $query="SELECT * FROM metadata WHERE (".join(") AND (",@queries).')';
     } elsif ($customquery) {      } elsif ($customquery) {
         $query = '';          $query = '';
     }      }
 #    &Apache::lonnet::logthis('query = '.$/.$query);      # &Apache::lonnet::logthis('query = '.$/.$query);
     return ($query,$customquery,$customshow,$libraries_to_query,      return ($query,$customquery,$customshow,$libraries_to_query,
             $pretty_search_string);              $pretty_search_string);
 }  }
Line 1466  sub parse_basic_search { Line 1503  sub parse_basic_search {
     #      #
     # Clean up fields for safety      # Clean up fields for safety
     for my $field ('basicexp') {      for my $field ('basicexp') {
  $ENV{"form.$field"}=~s/[^\w\s\(\)\-]//g;   $ENV{"form.$field"}=~s/[^\w\s\'\"\!\(\)\-]//g;
     }      }
     foreach ('mode','form','element') {      foreach ('mode','form','element') {
  # is this required?  Hmmm.   # is this required?  Hmmm.
Line 1479  sub parse_basic_search { Line 1516  sub parse_basic_search {
     #      #
     # Check to see if enough of a query is filled in      # Check to see if enough of a query is filled in
     my $search_string = $ENV{'form.basicexp'};      my $search_string = $ENV{'form.basicexp'};
     $search_string =~ s/(not\s*$|^\s*(and|or)|)//gi;  
     if (! &filled($search_string)) {      if (! &filled($search_string)) {
  &output_blank_field_error($r,$closebutton,'phase=disp_basic');   &output_blank_field_error($r,$closebutton,'phase=disp_basic');
  return OK;   return OK;
     }      }
     my $pretty_search_string='';      my $pretty_search_string=$search_string;
     my @Queries;      my @Queries;
     my $concatarg=join(',',      my $searchfield = 'concat_ws(" ",'.join(',',
                        ('title', 'author', 'subject', 'notes', 'abstract',                                              ('title','author','subject',
                         'keywords'));                                               'notes','abstract','keywords')
     foreach my $search (&process_phrase_input($search_string)){                                              ).')';
         $pretty_search_string .= '<br />'.'<b>'.$search.'</b>';      my ($error,$SQLQuery) = &process_phrase_input($search_string,
         if ($ENV{'form.related'}) {                                                      $ENV{'form.related'},
             my @New_Words;                                                      $searchfield);
             ($search,@New_Words) = &related_version($search);      if ($error) {
             next if (! $search);          &output_unparsed_phrase_error($r,$closebutton,'phase=disp_basic',
             if (@New_Words) {                                        '','basicexp');
                 $pretty_search_string .=           return;
                     " with related words: <b>@New_Words</b>";  
             }  
         }  
         #  
         # Build SQL query string based on form page  
         push(@Queries,  
              &build_SQL_query('concat_ws(" ",'.$concatarg.')',$search));  
     }      }
       push(@Queries,$SQLQuery);
       #foreach my $q (@Queries) {
       #    &Apache::lonnet::logthis('    '.$q);
       #}
     my $final_query = 'SELECT * FROM metadata WHERE '.join(" AND ",@Queries);      my $final_query = 'SELECT * FROM metadata WHERE '.join(" AND ",@Queries);
     #      #
     if (defined($pretty_domains_string) && $pretty_domains_string ne '') {      if (defined($pretty_domains_string) && $pretty_domains_string ne '') {
         $pretty_search_string .= ' '.$pretty_domains_string;          $pretty_search_string .= ' '.$pretty_domains_string;
     }      }
     $pretty_search_string .= "<br />\n";      $pretty_search_string .= "<br />\n";
     $pretty_search_string =~ s:^<br />::;      $pretty_search_string =~ s:^<br /> and ::;
 #    &Apache::lonnet::logthis($final_query);      # &Apache::lonnet::logthis($final_query);
     return ($final_query,$pretty_search_string,      return ($final_query,$pretty_search_string,
             $libraries_to_query);              $libraries_to_query);
 }  }
   
   
   ###############################################################
   ###############################################################
   
   my @Phrases;
   
   sub concat {
       my ($item) = @_;
       my $results = '';
       foreach (@$item) {
           if (ref($_) eq 'ARRAY') {
               $results .= join(' ',@$_);
           }
       }
       return $results;
   }
   
 sub process_phrase_input {  sub process_phrase_input {
     my ($phrase)=@_;      my ($phrase,$related,$field)=@_;
     my @Phrases;      #&Apache::lonnet::logthis('phrase = :'.$phrase.':');
     # &Apache::lonnet::logthis('phrase = :'.$phrase.':');      my $grammar = <<'ENDGRAMMAR';
     my $in_quotes = 0;      searchphrase:
     my @Words = split(/\s+/,$phrase);          expression /^\Z/ {
     foreach my $word (@Words) {              # &Apache::lonsearchcat::print_item(\@item,0);
         $word =~ s/(\w+)\"(\w+)/$1$2/g;              [@item];
         if ($in_quotes) {          }
             if ($word =~ s/(\")$//) {      expression:
                 $in_quotes = 0;          phrase(s)   {
               [@item];
           }
       phrase:
           orword {
               [@item];
           }
         | andword {
               [@item];
           }
         | minusword {
               unshift(@::Phrases,$item[1]->[0]);
               unshift(@::Phrases,$item[1]->[1]);
               [@item];
           }
         | word {
               unshift(@::Phrases,$item[1]);
               [@item];
           } 
       #
       orword:
           word 'OR' phrase {
               unshift(@::Phrases,'OR');
               unshift(@::Phrases,$item[1]);
               [@item];
           }
           | word 'or' phrase {
               unshift(@::Phrases,'OR');
               unshift(@::Phrases,$item[1]);
               [@item];
           }    
           | minusword 'OR' phrase {
               unshift(@::Phrases,'OR');
               unshift(@::Phrases,$item[1]->[0]);
               unshift(@::Phrases,$item[1]->[1]);
               [@item];
           }
           | minusword 'or' phrase {
               unshift(@::Phrases,'OR');
               unshift(@::Phrases,$item[1]->[0]);
               unshift(@::Phrases,$item[1]->[1]);
               [@item];
           }    
       andword:
           word phrase {
               unshift(@::Phrases,'AND');
               unshift(@::Phrases,$item[1]);
               [@item];
           }
           | minusword phrase {
               unshift(@::Phrases,'AND');
               unshift(@::Phrases,$item[1]->[0]);
               unshift(@::Phrases,$item[1]->[1]);
               [@item];
           }
       #
       minusword:
           '-' word {
               [$item[2],'NOT'];
           }
       word:
           "'" term(s) "'" {
             &Apache::lonsearchcat::concat(\@item);
           }
         | '"' term(s) '"' {
             &Apache::lonsearchcat::concat(\@item);
           }
         | term {
               $item[1];
           }
       term:
           /[\w\Q:!@#$%^&*()+_=|{}<>,.;\\\/?\E]+/ {
               $item[1];
           }
   ENDGRAMMAR
       #
       # The end result of parsing the phrase with the grammar is an array
       # @::Phrases.
       # $phrase = "gene splicing" or cat -> "gene splicing","OR","cat"
       # $phrase = "genetic engineering" -dna ->
       #                      "genetic engineering","AND","NOT","dna"
       # $phrase = cat or dog -poodle -> "cat","OR","dog","AND","NOT","poodle"
       undef(@::Phrases);
       my $p = new Parse::RecDescent($grammar);
       if (! defined($p->searchphrase($phrase))) {
           &Apache::lonnet::logthis('lonsearchcat:unable to process:'.$phrase);
           return 'Unable to process phrase '.$phrase;
       }
       #
       # Go through the phrases and make sense of them.  
       # Apply modifiers NOT OR and AND to the phrases.
       my @NewPhrases;
       while(@::Phrases) {
           my $phrase = shift(@::Phrases);
           # &Apache::lonnet::logthis('phrase = '.$phrase);
           my $phrasedata;
           if ($phrase =~ /^(NOT|OR|AND)$/) {
               if ($phrase eq 'OR') {
                   $phrasedata->{'or'}++;
                   if (! @::Phrases) { $phrasedata = undef; last; }
                   $phrase = shift(@::Phrases);
               } elsif ($phrase eq 'AND') {
                   $phrasedata->{'and'}++;
                   if (! @::Phrases) { $phrasedata = undef; last; }
                   $phrase = shift(@::Phrases);
             }              }
             if ($Phrases[-1] ne '') {              if ($phrase eq 'NOT') {
                 $Phrases[-1] .= ' ';                  $phrasedata->{'negate'}++;
                   if (! @::Phrases) { $phrasedata = undef; last; }
                   $phrase = shift(@::Phrases);
             }              }
             $Phrases[-1] .= $word;          }
           $phrasedata->{'phrase'} = $phrase;
           if ($related) {
               my @NewWords;
               (undef,@NewWords) = &related_version($phrasedata->{'phrase'});
               $phrasedata->{'related_words'} = \@NewWords;
           }
           push(@NewPhrases,$phrasedata);
       }
       #
       # Actually build the sql query from the phrases
       my $SQLQuery;
       foreach my $phrase (@NewPhrases) {
           my $query;
           if ($phrase->{'negate'}) {
               $query .= $field.' NOT LIKE "%'.$phrase->{'phrase'}.'%"';
         } else {          } else {
             if ($word =~ s/^(\")//) {              $query .= $field.' LIKE "%'.$phrase->{'phrase'}.'%"';
                 $in_quotes=1;          }
           foreach my $related (@{$phrase->{'related_words'}}) {
               if ($phrase->{'negate'}) {
                   $query .= ' AND '.$field.' NOT LIKE "%'.$related.'%"';
               } else {
                   $query .= ' OR '.$field.' LIKE "%'.$related.'%"';
             }              }
             push(@Phrases,$word);          }
           if ($SQLQuery) {
               if ($phrase->{'or'}) {
                   $SQLQuery .= ' OR ('.$query.')';
               } else {
                   $SQLQuery .= ' AND ('.$query.')';
               }
           } else {
               $SQLQuery = '('.$query.')';
         }          }
     }      }
     #      #
     #foreach my $p (@Phrases) {      # &Apache::lonnet::logthis("SQLQuery = $SQLQuery");
     #    &Apache::lonnet::logthis('    subphrase = '.$p);  
     #}  
     #      #
     return @Phrases;      return undef,$SQLQuery;
 }  }
   
 ######################################################################  ######################################################################
Line 1575  sub related_version { Line 1757  sub related_version {
     return $result,sort(@Words);      return $result,sort(@Words);
 }  }
   
 ######################################################################  
 ######################################################################  
   
 =pod   
   
 =item &build_SQL_query()   
   
 Builds a SQL query string from a logical expression with AND/OR keywords  
 using Text::Query and &recursive_SQL_query_builder()  
   
 =cut  
   
 ######################################################################  
 ######################################################################  
 sub build_SQL_query {  
     my ($field_name,$logic_statement)=@_;  
     my $q=new Text::Query('abc',  
   -parse => 'Text::Query::ParseAdvanced',  
   -build => 'Text::Query::Build');  
     $q->prepare($logic_statement);  
     my $matchexp=${$q}{'matchexp'}; chomp $matchexp;  
     &Apache::lonnet::logthis('matchexp = '.$matchexp);  
     my $sql_query=&recursive_SQL_query_build($field_name,$matchexp);  
     &Apache::lonnet::logthis('sql_query = '.$sql_query);  
     return $sql_query;  
 }  
   
 ######################################################################  ######################################################################
 ######################################################################  ######################################################################
Line 1635  sub build_custommetadata_query { Line 1791  sub build_custommetadata_query {
     return $matchexp;      return $matchexp;
 }  }
   
 ######################################################################  
 ######################################################################  
   
 =pod   
   
 =item &recursive_SQL_query_build()   
   
 Recursively constructs an SQL query.  Takes as input $dkey and $pattern.  
   
 =cut  
   
 ######################################################################  
 ######################################################################  
 sub recursive_SQL_query_build {  
     my ($dkey,$pattern)=@_;  
     my @matches=($pattern=~/(\[[^\]|\[]*\])/g);  
     return $pattern unless @matches;  
     foreach my $match (@matches) {  
         $match=~/\[ (\w+)\s(.*) \]/;  
         my ($key,$value)=($1,$2);  
         my $replacement='';  
         if ($key eq 'literal') {  
             $replacement="($dkey LIKE \"\%$value\%\")";  
         } elsif (lc($key) eq 'not') {  
             $value=~s/LIKE/NOT LIKE/;  
 #          $replacement="($dkey not like $value)";  
             $replacement="$value";  
         } elsif ($key eq 'and') {  
             $value=~/(.*[\"|\)]) ([|\(|\^].*)/;  
             $replacement="($1 AND $2)";  
  } elsif ($key eq 'or') {  
             $value=~/(.*[\"|\)]) ([|\(|\^].*)/;  
             $replacement="($1 OR $2)";  
  }  
  substr($pattern,  
                index($pattern,$match),  
                length($match),  
                $replacement);  
     }  
     &recursive_SQL_query_build($dkey,$pattern);  
 }  
   
 ######################################################################  ######################################################################
 ######################################################################  ######################################################################
Line 1871  sub print_sort_form { Line 1986  sub print_sort_form {
     my $bodytag=&Apache::loncommon::bodytag(undef,undef,undef,1).      my $bodytag=&Apache::loncommon::bodytag(undef,undef,undef,1).
         &Apache::lonhtmlcommon::breadcrumbs          &Apache::lonhtmlcommon::breadcrumbs
         (undef,'Searching','Searching',undef,undef,          (undef,'Searching','Searching',undef,undef,
          ! ($ENV{'form.catalogmode'} eq 'groupsearch'));           $ENV{'form.catalogmode'} ne 'groupsearch');
   
     ##      ##
     my %SortableFields=&Apache::lonlocal::texthash(       my %SortableFields=&Apache::lonlocal::texthash( 
Line 2138  results into MySQL. Line 2253  results into MySQL.
 sub run_search {  sub run_search {
     my ($r,$query,$customquery,$customshow,$serverlist,$pretty_string) = @_;      my ($r,$query,$customquery,$customshow,$serverlist,$pretty_string) = @_;
     my $bodytag=&Apache::loncommon::bodytag(undef,undef,undef,1);      my $bodytag=&Apache::loncommon::bodytag(undef,undef,undef,1);
     $bodytag.=      $bodytag.=&Apache::lonhtmlcommon::breadcrumbs
         &Apache::lonhtmlcommon::breadcrumbs(undef,'Searching','Searching',          (undef,'Searching','Searching',undef,undef,
                                             undef,undef,! $ENV{'form.launch'});           $ENV{'form.catalogmode'} ne 'groupsearch');
   
     my $connection = $r->connection;      my $connection = $r->connection;
     #      #
     # Print run_search header      # Print run_search header
Line 2153  $bodytag Line 2267  $bodytag
 <form name="statusform" action="" method="post">  <form name="statusform" action="" method="post">
 <input type="hidden" name="Queue" value="" />  <input type="hidden" name="Queue" value="" />
 END  END
     # Check to see if $pretty_string has more than one carriage return.      # Remove leading and trailing <br />
     # Assume \n s are following <br /> s and truncate the value.      $pretty_string =~ s:^\s*<br />::i;
     # (there is probably a better way)...      $pretty_string =~ s:(<br />)*\s*$::im;
     my @Lines = split /<br \/>/,$pretty_string;      my @Lines = split("<br />",$pretty_string);
       # I keep getting blank items at the end of the list, hence the following:
       while ($Lines[-1] =~ /^\s*$/ && @Lines) {
           pop(@Lines);
       }
     if (@Lines > 2) {      if (@Lines > 2) {
         $pretty_string = join '<br \>',(@Lines[0..2],'....<br />');          $pretty_string = join '<br />',(@Lines[0..2],'....<br />');
     }      }
     $r->print(&mt("Search: [_1]",$pretty_string));      $r->print(&mt("Search: [_1]",$pretty_string));
     $r->rflush();      $r->rflush();
Line 2251  END Line 2369  END
         #          #
         # Loop through the servers we have contacted but do not          # Loop through the servers we have contacted but do not
         # have results from yet, looking for results.          # have results from yet, looking for results.
         while (my ($server,$status) = each(%Server_status)) {          foreach my $server (keys(%Server_status)) {
             last if ($connection->aborted());              last if ($connection->aborted());
             &update_seconds($r);              &update_seconds($r);
               my $status = $Server_status{$server};
             if ($status eq 'con_lost') {              if ($status eq 'con_lost') {
                 delete ($Server_status{$server});                  delete ($Server_status{$server});
                 next;                  next;
Line 2933  sub detailed_citation_view { Line 3052  sub detailed_citation_view {
          { name=>'copyrighttag',           { name=>'copyrighttag',
            translate => '<b>Copyright/Distribution:</b>&nbsp;[_1]',},             translate => '<b>Copyright/Distribution:</b>&nbsp;[_1]',},
          { name=>'count',           { name=>'count',
              format => "%d",
            translate => '<b>Access Count:</b>&nbsp;[_1]',},             translate => '<b>Access Count:</b>&nbsp;[_1]',},
          { name=>'stdno',           { name=>'stdno',
              format => "%d",
            translate => '<b>Number of Students:</b>&nbsp;[_1]',},             translate => '<b>Number of Students:</b>&nbsp;[_1]',},
          { name=>'avetries',           { name=>'avetries',
              format => "%.2f",
            translate => '<b>Average Tries:</b>&nbsp;[_1]',},             translate => '<b>Average Tries:</b>&nbsp;[_1]',},
          { name=>'disc',           { name=>'disc',
              format => "%.2f",
            translate => '<b>Degree of Discrimination:</b>&nbsp;[_1]',},             translate => '<b>Degree of Discrimination:</b>&nbsp;[_1]',},
          { name=>'difficulty',           { name=>'difficulty',
              format => "%.2f",
            translate => '<b>Degree of Difficulty:</b>&nbsp;[_1]',},             translate => '<b>Degree of Difficulty:</b>&nbsp;[_1]',},
          { name=>'clear',           { name=>'clear',
              format => "%.2f",
            translate => '<b>Clear:</b>&nbsp;[_1]',},             translate => '<b>Clear:</b>&nbsp;[_1]',},
          { name=>'depth',           { name=>'depth',
              format => "%.2f",
            translate => '<b>Depth:</b>&nbsp;[_1]',},             translate => '<b>Depth:</b>&nbsp;[_1]',},
          { name=>'helpful',           { name=>'helpful',
              format => "%.2f",
            translate => '<b>Helpful:</b>&nbsp;[_1]',},             translate => '<b>Helpful:</b>&nbsp;[_1]',},
          { name=>'correct',           { name=>'correct',
              format => "%.2f",
            translate => '<b>Correct:</b>&nbsp;[_1]',},             translate => '<b>Correct:</b>&nbsp;[_1]',},
          { name=>'technical',           { name=>'technical',
              format => "%.2f",
            translate => '<b>Technical:</b>&nbsp;[_1]',},             translate => '<b>Technical:</b>&nbsp;[_1]',},
            { name=>'comefrom_list',
              type => 'list',
              translate => 'Resources that lead up to this resource in maps',},
            { name=>'goto_list',
              type => 'list',
              translate => 'Resources that follow this resource in maps',},
            { name=>'sequsage_list',
              type => 'list',
              translate => 'Resources using or importing resource',},
          ) {           ) {
         if (exists($values{$field->{'name'}}) &&          next if (! exists($values{$field->{'name'}}) ||
             $values{$field->{'name'}} ne '') {                   $values{$field->{'name'}} eq '');
           if (exists($field->{'type'}) && $field->{'type'} eq 'list') {
               $result .= '<b>'.&mt($field->{'translate'}).'</b><ul>';
               foreach my $item (split(',',$values{$field->{'name'}})){
                   $result .= '<li>'.
                       '<a target="search_preview" '.
                       'href="/res/'.$item.'">'.$item.'</a></li>';
               }
               $result .= '</ul>';
           } elsif (exists($field->{'format'}) && $field->{'format'} ne ''){
               $result.= &mt($field->{'translate'},
                             sprintf($field->{'format'},
                                     $values{$field->{'name'}}))."<br />\n";
           } else {
             if ($field->{'special'} eq 'url link') {              if ($field->{'special'} eq 'url link') {
                 $result.=                   $result.= 
                     &mt($field->{'translate'},                       &mt($field->{'translate'},
                         '<a href="'.$values{'url'}.'" '.                           '<a href="'.$values{'url'}.'" '.
                             'target="search_preview">'.                           'target="search_preview">'.
                         $values{$field->{'name'}}.                           $values{$field->{'name'}}.
                         '</a>');                           '</a>');
             } else {              } else {
                 $result.= &mt($field->{'translate'},                  $result.= &mt($field->{'translate'},
                               $values{$field->{'name'}});                                $values{$field->{'name'}});
             }              }
             $result .= "<br />\n";              $result .= "<br />\n";
             }          }
     }      }
     $result .= "</p>";      $result .= "</p>";
     if (exists($values{'extrashow'}) && $values{'extrashow'} ne '') {      if (exists($values{'extrashow'}) && $values{'extrashow'} ne '') {
Line 3175  sub filled { Line 3326  sub filled {
   
 =pod   =pod 
   
   =item &output_unparsed_phrase_error()
   
   =cut
   
   ######################################################################
   ######################################################################
   sub output_unparsed_phrase_error {
       my ($r,$closebutton,$parms,$hidden_fields,$field)=@_;
       my $errorstring;
       if ($field eq 'basicexp') {
           $errorstring = &mt('Unable to understand the search phrase <i>[_1]</i>.  Please modify your search.',$ENV{'form.basicexp'});
       } else {
           $errorstring = &mt('Unable to understand the search phrase <b>[_1]</b>:<i>[_2]</i>.',$field,$ENV{'form.'.$field});
       }
       my $bodytag = &Apache::loncommon::bodytag('Search');
       my $heading = &mt('Unparsed Field');
       my $revise  = &mt('Revise search request');
       # make query information persistent to allow for subsequent revision
       $r->print(<<ENDPAGE);
   <html>
   <head>
   <title>The LearningOnline Network with CAPA</title>
   </head>
   $bodytag
   <form method="post" action="/adm/searchcat">
   $hidden_fields
   $closebutton
   <hr />
   <h2>$heading</h2>
   <p>
   $errorstring
   </p>
   <p>
   <a href="/adm/searchcat?$parms&persistent_db_id=$ENV{'form.persistent_db_id'}">$revise</a>
   </p>
   </body>
   </html>
   ENDPAGE
   }
   
   ######################################################################
   ######################################################################
   
   =pod 
   
 =item &output_blank_field_error()  =item &output_blank_field_error()
   
 Output a complete page that indicates the user has not filled in enough  Output a complete page that indicates the user has not filled in enough
Line 3192  $parms is extra information to include i Line 3388  $parms is extra information to include i
 ######################################################################  ######################################################################
 sub output_blank_field_error {  sub output_blank_field_error {
     my ($r,$closebutton,$parms,$hidden_fields)=@_;      my ($r,$closebutton,$parms,$hidden_fields)=@_;
     my $bodytag=&Apache::loncommon::bodytag(undef,undef,undef,1);      my $bodytag=&Apache::loncommon::bodytag('Search');
     # make query information persistent to allow for subsequent revision      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.');
     $r->print(<<BEGINNING);      my $revise = &mt('Revise Search Request');
       my $heading = &mt('Unactionable Search Queary');
       $r->print(<<ENDPAGE);
 <html>  <html>
 <head>  <head>
 <title>The LearningOnline Network with CAPA</title>  <title>The LearningOnline Network with CAPA</title>
 BEGINNING  
     $r->print(<<RESULTS);  
 </head>  </head>
 $bodytag  $bodytag
 <img align='right' src='/adm/lonIcons/lonlogos.gif' />  
 <h1>Search Catalog</h1>  
 <form method="post" action="/adm/searchcat">  <form method="post" action="/adm/searchcat">
 $hidden_fields  $hidden_fields
 <a href="/adm/searchcat?$parms&persistent_db_id=$ENV{'form.persistent_db_id'}"  
 >Revise search request</a>&nbsp;  
 $closebutton  $closebutton
 <hr />  <hr />
 <h3>Unactionable search query.</h3>  <h2>$heading</h2>
   <p>
   $errormsg
   </p>
 <p>  <p>
 You did not fill in enough information for the search to be started.  <a href="/adm/searchcat?$parms&persistent_db_id=$ENV{'form.persistent_db_id'}">$revise</a>&nbsp;
 You need to fill in relevant fields on the search page in order   
 for a query to be processed.  
 </p>  </p>
 </body>  </body>
 </html>  </html>
 RESULTS  ENDPAGE
       return;
 }  }
   
 ######################################################################  ######################################################################

Removed from v.1.224  
changed lines
  Added in v.1.230.2.1


FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>