File:  [LON-CAPA] / loncom / interface / coursecatalog.pm
Revision 1.60: download - view: text, annotated - select for diffs
Sun Apr 4 15:38:34 2010 UTC (14 years ago) by raeburn
Branches: MAIN
CVS tags: PRINT_INCOMPLETE_base, PRINT_INCOMPLETE, HEAD
- C(c)ourse -> C(c)ommunity if listing Communities in Catalog.

# The LearningOnline Network with CAPA
# Handler for displaying the course catalog interface
#
# $Id: coursecatalog.pm,v 1.60 2010/04/04 15:38:34 raeburn Exp $
#
# Copyright Michigan State University Board of Trustees
#
# This file is part of the LearningOnline Network with CAPA (LON-CAPA).
#
# LON-CAPA is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# LON-CAPA is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with LON-CAPA; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
#
# /home/httpd/html/adm/gpl.txt
#
# http://www.lon-capa.org/
#

package Apache::coursecatalog;

use strict;
use lib qw(/home/httpd/lib/perl);
use Apache::Constants qw(:common);
use Apache::loncommon;
use Apache::lonhtmlcommon;
use Apache::lonnet;
use Apache::lonlocal;
use Apache::courseclassifier;
use Apache::lonacc;
use LONCAPA;

sub handler {
    my ($r) = @_;
    &Apache::loncommon::content_type($r,'text/html');
    $r->send_http_header;
    if ($r->header_only) {
        return OK;
    }
    my $handle = &Apache::lonnet::check_for_valid_session($r);
    my $lonidsdir=$r->dir_config('lonIDsDir');
    if ($handle ne '') {
        &Apache::lonnet::transfer_profile_to_env($lonidsdir,$handle);
    }
    &Apache::lonacc::get_posted_cgi($r);
    &Apache::lonlocal::get_language_handle($r);
    &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
                                            ['sortby','showdom']);

    my $codedom = &Apache::lonnet::default_login_domain();

    if (($env{'user.domain'} ne '') && ($env{'user.domain'} ne 'public')) { 
        $codedom = $env{'user.domain'};
        if ($env{'request.role.domain'} ne '') {
            $codedom = $env{'request.role.domain'};
        }
    }
    my $formname = 'coursecatalog';
    if ($env{'form.showdom'} ne '') {
        if (&Apache::lonnet::domain($env{'form.showdom'}) ne '') {
            $codedom = $env{'form.showdom'};
        }
    }
    my $domdesc = &Apache::lonnet::domain($codedom,'description');
    &Apache::lonhtmlcommon::clear_breadcrumbs();

    my %domconfig =
        &Apache::lonnet::get_dom('configuration',['coursecategories'],$codedom);
    my (@cats,@trails,%allitems,%idx,@jsarray,%subcathash,$cathash);
    if (ref($domconfig{'coursecategories'}) eq 'HASH') {
        $cathash = $domconfig{'coursecategories'}{'cats'};
    } else {
        $cathash = {};
    }
    my $subcats;
    if ($env{'form.withsubcats'}) {
        $subcats = \%subcathash;
    }
    &Apache::loncommon::extract_categories($cathash,\@cats,\@trails,\%allitems,
                                           \%idx,\@jsarray,$subcats);
    if ($env{'form.coursenum'} ne '' && &user_is_known()) {
        &course_details($r,$codedom,$formname,$domdesc,\@trails,\%allitems);
    } else {
        my ($catlinks,$has_subcats,$selitem) = &category_breadcrumbs($codedom,@cats);
        my $catjs = <<"ENDSCRIPT";

function setCatDepth(depth) {
    document.coursecats.catalog_maxdepth.value = depth;
    if (depth == '') {
        document.coursecats.currcat_0.value = '';
    }
    document.coursecats.submit();
    return;
}

function changeSort(caller) {
    document.$formname.sortby.value = caller;
    document.$formname.submit();
}

function setCourseId(caller) {
    document.$formname.coursenum.value = caller;
    document.$formname.submit();
}

ENDSCRIPT
        $catjs .= &courselink_javascript(); 
        my $numtitles;
        if ($env{'form.currcat_0'} eq 'instcode::0') {
            $numtitles = &instcode_course_selector($r,$codedom,$formname,$domdesc,
                                                   $catlinks,$catjs);
            if ($env{'form.state'} eq 'listing') {
                $r->print(&print_course_listing($codedom,$numtitles));
            }
        } else {
            my (%add_entries);
            my ($currdepth,$deeper) = &get_depth_values();
            if ($selitem) {
                my $alert = &mt('Choose a subcategory to display');
                if (!$deeper) {
                    $alert = &mt('Choose a category to display');
                }
                $catjs .= <<ENDJS;
function check_selected() {
    if (document.coursecats.$selitem.options[document.coursecats.$selitem.selectedIndex].value == "") {
        alert('$alert');
        return false;
    }
}
ENDJS
            }
            $catjs = '<script type="text/javascript">'."\n".$catjs."\n".'</script>';
            &cat_header($r,$codedom,$catjs,\%add_entries,$catlinks);
            if ($env{'form.currcat_0'} ne '') {
                $r->print('<form name="'.$formname.
                          '" method="post" action="/adm/coursecatalog">'.
                          &additional_filters($codedom,$has_subcats)."\n");
                $r->print('<input type="hidden" name="catalog_maxdepth" value="'.
                          $deeper.'" />'."\n");
                for (my $i=0; $i<$deeper; $i++) {
                    $r->print('<input type="hidden" name="currcat_'.$i.'" value="'.$env{'form.currcat_'.$i}.'" />'."\n");
                }
                my $display_button;
                if ($env{'form.currcat_0'} eq 'communities::0') {
                    $display_button = &mt('Display communities');
                } else {
                    $display_button = &mt('Display courses');
                }
                $r->print('<input type="hidden" name="coursenum" value="" />'."\n".
                          '<input type="hidden" name="sortby" value="" />'."\n".
                          '<input type="hidden" name="state" value="listing" />'."\n".
                          '<input type="hidden" name="showdom" value="'.
                          $env{'form.showdom'}.'" />'.
                          '<input type="submit" name="catalogfilter" value="'.
                          $display_button.'" /></form><br /><br />');
            }
            if ($env{'form.state'} eq 'listing') {
                $r->print(&print_course_listing($codedom,undef,\@trails,\%allitems,$subcats));
            }
        }
    }
    $r->print('<br />'.&Apache::loncommon::end_page());
    return OK;
}

sub course_details {
    my ($r,$codedom,$formname,$domdesc,$trails,$allitems) = @_;
    my $output;
    my %add_entries = (topmargin    => "0",
                       marginheight => "0",);
    my $js = '<script type="text/javascript">'."\n".
             &courselink_javascript().'</script>'."\n";
    my $start_page =
        &Apache::loncommon::start_page('Course/Community Catalog',$js,
                                           {'add_entries' => \%add_entries, });
    $r->print($start_page);
    if ($env{'form.numtitles'} > 0) {
        &Apache::lonhtmlcommon::add_breadcrumb
                ({href=>"/adm/coursecatalog",
                  text=>"Course/Community Catalog"});
    }
    my $brtextone = 'Course listing';
    my $brtexttwo = 'Course details';
    if ($env{'form.currcat_0'} eq 'communities::0') {
        $brtextone = 'Community listing';
        $brtextone = 'Community details';
    }
    &Apache::lonhtmlcommon::add_breadcrumb
             ({href=>"javascript:document.$formname.submit()",
              text=>$brtextone},
             {text=>$brtexttwo});
    $r->print(&Apache::lonhtmlcommon::breadcrumbs('Course/Community Catalog'));
    $r->print('<br />');
    if ($env{'form.currcat_0'} eq 'communities::0') {
        $r->print(&mt('Detailed community information:'));
    } else {
        $r->print(&mt('Detailed course information:'));
    }
    $r->print('<br /><br />'.
              &print_course_listing($codedom,undef,$trails,$allitems).
              '<br /><br />');
    $r->print('<form name="'.$formname.'" method="post" action="/adm/coursecatalog">'.
              '<a href = "javascript:document.coursecatalog.submit()">');
    if ($env{'form.currcat_0'} eq 'communities::0') {
        $r->print(&mt('Back to community listing'));
    } else {
        $r->print(&mt('Back to course listing'));
    }
    $r->print('</a>'.
              &Apache::lonhtmlcommon::echo_form_input(['coursenum','catalogfilter',
                                                       'showdetails','courseid']).'</form>');
    return;
}

sub courselink_javascript {
    return <<"END";

function ToSyllabus(cdom,cnum) {
    if (cdom == '' || cdom == null) {
        return;
    }
    if (cnum == '' || cnum == null) {
        return;
    }
    document.linklaunch.action = "/public/"+cdom+"/"+cnum+"/syllabus";
    document.linklaunch.submit();
}

function ToSelfenroll(courseid) {
    if (courseid == '') {
        return;
    }
    document.linklaunch.action = "/adm/selfenroll";
    document.linklaunch.courseid.value = courseid;
    document.linklaunch.submit();
}

END
}

sub instcode_course_selector {
    my ($r,$codedom,$formname,$domdesc,$catlinks,$catjs) = @_;
    my %coursecodes = ();
    my %codes = ();
    my @codetitles = ();
    my %cat_titles = ();
    my %cat_order = ();
    my %cat_items;
    my $caller = 'global';
    my $format_reply;
    my %add_entries = (topmargin    => "0",
                       marginheight => "0",);
    my ($jscript,$totcodes,$numtitles,$lasttitle) = 
        &Apache::courseclassifier::instcode_selectors_data($codedom,$formname,
                           \%cat_items,\@codetitles,\%cat_titles,\%cat_order);
    my $js = '<script type"text/javascript">'."\n$jscript\n$catjs\n".
              '</script>';
    if ($totcodes) {
        if (($env{'form.state'} eq 'listing') && ($numtitles > 0)) {
            $add_entries{'onLoad'} = 'setElements()';
        }
        &cat_header($r,$codedom,$js,\%add_entries,$catlinks,$numtitles);
        my $cat_maxdepth = $env{'form.catalog_maxdepth'};
        $r->print('<form name="'.$formname.'" method="post" action="/adm/coursecatalog">'.
                  '<input type="hidden" name="catalog_maxdepth" value="'.$cat_maxdepth.'" />'."\n".
                  '<input type="hidden" name="showdom" value="'.$env{'form.showdom'}.'" />'."\n".
                  '<input type="hidden" name="currcat_0" value="instcode::0" />'.
                  &additional_filters($codedom));
        if ($numtitles > 0) {
            $r->print('<b>'.&mt('Choose which course(s) to list.').'</b><br />'.
                      &Apache::courseclassifier::build_instcode_selectors($numtitles,
                       $lasttitle,\%cat_items,\@codetitles,\%cat_titles,\%cat_order));
        }
        $r->print('<input type="hidden" name="coursenum" value="" />'."\n".
                  '<input type="hidden" name="sortby" value="" />'."\n".
                  '<input type="hidden" name="state" value="listing" />'."\n".
                  '<input type="hidden" name="form.currcat_0" value="instcode::0" />'."\n".
                  '<input type="submit" name="catalogfilter" value="'.
                  &mt('Display courses').'" />'.
                  '<input type="hidden" name="numtitles" value="'.$numtitles.
                  '" /></form><br /><br />');
    } else {
        $js = '<script type"text/javascript">'."\n$catjs\n".'</script>';
        &cat_header($r,$codedom,$js,\%add_entries,$catlinks,$numtitles);
        my $cat_maxdepth = $env{'form.catalog_maxdepth'};
        $r->print('<form name="'.$formname.'" method="post" action="/adm/coursecatalog">'.
                  '<input type="hidden" name="catalog_maxdepth" value="'.$cat_maxdepth.'" />'.
                  '<input type="hidden" name="showdom" value="'.$env{'form.showdom'}.'" />'.
                  '<input type="hidden" name="currcat_0" value="instcode::0" />');
        $r->print('<br />'.&mt('No official courses to display for [_1].',$domdesc).'</form>');
    }
    return $numtitles;
}

sub cat_header {
    my ($r,$codedom,$js,$add_entries,$catlinks,$numtitles) = @_;
    my $start_page =
        &Apache::loncommon::start_page('Other',$js,
                                       { 'add_entries' => $add_entries, });
    $r->print($start_page);
    my $brtext = 'Course listing';
    if ($env{'form.currcat_0'} eq 'communities::0') {
        $brtext = 'Community listing';
    }
    if ($env{'form.state'} eq 'listing') {
        if ($numtitles > 0) {
            &Apache::lonhtmlcommon::add_breadcrumb
                ({href=>"/adm/coursecatalog",
                  text=>"Course/Community Catalog"},
                 {text=>$brtext});
        } else {
            &Apache::lonhtmlcommon::add_breadcrumb
            ({text=>$brtext});
        }
    } else {
        &Apache::lonhtmlcommon::add_breadcrumb
        ({href=>"/adm/coursecatalog",
          text=>"Course/Community Catalog"});
    }
    $r->print(&Apache::lonhtmlcommon::breadcrumbs('Course/Community Catalog'));
    my $onchange;
    unless ($env{'form.interface'} eq 'textual') {
        $onchange = 'this.form.submit()';
    }
    $r->print('<form name="coursecatdom" method="post" action="/adm/coursecatalog">'.
              '<table border="0"><tr><td><b>'.&mt('Domain:').'</b></td><td>'.
              &Apache::loncommon::select_dom_form($codedom,'showdom','',1,$onchange));
    if (!$onchange) {
	   $r->print('&nbsp;<input type="submit" name="godom" value="'.&mt('Change').'" />');
    }
    $r->print('</td></tr></table></form>'.
	      '<form name="coursecats" method="post" action="/adm/coursecatalog"'.
              ' onsubmit="return check_selected();">'.
              '<table border="0"><tr>'.$catlinks.'</tr></table></form>');
    return;
}

sub category_breadcrumbs {
    my ($dom,@cats) = @_;
    my $crumbsymbol = ' &#x25b6; ';
    my ($currdepth,$deeper) = &get_depth_values();
    my $currcat_str = 
        '<input type="hidden" name="catalog_maxdepth" value="'.$deeper.'" />'.
        '<input type="hidden" name="showdom" value="'.$dom.'" />';
    my $catlinks = '<td valign="top"><b>'.&mt('Catalog:').'</b></td><td><table><tr><td>';
    my $has_subcats;
    my $selitem;
    if (ref($cats[0]) eq 'ARRAY') {
        if (@{$cats[0]} == 0) {
            $catlinks .= &mt('No categories defined in this domain'); 
        } elsif (@{$cats[0]} == 1) {
            if ($cats[0][0] eq 'instcode') {
                $catlinks .= &mt('Official courses (with institutional codes)');
                $env{'form.currcat_0'} = 'instcode::0';
            } elsif ($cats[0][0] eq 'communities') {
                $catlinks .= &mt('Communities');
                $env{'form.currcat_0'} = 'communities::0';
            } else {
                my $name = $cats[0][0];
                my $item = &escape($name).'::0';
                $catlinks .= $name;
                $env{'form.currcat_0'} = $item;
            }
            $currcat_str .= '<input type="hidden" name="currcat_0" value="'.$env{'form.currcat_0'}.'" />';
        } else {
            $catlinks .= &main_category_selector(@cats);
            if (($env{'form.currcat_0'} ne '') && 
                ($env{'form.currcat_0'} ne 'instcode::0')) {
                $catlinks .= $crumbsymbol;
            } else {
                $catlinks .= '</td>';
            }
        }
    } else {
        $catlinks .= &mt('Official courses (with institutional codes)');
                     $env{'form.currcat_0'} = 'instcode::0';
         $currcat_str .= '<input type="hidden" name="currcat_0" value="'.$env{'form.currcat_0'}.'" />';
    }
    if ($deeper) {
        for (my $i=1; $i<=$deeper; $i++) {
            my $shallower = $i-1;
            next if ($shallower == 0);
            my ($cat,$container,$depth) = map { &unescape($_); } split(/:/,$env{'form.currcat_'.$shallower});
            if ($cat ne '') {
                $catlinks .= '<td valign="top">'.
                             '<select name="currcat_'.$shallower.'" onchange="'.
                             'setCatDepth('."'$shallower'".');this.form.submit();">';
                if (ref($cats[$shallower]{$container}) eq 'ARRAY') {
                    $catlinks .= '<option value="">'.&mt('De-select').'</option>';
                    for (my $j=0; $j<@{$cats[$shallower]{$container}}; $j++) {
                        my $name = $cats[$shallower]{$container}[$j];
                        my $item = &escape($name).':'.$container.':'.$shallower;
                        my $selected = '';
                        if ($item eq $env{'form.currcat_'.$shallower}) {
                            $selected = ' selected="selected"';
                        }
                        $catlinks .= 
                           '<option value="'.$item.'"'.$selected.'>'.$name.'</option>';
                    }
                }
                $catlinks .= '</select>';
            }
            unless ($i == $deeper) {
                $catlinks .= $crumbsymbol;
            } 
        }
        my ($cat,$container,$depth);
        if ($env{'form.currcat_'.$currdepth} eq '') {
            my $shallower = $currdepth - 1;
            ($cat,$container,$depth) = map { &unescape($_); } split(/:/,$env{'form.currcat_'.$shallower});
        } else {
            ($cat,$container,$depth) = map { &unescape($_); } split(/:/,$env{'form.currcat_'.$currdepth});
        }
        my $deeperlevel = $depth +1;
        if (ref($cats[$deeperlevel]{$cat}) eq 'ARRAY') {
            $has_subcats = 1;
            my $buttontext = &mt('Show subcategories');
            my $selitem = 'currcat_'.$deeperlevel;
            $catlinks .= '&nbsp;<select name="'.$selitem.'" onchange="this.form.submit()">';
            if (@{$cats[$deeperlevel]{$cat}}) {
                $catlinks .= '<option value="" selected="selected">'.
                             &mt('Subcategory ...').'</option>';
            }
            for (my $k=0; $k<@{$cats[$deeperlevel]{$cat}}; $k++) {
                my $name = $cats[$deeperlevel]{$cat}[$k];
                my $item = &escape($name).':'.&escape($cat).':'.$deeperlevel;
                $catlinks .= '<option value="'.$item.'">'.$name.'</option>'."\n";
            }
            $catlinks .= '</select>'."\n";
        } elsif ($cat ne 'instcode') {
            $catlinks .= '&nbsp;'.&mt('(No subcategories)');
        }
    } else {
        $selitem = 'currcat_0';
    }
    $catlinks .= $currcat_str.'</td></tr></table></td>';
    return ($catlinks,$has_subcats,$selitem);
}

sub main_category_selector {
    my (@cats) = @_;
    my $maincatlinks = '<select name="currcat_0" onchange="setCatDepth('."'0'".');this.form.submit();">'."\n";
    if (ref($cats[0]) eq 'ARRAY') {
        if (@{$cats[0]} > 1) {
            my $selected = '';
            if ($env{'form.currcat_0'} eq '') {
                $selected = ' selected="selected"';    
            }
            $maincatlinks .= 
                '<option value=""'.$selected.'>'.&mt('Select').'</option>'."\n";
        }
        for (my $i=0; $i<@{$cats[0]}; $i++) {
            my $name = $cats[0][$i];
            my $item = &escape($name).'::0';
            my $selected;
            if ($env{'form.currcat_0'} eq $item) {
                $selected = ' selected="selected"';
            }
            $maincatlinks .= '<option value="'.$item.'"'.$selected.'>';
            if ($name eq 'instcode') {
                $maincatlinks .= &mt('Official courses (with institutional codes)');
            } elsif ($name eq 'communities') {
                $maincatlinks .= &mt('Communities');
            } else {
                $maincatlinks .= $name;
            }
            $maincatlinks .= '</option>'."\n";
        }
        $maincatlinks .= '</select>'."\n";
    }
    return $maincatlinks;
}

sub get_depth_values {
    my $currdepth = 0;
    my $deeper = 0;
    if ($env{'form.catalog_maxdepth'} ne '') {
        $currdepth = $env{'form.catalog_maxdepth'};
        if ($env{'form.currcat_'.$currdepth} eq '') {
            $deeper = $currdepth;
        } else {
            $deeper = $currdepth + 1;
        }
    }
    return ($currdepth,$deeper);
}

sub additional_filters {
    my ($codedom,$has_subcats) = @_;
    my $output = '<table>';
    if (($env{'form.currcat_0'} ne 'instcode::0') && 
        ($env{'form.currcat_0'} ne '') && ($has_subcats)) {
        my $include_subcat_status;
        if ($env{'form.withsubcats'}) {
            $include_subcat_status = 'checked="checked" ';
        }
        my $counter = $env{'form.catalog_maxdepth'};
        if ($counter > 0) {
            if ($env{'form.state'} eq 'listing') {
                $counter --;
            } elsif ($env{'form.currcat_'.$counter} eq '') {
                $counter --;
            }
        }
        my ($catname) = split(/:/,$env{'form.currcat_'.$counter});
        if ($catname ne '') {
            $output .= '<tr><td><label>'.
                       '<input type="checkbox" name="withsubcats" value="1" '.
                       $include_subcat_status.'/>'.
                       &mt('Include subcategories within "[_1]"',
                           &unescape($catname)).'</label></td></tr>';
        }
    }
    my $show_selfenroll_status;
    if ($env{'form.showselfenroll'}) {
        $show_selfenroll_status = 'checked="checked" ';
    }
    my $selfenroll_text;
    if ($env{'form.currcat_0'} eq 'communities::0') {
        $selfenroll_text = &mt('Only show communities which allow self-enrollment');
    } else {
        $selfenroll_text = &mt('Only show courses which allow self-enrollment');
    }
    $output .= '<tr><td>'.
               '<label><input type="checkbox" name="showselfenroll" value="1" '.
               $show_selfenroll_status.'/>'.$selfenroll_text.
               '</label></td></tr>';
    if (&user_is_dc($codedom)) {
        my $showdetails_status;
        if ($env{'form.showdetails'}) {
            $showdetails_status = 'checked="checked" ';
        }
        my $showhidden_status;
        if ($env{'form.showhidden'}) {
             $showhidden_status = 'checked="checked" ';
        }
        my $dc_title = &Apache::lonnet::plaintext('dc');
        my ($details_text,$hidden_text);
        if ($env{'form.currcat_0'} eq 'communities::0') {
            $details_text = &mt('Show full details for each community ([_1] only)',$dc_title);
            $hidden_text = &mt('Include communities set to be hidden from catalog ([_1] only)',$dc_title);
        } else {
            $details_text = &mt('Show full details for each course ([_1] only)',$dc_title);
            $hidden_text = &mt('Include courses set to be hidden from catalog ([_1] only)',$dc_title);
        }
        $output .= '<tr><td>'."\n".
                   '<label><input type="checkbox" name="showdetails" value="1" '.
                   $showdetails_status.'/>'.$details_text.
                   '</label>'."\n".'</td></tr><tr><td>'.
                   '<label><input type="checkbox" name="showhidden" value="1" '.
                   $showhidden_status.'/>'.$hidden_text.
                   '</label>'."\n".'</td></tr>';
    }
    $output .= '</table><br />';
    return $output;
}

sub user_is_dc {
    my ($codedom) = @_;
    if (exists($env{'user.role.dc./'.$codedom.'/'})) {
        my $livedc = 1;
        my $now = time;
        my ($start,$end)=split(/\./,$env{'user.role.dc./'.$codedom.'/'});
        if ($start && $start>$now) { $livedc = 0; }
        if ($end   && $end  <$now) { $livedc = 0; }
        return $livedc;
    }
    return;
}

sub search_official_courselist {
    my ($domain,$numtitles) = @_;
    my $instcode = &Apache::courseclassifier::instcode_search_str($domain,$numtitles);
    my $showhidden;
    if (&user_is_dc($domain)) {
        $showhidden = $env{'form.showhidden'};
    }
    my %courses = 
        &Apache::lonnet::courseiddump($domain,'.',1,$instcode,'.','.',undef,undef,
                                      'Course',1,$env{'form.showselfenroll'},undef,
                                      $showhidden,'coursecatalog');
    return %courses;
}

sub search_courselist {
    my ($domain,$subcats) = @_;
    my $cat_maxdepth = $env{'form.catalog_maxdepth'};
    my $filter = $env{'form.currcat_'.$cat_maxdepth};
    if (($filter eq '') && ($cat_maxdepth > 0)) {
        my $shallower = $cat_maxdepth - 1;
        $filter = $env{'form.currcat_'.$shallower};
    }
    my %courses;
    my $filterstr;
    if ($filter ne '') {
        if ($env{'form.withsubcats'}) {
            if (ref($subcats) eq 'HASH') {
                if (ref($subcats->{$filter}) eq 'ARRAY') {
                    $filterstr = join('&',@{$subcats->{$filter}});
                    if ($filterstr ne '') {
                        $filterstr = $filter.'&'.$filterstr;
                    }
                } else {
                    $filterstr = $filter;
                }
            } else {
                $filterstr = $filter;
            }  
        } else {
            $filterstr = $filter; 
        }
        my ($showhidden,$typefilter);
        if (&user_is_dc($domain)) {
            $showhidden = $env{'form.showhidden'};
        }
        if ($env{'form.currcat_0'} eq 'communities::0') {
            $typefilter = 'Community';
        } else {
            $typefilter = '.';
        }
        %courses = 
            &Apache::lonnet::courseiddump($domain,'.',1,'.','.','.',undef,undef,
                                          $typefilter,1,$env{'form.showselfenroll'},
                                          $filterstr,$showhidden,'coursecatalog');
    }
    return %courses;
}

sub print_course_listing {
    my ($domain,$numtitles,$trails,$allitems,$subcats) = @_;
    my $output;
    my %courses;
    my $knownuser = &user_is_known();
    my $details = $env{'form.coursenum'};
    if (&user_is_dc($domain)) {
        if ($env{'form.showdetails'}) {
            $details = 1;
        }
    }
    if ($env{'form.coursenum'} ne '') {
        %courses = &Apache::lonnet::courseiddump($domain,'.',1,'.','.',
                                                 $env{'form.coursenum'},
                                                 undef,undef,'.',1);
        if (keys(%courses) == 0) {
            if ($env{'form.currcat_0'} eq 'communities::0') {
                $output .= &mt('The courseID provided does not match a community in this domain.');
            } else { 
                $output .= &mt('The courseID provided does not match a course in this domain.');
            }
            return $output;
        }
    } else {
        if ($env{'form.currcat_0'} eq 'instcode::0') {
            %courses = &search_official_courselist($domain,$numtitles);
        } else {
            %courses = &search_courselist($domain,$subcats);
        }
        if (keys(%courses) == 0) {
            if ($env{'form.currcat_0'} eq 'communities::0') {
                $output = &mt('No communities match the criteria you selected.');
            } else {
                $output = &mt('No courses match the criteria you selected.');
            }
            return $output;
        }
        if (($knownuser) && (!$env{'form.showdetails'}) && (!&user_is_dc($domain))) {
            $output = '<b>'.&mt('Note for students:').'</b> '
                     .&mt('If you are officially enrolled in a course but the course is not listed in your LON-CAPA courses, click the "Show more details" link for the specific course and check the default access dates and/or automated enrollment settings.')
                     .'<br /><br />';
        }
    }
    my $now = time;
    my %domconfig =
        &Apache::lonnet::get_dom('configuration',['usercreation'],$domain);
    $output .= &construct_data_table($knownuser,\%courses,$details,undef,$now,\%domconfig,$trails,$allitems);
    $output .= "\n".'<form name="linklaunch" method="post" action="">'.
               '<input type="hidden" name="backto" value="coursecatalog" />'.
               '<input type="hidden" name="courseid" value="" />'.
               &Apache::lonhtmlcommon::echo_form_input(['catalogfilter','courseid']).'</form>';
    return $output;
}

sub construct_data_table {
    my ($knownuser,$courses,$details,$usersections,$now,$domconfig,$trails,
        $allitems) = @_;
    my %sortname;
    if (($details eq '') || ($env{'form.showdetails'})) {
        $sortname{'Code'} = 'code';
        $sortname{'Categories'} = 'cats';
        $sortname{'Title'} = 'title';
        $sortname{'Owner(s)'} = 'owner';
    }
    my $output = &Apache::loncommon::start_data_table().
                 &Apache::loncommon::start_data_table_header_row();
    my @coltitles = ('Count');
    if ($env{'form.currcat_0'} eq 'instcode::0') {
        push(@coltitles,'Code');
    } else {
        push(@coltitles,'Categories');
    }
    push(@coltitles,('Sections','Crosslisted','Title','Owner(s)'));
    if (ref($usersections) eq 'HASH') {
       $coltitles[1] = 'Your Section';
    }
    foreach my $item (@coltitles) {
        $output .= '<th>';
        if (defined($sortname{$item})) {
            $output .= '<a href="javascript:changeSort('."'$sortname{$item}'".')">'.&mt($item).'</a>';
        } elsif ($item eq 'Count') {
            $output .= '&nbsp;&nbsp;';
        } else {
            $output .= &mt($item);
        }
        $output .= '</th>';
    }
    if ($knownuser) {
        if ($details) {
            if ($env{'form.currcat_0'} eq 'communities::0') {
                $output .= '<th>'.&mt('Default Access Dates for Members').'</th>';
            } else {
                $output .=
                    '<th>'.&mt('Default Access Dates for Students').'</th>'.
                    '<th>'.&mt('Student Counts').'</th>'.
                    '<th>'.&mt('Auto-enrollment of[_1]registered students','<br />').'</th>';
            }
        } else {
            $output .= '<th>'.&mt('Details').'</th>';
        }
    }
    $output .= '<th>'.&mt('Self-enroll (if permitted)').'</th>';
    &Apache::loncommon::end_data_table_header_row();
    my %courseinfo = &build_courseinfo_hash($courses,$knownuser,$details,
                                            $usersections);
    my %Sortby;
    foreach my $course (sort(keys(%{$courses}))) {
        if ($env{'form.sortby'} eq 'code') {
            push(@{$Sortby{$courseinfo{$course}{'code'}}},$course);
        } elsif ($env{'form.sortby'} eq 'cats') {
            push(@{$Sortby{$courseinfo{$course}{'categories'}}},$course);
        } elsif ($env{'form.sortby'} eq 'owner') {
            push(@{$Sortby{$courseinfo{$course}{'ownerlastnames'}}},$course);
        } else {
            my $clean_title = $courseinfo{$course}{'title'};
            $clean_title =~ s/\W+//g;
            if ($clean_title eq '') {
                $clean_title = $courseinfo{$course}{'title'};
            }
            push(@{$Sortby{$clean_title}},$course);
        }
    }
    my @sorted_courses;
    if (($env{'form.sortby'} eq 'code') || ($env{'form.sortby'} eq 'owner') ||
        ($env{'form.sortby'} eq 'cats')) {
        @sorted_courses = sort(keys(%Sortby));
    } else {
        @sorted_courses = sort { lc($a) cmp lc($b) } (keys(%Sortby));
    }
    my $count = 1;
    foreach my $item (@sorted_courses) {
        foreach my $course (@{$Sortby{$item}}) {
            $output.=&Apache::loncommon::start_data_table_row(); 
            $output.=&courseinfo_row($courseinfo{$course},$knownuser,$details,
                                     \$count,$now,$course,$trails,$allitems);
            $output.=&Apache::loncommon::end_data_table_row();
        }
    }
    $output .= &Apache::loncommon::end_data_table();
    return $output;
}

sub build_courseinfo_hash {
    my ($courses,$knownuser,$details,$usersections) = @_;
    my %courseinfo;
    my $now = time;
    foreach my $course (keys(%{$courses})) {
        my $descr;
        if (ref($courses->{$course}) eq 'HASH') {
            $descr = $courses->{$course}{'description'}; 
        }
        my $cleandesc=&HTML::Entities::encode($descr,'<>&"');
        $cleandesc=~s/'/\\'/g;
        $cleandesc =~ s/^\s+//;
        my ($cdom,$cnum)=split(/\_/,$course);
        my ($instcode,$singleowner,$ttype,$selfenroll_types,
            $selfenroll_start,$selfenroll_end,@owners,%ownernames,$categories);
        if (ref($courses->{$course}) eq 'HASH') {
            $descr = $courses->{$course}{'description'};
            $instcode =  $courses->{$course}{'inst_code'};
            $singleowner = $courses->{$course}{'owner'};
            $ttype =  $courses->{$course}{'type'};
            $selfenroll_types = $courses->{$course}{'selfenroll_types'};
            $selfenroll_start = $courses->{$course}{'selfenroll_start_date'};
            $selfenroll_end = $courses->{$course}{'selfenroll_end_date'};
            $categories = $courses->{$course}{'categories'};
            push(@owners,$singleowner);
            if (ref($courses->{$course}{'co-owners'}) eq 'ARRAY') {
                foreach my $item (@{$courses->{$course}{'co-owners'}}) {
                    push(@owners,$item);
                }
            }
        }
        foreach my $owner (@owners) {
            my ($ownername,$ownerdom); 
            if ($owner =~ /:/) {
                ($ownername,$ownerdom) = split(/:/,$owner);
            } else {
                $ownername = $owner;
                if ($owner ne '') {
                    $ownerdom = $cdom;
                }
            }
            if ($ownername ne '' && $ownerdom ne '') {
                my %namehash=&Apache::loncommon::getnames($ownername,$ownerdom);
                $ownernames{$ownername.':'.$ownerdom} = \%namehash; 
            }
        }
        $courseinfo{$course}{'cdom'} = $cdom;
        $courseinfo{$course}{'cnum'} = $cnum;
        $courseinfo{$course}{'code'} = $instcode;
        my @lastnames;
        foreach my $owner (keys(%ownernames)) {
            if (ref($ownernames{$owner}) eq 'HASH') {
                push(@lastnames,$ownernames{$owner}{'lastname'});
            }
        }
        $courseinfo{$course}{'ownerlastnames'} = join(', ',sort(@lastnames));
        $courseinfo{$course}{'title'} = $cleandesc;
        $courseinfo{$course}{'owner'} = $singleowner;
        $courseinfo{$course}{'selfenroll_types'} = $selfenroll_types;
        $courseinfo{$course}{'selfenroll_start'} = $selfenroll_start;
        $courseinfo{$course}{'selfenroll_end'} = $selfenroll_end;
        $courseinfo{$course}{'categories'} = $categories;

        my %coursehash = &Apache::lonnet::dump('environment',$cdom,$cnum);
        my @classids;
        my @crosslistings;
        my ($seclist,$numsec) = 
            &identify_sections($coursehash{'internal.sectionnums'});
        if (ref($usersections) eq 'HASH') {
            if (ref($usersections->{$course}) eq 'ARRAY') {
                $seclist = join(', ',@{$usersections->{$course}});
            }
        }
        $courseinfo{$course}{'seclist'} = $seclist;
        my ($xlist_items,$numxlist) = 
            &identify_sections($coursehash{'internal.crosslistings'});
        my $showsyllabus = 1; # default is to include a syllabus link
        if (defined($coursehash{'showsyllabus'})) {
            $showsyllabus = $coursehash{'showsyllabus'};
        }
        $courseinfo{$course}{'showsyllabus'} = $showsyllabus;
        if (((defined($env{'form.coursenum'}) && ($cnum eq $env{'form.coursenum'}))) ||
            ($knownuser && ($details == 1))) {
            $courseinfo{$course}{'counts'} =  &count_students($cdom,$cnum,$numsec);
            $courseinfo{$course}{'autoenrollment'} =
                &autoenroll_info(\%coursehash,$now,$seclist,$xlist_items,
                                 $instcode,\@owners,$cdom,$cnum);

            my $startaccess = '';
            my $endaccess = '';
            my $accessdates;
            if ( defined($coursehash{'default_enrollment_start_date'}) ) {
                $startaccess = &Apache::lonlocal::locallocaltime($coursehash{'default_enrollment_start_date'});
            }
            if ( defined($coursehash{'default_enrollment_end_date'}) ) {
                $endaccess = &Apache::lonlocal::locallocaltime($coursehash{'default_enrollment_end_date'});
                if ($coursehash{'default_enrollment_end_date'} == 0) {
                    $endaccess = &mt('No ending date');
                }
            }
            if ($startaccess) {
                $accessdates .= '<i>'.&mt('From:[_1]','</i> '.$startaccess).'<br />';
            }
            if ($endaccess) {
                $accessdates .= '<i>'.&mt('To:[_1]','</i> '.$endaccess).'<br />';
            }
            if (($selfenroll_types ne '') && 
                ($selfenroll_end > 0 && $selfenroll_end > $now)) {
                my ($selfenroll_start_access,$selfenroll_end_access);
                if (($coursehash{'default_enrollment_start_date'} ne 
                     $coursehash{'internal.selfenroll_start_access'}) ||
                   ($coursehash{'default_enrollment_end_date'} ne 
                    $coursehash{'internal.selfenroll_end_access'})) {
                    if ( defined($coursehash{'internal.selfenroll_start_access'}) ) {
                        $selfenroll_start_access = &Apache::lonlocal::locallocaltime($coursehash{'internal.selfenroll_start_access'});
                    }
                    if ( defined($coursehash{'default_enrollment_end_date'}) ) {
                        $selfenroll_end_access = &Apache::lonlocal::locallocaltime($coursehash{'internal.selfenroll_end_access'});
                        if ($coursehash{'internal.selfenroll_end_access'} == 0) {
                            $selfenroll_end_access = &mt('No ending date');
                        }
                    }
                    if ($selfenroll_start_access || $selfenroll_end_access) {
                        $accessdates .= '<br/><br /><i>'.&mt('Self-enrollers:').'</i><br />';
                        if ($selfenroll_start_access) {
                            $accessdates .= '<i>'.&mt('From:[_1]','</i> '.$selfenroll_start_access).'<br />';
                        }
                        if ($selfenroll_end_access) {
                            $accessdates .= '<i>'.&mt('To:[_1]','</i> '.$selfenroll_end_access).'<br />';
                        }
                    }
                }
            }
            $courseinfo{$course}{'access'} = $accessdates;
        }
        if ($xlist_items eq '') {
            $xlist_items = &mt('No');
        }
        $courseinfo{$course}{'xlist'} = $xlist_items;
    }
    return %courseinfo;
}

sub count_students {
    my ($cdom,$cnum,$numsec) = @_;
    my $classlist = &Apache::loncoursedata::get_classlist($cdom,$cnum);
    my %student_count = (
                           Active => 0,
                           Future => 0,
                           Expired => 0,
                       );
    my %idx;
    $idx{'status'} = &Apache::loncoursedata::CL_STATUS();
    my %status_title = &Apache::lonlocal::texthash(
                           Expired => 'Previous access',
                           Active => 'Current access',
                           Future => 'Future access',
                       );

    while (my ($student,$data) = each(%$classlist)) {
        $student_count{$data->[$idx{'status'}]} ++;
    }

    my $countslist = &mt('[quant,_1,section:,sections:,No sections]',$numsec).'<br />';
    foreach my $status ('Active','Future') {
        $countslist .= '<span class="LC_nobreak">'.$status_title{$status}.': '.
                       $student_count{$status}.'</span><br />';
    }
    return $countslist;
}

sub courseinfo_row {
    my ($info,$knownuser,$details,$countref,$now,$course,$trails,$allitems) = @_;
    my ($cdom,$cnum,$title,$ownerlast,$code,$owner,$seclist,$xlist_items,
        $accessdates,$showsyllabus,$counts,$autoenrollment,$output,$categories);
    if (ref($info) eq 'HASH') {
        $cdom = $info->{'cdom'};
        $cnum = $info->{'cnum'};
        $title = $info->{'title'};
        $ownerlast = $info->{'ownerlastnames'};
        $code = $info->{'code'};
        $owner = $info->{'owner'};
        $seclist = $info->{'seclist'};
        $xlist_items = $info->{'xlist'};
        $accessdates = $info->{'access'};
        $counts = $info->{'counts'};
        $autoenrollment = $info->{'autoenrollment'};
        $showsyllabus = $info->{'showsyllabus'};
        $categories = $info->{'categories'};
    } else {
        $output = '<td colspan="8">'.&mt('No information available for [_1].',
                                         $code).'</td>';
        return $output;
    }
    $output .= '<td>'.$$countref.'</td>';
    if ($env{'form.currcat_0'} eq 'instcode::0') {
        $output .= '<td>'.$code.'</td>';
    } else {
        my ($categorylist,@cats);
        if ($categories ne '') {
            @cats = split('&',$categories);
        }
        if ((ref($trails) eq 'ARRAY') && (ref($allitems) eq 'HASH')) {
            my @categories = map { $trails->[$allitems->{$_}]; } @cats;
            $categorylist = join('<br />',@categories);
        }
        if ($categorylist eq '') {
            $categorylist = '&nbsp;';
        }
        $output .= '<td>'.$categorylist.'</td>';
    }
    $output .= '<td>'.$seclist.'</td>'.
               '<td>'.$xlist_items.'</td>'.
               '<td>'.$title.'&nbsp;<font size="-2">';
    if ($showsyllabus) {
        $output .= '<a href="javascript:ToSyllabus('."'$cdom','$cnum'".')">'.&mt('Syllabus').'</a>';
    } else {
        $output .= '&nbsp;';
    }
    $output .= '</font></td>'.
               '<td>'.$ownerlast.'</td>';
    if ($knownuser) {
        if ($details) {
            if ($env{'form.currcat_0'} eq 'communities::0') {
                $output .= '<td>'.$accessdates.'</td>';
            } else { 
                $output .=
                    '<td>'.$accessdates.'</td>'. 
                    '<td>'.$counts.'</td>'.
                    '<td>'.$autoenrollment.'</td>';
            }
        } else {
            $output .= "<td><a href=\"javascript:setCourseId('$cnum')\">".&mt('Show more details').'</a></td>';
        }
    }
    my $selfenroll;
    if ($info->{'selfenroll_types'}) {
        my $showstart = &Apache::lonlocal::locallocaltime($info->{'selfenroll_start'});
        my $showend = &Apache::lonlocal::locallocaltime($info->{'selfenroll_end'});
        if (($info->{'selfenroll_end'} > 0) && ($info->{'selfenroll_end'} > $now)) {
            if (($info->{'selfenroll_start'} > 0) && ($info->{'selfenroll_start'} > $now)) {
                $output .= '<td>'.&mt('Starts: [_1]','<span class="LC_cusr_emph">'.$showstart.'</span>').'<br />'.&mt('Ends: [_1]','<span class="LC_cusr_emph">'.$showend.'</span>').'</td>';
            } else { 
                $output .= '<td><a href="javascript:ToSelfenroll('."'$course'".')">'.&mt('Enroll in course').'</a></td>';
            }
            $selfenroll = 1;
        }
    }
    if (!$selfenroll) {
        $output .= '<td>&nbsp;</td>';
    }
    $$countref ++;
    return $output;
}

sub identify_sections {
    my ($seclist) = @_;
    my @secnums;
    if ($seclist =~ /,/) {
        my @sections = split(/,/,$seclist);
        foreach my $sec (@sections) {
            $sec =~ s/:[^:]*$//;
            push(@secnums,$sec);
        }
    } else {
        if ($seclist =~ m/^([^:]+):/) {
            my $sec = $1;
            if (!grep(/^\Q$sec\E$/,@secnums)) {
                push(@secnums,$sec);
            }
        }
    }
    @secnums = sort {$a <=> $b} @secnums;
    $seclist = join(', ',@secnums);
    my $numsec = @secnums;
    return ($seclist,$numsec);
}

sub get_valid_classes {
    my ($seclist,$xlist_items,$crscode,$owners,$cdom,$cnum) = @_;
    my $response;
    my %validations;
    @{$validations{'sections'}} = ();
    @{$validations{'xlists'}} = ();
    my $totalitems = 0;
    if ($seclist) {
        foreach my $sec (split(/, /,$seclist)) {
            my $class = $crscode.$sec;
            if (&Apache::lonnet::auto_validate_class_sec($cdom,$cnum,$owners,
							 $class) eq 'ok') {
                if (!grep(/^\Q$sec$\E/,@{$validations{'sections'}})) {
                    push(@{$validations{'sections'}},$sec);
                    $totalitems ++;
                }
            }
        }
    }
    if ($xlist_items) {
        foreach my $item (split(/, /,$xlist_items)) {
            if (&Apache::lonnet::auto_validate_class_sec($cdom,$cnum,$owners,
							 $item) eq 'ok') {
                if (!grep(/^\Q$item$\E/,@{$validations{'xlists'}})) {
                    push(@{$validations{'xlists'}},$item);
                    $totalitems ++;
                }
            }
        }
    }
    if ($totalitems > 0) {
        if (@{$validations{'sections'}}) {
            $response = &mt('Sections:').' '.
                        join(', ',@{$validations{'sections'}}).'<br />';
        }
        if (@{$validations{'xlists'}}) {
            $response .= &mt('Courses:').' '.
                        join(', ',@{$validations{'xlists'}});
        }
    }
    return $response;
}

sub autoenroll_info {
    my ($coursehash,$now,$seclist,$xlist_items,$code,$owners,$cdom,$cnum) = @_;
    my $autoenrolldates = &mt('Not enabled');
    if (defined($coursehash->{'internal.autoadds'}) && $coursehash->{'internal.autoadds'} == 1) {
        my ($autostart,$autoend);
        if ( defined($coursehash->{'internal.autostart'}) ) {
            $autostart = &Apache::lonlocal::locallocaltime($coursehash->{'internal.autostart'});
        }
        if ( defined($coursehash->{'internal.autoend'}) ) {
            $autoend = &Apache::lonlocal::locallocaltime($coursehash->{'internal.autoend'});
        }
        if ($coursehash->{'internal.autostart'} > $now) {
            if ($coursehash->{'internal.autoend'} && $coursehash->{'internal.autoend'} < $now) {
                $autoenrolldates = &mt('Not enabled');
            } else {
                my $valid_classes = 
                   &get_valid_classes($seclist,$xlist_items,$code,
                                      $owners,$cdom,$cnum);
                if ($valid_classes ne '') {
                    $autoenrolldates = &mt('Not enabled').'<br />'
                                      .&mt('Starts: [_1]',$autostart)
                                      .'<br />'.$valid_classes;
                }
            }
        } else {
            if ($coursehash->{'internal.autoend'} && $coursehash->{'internal.autoend'} < $now) {
                $autoenrolldates = &mt('Not enabled').'<br />'
                                  .&mt('Ended: [_1]',$autoend);
            } else {
                my $valid_classes = &get_valid_classes($seclist,$xlist_items,
                                                       $code,$owners,$cdom,$cnum);
                if ($valid_classes ne '') {
                    $autoenrolldates = &mt('Currently enabled').'<br />'.
                                       $valid_classes;
                }
            }
        }
    }
    return $autoenrolldates;
}

sub user_is_known {
    my $known = 0;
    if ($env{'user.name'} ne '' && $env{'user.name'} ne 'public' 
        && $env{'user.domain'} ne '' && $env{'user.domain'} ne 'public') {
        $known = 1;
    }
    return $known;
}

1;

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