File:  [LON-CAPA] / loncom / interface / lonpickcourse.pm
Revision 1.127: download - view: text, annotated - select for diffs
Sat Apr 8 14:28:56 2017 UTC (7 years, 8 months ago) by raeburn
Branches: MAIN
CVS tags: version_2_12_X, version_2_11_X, version_2_11_5_msu, version_2_11_5, version_2_11_4_uiuc, version_2_11_4_msu, version_2_11_4, version_2_11_3_uiuc, version_2_11_3_msu, version_2_11_3, version_2_11_2_uiuc, version_2_11_2_msu, version_2_11_2_educog, version_2_11_2, HEAD
- Hide role selection text used in modal window until needed.

# The LearningOnline Network
# Pick a course
#
# $Id: lonpickcourse.pm,v 1.127 2017/04/08 14:28:56 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::lonpickcourse;

use strict;
use Apache::Constants qw(:common);
use Apache::loncommon;
use Apache::lonhtmlcommon;
use Apache::loncoursedata;
use Apache::lonnet;
use Apache::lonlocal;
use Apache::longroup;
use LONCAPA qw(:DEFAULT :match);
use JSON::DWIW;

sub handler {
    my $r = shift;
    if ($env{'form.context'} eq 'adhoc') {
        &Apache::loncommon::content_type($r,'application/json');
        $r->send_http_header;
        my ($possroles,$description) = &Apache::lonnet::get_my_adhocroles($env{'form.cid'},1);
        if ((ref($possroles) eq 'ARRAY') && (ref($description) eq 'HASH')) {
            my $response = [];
            if (@{$possroles}) {
                foreach my $role (@{$possroles}) {
                    push(@{$response},
                                      { name => $role,
                                        desc => $description->{$role},
                                      });
                }
            }
            $r->print(JSON::DWIW->to_json({roles => $response}));
        }
        return OK;
    }
    &Apache::loncommon::content_type($r,'text/html');
    $r->send_http_header;
    return OK if $r->header_only;
    
# ------------------------------------------------------------ Print the screen

    # Get parameters from query string
    &Apache::loncommon::get_unprocessed_cgi
        ($ENV{'QUERY_STRING'},['domainfilter','form','cnumelement',
			       'cdomelement','cnameelement','roleelement',
                               'multiple','type','setroles','fixeddom','cloner',
                               'crscode','crsdom']);
    my ($type,$title,$jscript,$multelement,$multiple,$roleelement,$typeelement,
        $lastaction,$autosubmit,$submitopener,$cloneruname,$clonerudom,$crscode,
        $crsdom,$rolechooser);

    # Get course type - Course, Community or Placement.
    $type = $env{'form.type'};
    if (!defined($env{'form.type'})) {
        $type = 'Course';
    }
    $title = 'Selecting a '.$type;

    # Setup for multiple course selections, if flag for multiples set.
    $multiple = $env{'form.multiple'};
    if ($multiple) {
        ($jscript,$multelement) = &multiples_tag();
        $title = 'Selecting '.$type.'(s)';
    }

    # if called when a DC, DH or DA is selecting a course 
    my ($roledom,$rolename) = split(/:/,$env{'form.roleelement'});
    if ($roledom) {
        $roleelement = '<input type="hidden" name="roleelement" value="'.$env{'form.roleelement'}.'" />';
        $submitopener = &processpick();
        $autosubmit = 'process_pick("'.$roledom.'","'.$rolename.'")';
        if (($rolename eq 'dh') || ($rolename eq 'da')) {
            my %lt = &Apache::lonlocal::texthash(
                     title    => 'Ad hoc role selection',
                     preamble => 'Please choose an ad hoc role in the course.',
                     cancel   => 'Click "OK" to enter the course, or "Cancel" to choose a different course.',
            );

            $rolechooser = <<"END";
<div id="LC_adhocrole_chooser" title="$lt{'title'}" style="display:none">
  <p>$lt{'preamble'}</p>
  <form name="LChelpdeskadhoc" id="LChelpdeskpicker" action="">
    <div id="LC_choose_adhoc">
    </div>
    <input type="submit" tabindex="-1" style="position:absolute; top:-1000px" />
  </form>
  <p>$lt{'cancel'}</p>
</div>
END
        }
    }
    if ($env{'form.typeelement'} ne '') {
        $typeelement = '<input type="hidden" name="typeelement" value="'.$env{'form.typeelement'}.'" />';
    }

    # if called when a DC is creating a course for another user.
    if ($env{'form.form'} eq 'ccrs') {
        ($cloneruname,$clonerudom) = ($env{'form.cloner'} =~ /^($match_username):($match_domain)$/);
        $crscode = $env{'form.crscode'};
        $crsdom = $env{'request.role.domain'};
    }

    # if called when requesting a course
    if ($env{'form.form'} eq 'requestcrs') {
        $cloneruname = $env{'user.name'};
        $clonerudom =  $env{'user.domain'};
        $crscode = $env{'form.crscode'};
        $crsdom = $env{'form.crsdom'};
    }

    my $onlyown = 0;
    # if called to assign course-based portfolio access control
    if ((($env{'form.form'} eq 'portform') && (!$env{'user.adv'}))) {
        $onlyown = 1;
    }

    my %loaditem;
    if (($env{'form.type'} eq 'Course') && ($env{'form.numtitles'})) {
        if (($env{'form.official'} eq 'on') && ($env{'form.state'} eq 'listing')) {
            $loaditem{'onload'} = 'setElements(document.filterpicker); ';
        }
    }

    if ((($env{'form.form'} eq 'cu') || ($env{'form.form'} eq 'studentform')) && 
        ($env{'form.pickedcourse'})) {
        if ($type ne 'Community') {
            my %coursedescription =
                &Apache::lonnet::coursedescription($env{'form.pickedcourse'},
                                                   {'one_time' => '1'});
            my $cdom = $coursedescription{'domain'};
            my %domdefs = &Apache::lonnet::get_domain_defaults($cdom);
            if (($domdefs{'officialcredits'} || $domdefs{'unofficialcredits'} || $domdefs{'textbookcredits'})) {
                $loaditem{'onload'} .= 'setDefaultCredits();';
            }
        }
        $loaditem{'onload'} .= 'setRoles();setSections();';
    }
    if ((($env{'form.gosearch'}) && ($env{'form.updater'} eq '')) && (!$onlyown)) {
        $loaditem{'onload'} .=  'hideSearching(); ';
    }
    my $js = &Apache::loncommon::js_changer();
    $r->print(&Apache::loncommon::start_page($title,$js,
					     {'add_entries' => \%loaditem,
					      'no_nav_bar'  => 1, }));

    if ($env{'form.form'} eq 'portform') {
        $lastaction = 'document.courselist.submit()';
    } elsif ($env{'form.form'} eq 'cu' || ($env{'form.form'} eq 'studentform' &&
        !$multiple)) {
        $lastaction = 
             'document.courselist.pickedcourse.value = cdom+"_"+cname;'."\n".
             'document.courselist.submit();';
    } else {
        $lastaction = 'self.close()';
    }

    # if called to assign a role in a course to a user via CUSR
    if ($env{'form.form'} eq 'cu' || $env{'form.form'} eq 'studentform') {
        $r->print(&create_user_javascript($type));
    }

    # print javascript functions for choosing a course 
    if ((($env{'form.gosearch'}) && ($env{'form.updater'} eq '')) || 
        $onlyown) {
        $r->print(&gochoose_javascript($type,$multiple,$autosubmit,$lastaction,
                                       $rolename,$rolechooser));
    }
    $r->print(&Apache::lonhtmlcommon::scripttag($jscript));
    $r->print($submitopener);

# ------------------------------------------ Display of filters to limit search
    my $filter = {};
    my $action = '/adm/pickcourse';
    my ($numtitles,$showroles,$nohost,@codetitles);
    unless ($onlyown) {
        my $filterlist = ['domainfilter','sincefilter'];
        # created filter for DCs only
        if ($env{'user.adv'} && $env{'form.domainfilter'} &&
            exists($env{'user.role.dc./'.$env{'form.domainfilter'}.'/'})
            && $env{'form.form'} ne 'portform') {
            my $loncaparev = &Apache::lonnet::get_server_loncaparev($env{'form.domainfilter'});
            if ($loncaparev ne 'unknown_cmd') {
                push(@{$filterlist},'createdfilter');
            }
        }
        push(@{$filterlist},('descriptfilter','instcodefilter'));
        if ($env{'form.form'} eq 'rules') {
            push(@{$filterlist},('personfilter','persondomfilter'));
            if ($env{'form.persondomfilter'} eq '') {
                unless ($env{'form.gosearch'}) {
                    $filter->{'persondomfilter'} = $env{'request.role.domain'};
                }
            } else {
                $filter->{'persondomfilter'} =
                    &LONCAPA::clean_domain($env{'form.persondomfilter'});
            }
            if (($env{'form.personfilter'} ne '') && ($env{'form.persondomfilter'} ne '')) {
                if (&Apache::lonnet::homeserver($env{'form.personfilter'},
                                                 $env{'form.persondomfilter'}) eq 'no_host') {
                    $nohost = 1;
                } else {
                    $showroles = 1;
                } 
            }
        } else {
            push(@{$filterlist},('ownerfilter','ownerdomfilter'));
        }
        # course ID filter for DCs only
        if ($env{'user.adv'} && $env{'form.domainfilter'} &&
            exists($env{'user.role.dc./'.$env{'form.domainfilter'}.'/'})) {
            push(@{$filterlist},'coursefilter');
        }
        if ($cloneruname ne '' && $clonerudom ne '') {
            push(@{$filterlist},'cloneableonly');
        }
        if ((ref($filterlist) eq 'ARRAY') && (ref($filter) eq 'HASH')) {
            foreach my $item (@{$filterlist}) {
                $filter->{$item} = $env{'form.'.$item};
            }
        }
        if ($env{'form.form'} eq 'portform') {
            $filter->{'domainfilter'} ||= $env{'user.domain'};
        } elsif ($env{'form.form'} eq 'studentform') {
            $filter->{'domainfilter'} ||= $env{'request.role.domain'};
        }
        my $codedom;
        if ($env{'form.fixeddom'}) {
            $codedom = $env{'request.role.domain'};
        } else {
            $codedom = $filter->{'domainfilter'};
        }
        my ($clonetext,$clonewarning);
        if (($env{'form.form'} eq 'ccrs') || ($env{'form.form'} eq 'requestcrs')) {
            (my $coord_cloneable,$clonewarning) =
                &get_coordinator_cloneable($cloneruname,$clonerudom,$type);
            if ($env{'form.form'} eq 'ccrs') {
                $clonetext = '<input type="hidden" name="cloner" value="'.$env{'form.cloner'}.'" />'."\n";
            }
            if ($coord_cloneable) {
                $clonetext .= '<input type="hidden" name="cc_clone" value="'.$coord_cloneable.'" />';
            }
            if ($crscode ne '') {
                $clonetext .= '<input type="hidden" name="crscode" value="'.$crscode.'" />';
            }
            if ($crsdom ne '') {
                $clonetext .= '<input type="hidden" name="crsdom" value="'.$crsdom.'" />';
            }
        }
        $r->print(&Apache::loncommon::build_filters($filterlist,$type,$roleelement,$multelement,
                                                    $filter,$action,\$numtitles,undef,$cloneruname,
                                                    $clonerudom,$typeelement,\@codetitles,$codedom,
                                                    $env{'form.form'},$env{'form.fixeddom'},
                                                    $env{'form.prevphase'},$env{'form.cnameelement'},
                                                    $env{'form.cnumelement'},$env{'form.cdomelement'},
                                                    $env{'form.setroles'},$clonetext,$clonewarning));
    }

# ---------------------------------------------------------------- Get the data
    if ((($env{'form.gosearch'}) && ($env{'form.updater'} eq '')) || 
         $onlyown) {
        my $domcloner;
        if ($env{'form.form'} eq 'ccrs') {
            if (($env{'request.role.domain'} eq $env{'form.domainfilter'}) &&
                (&Apache::lonnet::allowed('ccc',$env{'request.role.domain'}))) {
                $domcloner = 1;
            }
        }
        my %courses;
        if (!$onlyown) {
            $r->print('<div id="searching">'.&mt('Searching ...').'</div>');
            $r->rflush();
            my $srchdom = $filter->{'domainfilter'};
            %courses = &Apache::loncommon::search_courses($srchdom,$type,$filter,$numtitles,
                                                          $cloneruname,$clonerudom,$domcloner,
                                                          \@codetitles,$env{'form.cc_clone'},
                                                          $crsdom,$crscode);
        } else {
            $r->print('<br />');
            my %coursehash = &Apache::loncommon::findallcourses();
            foreach my $cid (sort(keys(%coursehash))) {
                $courses{$cid}{'description'} = $env{'course.'.$cid.'.description'};
            }
        }
        if ($nohost) {
            $r->print ('<span class="LC_warning">'.
                       &mt('User does not exist - username: [_1], domain: [_2].',
                           '<b>'.$filter->{'personfilter'}.'</b>',
                           '<b>'.$filter->{'persondomfilter'}.'</b>').'</span>');
        } else {
            &display_matched_courses($r,$type,$multiple,$action,$showroles,$cloneruname,
                                     $clonerudom,$crsdom,$crscode,%courses);
        }
    }
    $r->print(&Apache::loncommon::end_page());
    return OK;
}

sub processpick {
    my $openerform = 'rolechoice';
    if ($env{'form.form'} eq 'studentform') {
        $openerform = $env{'form.form'};
    }
    my $process_pick = <<"ENDONE";
<script type="text/javascript">
function process_pick(dom,rolename) {
    var pickedCourse=opener.document.$openerform.$env{'form.cnumelement'}.value;
    var pickedDomain=opener.document.$openerform.$env{'form.cdomelement'}.value;
    var okDomain = 0;
ENDONE
    if ($openerform eq 'rolechoice') {
        $process_pick .= <<"ENDTWO";
    if (pickedDomain == dom) {
        if (pickedCourse != '') {
            var courseTarget; 
            if (rolename == 'cc') {
                var ccrole = "cc";
                var pickedType = "$env{'form.type'}";
                if (pickedType == "Community") {
                    ccrole = "co";
                }
                courseTarget = ccrole+"./"+pickedDomain+"/"+pickedCourse;
            } else {
                if (!/\\W/.test(rolename)) {
                    courseTarget = "cr/"+pickedDomain+"/"+pickedDomain+"-domainconfig/"+rolename+"./"+pickedDomain+"/"+pickedCourse;
                }
            }
            if ((courseTarget != '') && (courseTarget != undefined)) { 
                opener.document.title='Role selected. Please stand by.';
                opener.status='Role selected. Please stand by.';
                opener.document.rolechoice.newrole.value=courseTarget;
                opener.document.rolechoice.submit();
            } else {
                alert("Invalid role selection");
                return;
            }
        }
    }
    else {
        alert("You may only use this screen to select courses in the current domain: "+dom+"\\nPlease return to the roles page window and click the 'Select Course' link for domain: "+pickedDomain+",\\n if you are a Domain Coordinator in that domain, and wish to become a Course Coordinator in a course in the domain");
    }
ENDTWO
    } else {
        $process_pick .= <<"ENDTHREE";
    if (pickedDomain != dom) {
        alert("You may only use this screen to select courses in the current domain: "+dom+"\\nPlease return to the roles page window and click the 'Select Course' link for domain: "+pickedDomain+",\\n if you are a Domain Coordinator in that domain, and wish to become a Course Coordinator in a course in the domain");
        return;
    }
ENDTHREE
    }
    $process_pick .= "
}

</script>
";
    return $process_pick;
}

sub create_user_javascript {
    my ($type) = @_;
    my $output;
    #javascript for reporting sections and groups then closing
    if ($env{'form.pickedcourse'}) {
        my %coursedescription = 
            &Apache::lonnet::coursedescription($env{'form.pickedcourse'},
                                               {'one_time' => '1'});
        my $cdom = $coursedescription{'domain'};
        my $cnum = $coursedescription{'num'};
        my $crstype = $coursedescription{'type'};
        my %domdefs = &Apache::lonnet::get_domain_defaults($cdom);
        my ($showcredits,$credits);
        if (($crstype ne 'Community') &&
            (($domdefs{'officialcredits'} || $domdefs{'unofficialcredits'} || $domdefs{'textbookcredits'}))) {
            $showcredits = 1; 
            $credits = $coursedescription{'internal.defaultcredits'};
        }
        my $sec_element = 'currsec';
        my $grplist_element = 'groups';
        my ($sections,$groups) =
          &Apache::loncommon::get_secgrprole_info($cdom,$cnum,'',$type);
        my $num_sections = scalar(@{$sections});
        my $seclist = join(',',@{$sections});
        my $num_groups = scalar(@{$groups});
        my $groupslist = join(',',@{$groups});
        $output = qq|
<script type="text/javascript">
// <![CDATA[
function setSections() {
    opener.document.$env{"form.form"}.$grplist_element.value='$groupslist';
    window.opener.setSect('$seclist');
    self.close();
}
function setRoles() {
    window.opener.setRole('$crstype');
}
|;
        if ($showcredits) {
            $output .= qq|
function setDefaultCredits() {
    window.opener.setCredits('$credits');
}
|;
        }
        $output .= qq|
// ]]>
</script>
|;
    }
    return $output;
}

sub display_matched_courses {
    my ($r,$type,$multiple,$action,$showroles,$cloneruname,$clonerudom,$crsdom,$crscode,%courses) = @_;
    if ($env{'form.form'} eq 'portform') {
        $action = '/adm/portfolio';
    }
    my $numcourses = keys(%courses);
    $r->print('<form name="courselist" method="post" action="'.$action.'" id="LCcoursepicker">');
    if ($env{'form.form'} eq 'modifycourse') {
        if ($numcourses > 0) {
            my $ccrole = 'cc';
            if ($type eq 'Community') {
                $ccrole = 'co';
            }
            my $cctitle = &Apache::lonnet::plaintext($ccrole,$type);
            my $dctitle = &Apache::lonnet::plaintext('dc');
            my $ccrolechk = ' ';
            my $possrole;
            my $menuchk = ' checked="checked" ';
            $r->print(
                '<div class="LC_left_float">'
               .'<fieldset>'
               .'<legend>'.&mt('Pick action').'</legend>');
            my $roleradio = '<span class="LC_nobreak"><label>'.
                            '<input type="radio" name="phase" value="adhocrole"'.$ccrolechk.'/>'.'&nbsp;';
            if (&Apache::lonnet::allowed('ccc',$crsdom)) {
                $possrole = 1;
                $r->print($roleradio);
                if ($type eq 'Community') {
                    $r->print(&mt('Enter the community with the role of [_1].',$cctitle));
                } elsif ($type eq 'Placement') {
                    $r->print(&mt('Enter the placement test with the role of [_1].',$cctitle));
                } else {
                    $r->print(&mt('Enter the course with the role of [_1].',$cctitle));
                }
            } elsif (&Apache::lonnet::allowed('rar',$crsdom)) {
                my ($roles_by_num,$description,$accessref,$accessinfo) = &Apache::lonnet::get_all_adhocroles($crsdom);
                if ((ref($roles_by_num) eq 'ARRAY') && (ref($description) eq 'HASH')) {
                    if (@{$roles_by_num} > 1) {
                        $r->print($roleradio);
                        if ($type eq 'Community') {
                            $r->print(&mt('Enter the community with one of the available ad hoc roles.'));
                        } elsif ($type eq 'Placement') {
                            $r->print(&mt('Enter the placement test with one of the available ad hoc roles.'));
                        } else {
                            $r->print(&mt('Enter the course with one of the available ad hoc roles.'));
                        }
                        $possrole = 1;
                    } elsif (@{$roles_by_num} == 1) {
                        $r->print($roleradio);
                        my $rolename = $description->{$roles_by_num->[0]};
                        if ($type eq 'Community') {
                            $r->print(&mt('Enter the community with the ad hoc role of: [_1]',$rolename));
                        } elsif ($type eq 'Placement') {
                            $r->print(&mt('Enter the placement test with the ad hoc role of: [_1]',$rolename));
                        } else {
                            $r->print(&mt('Enter the course with the ad hoc role of: [_1]',$rolename));
                        }
                        $possrole = 1;
                    }
                    if ($possrole) {
                        $r->print('<input type="hidden" name="adhocrole" value="" />');
                    }
                }
            }
            if ($possrole) {
                $r->print('</label></span><br />');
            }
            $r->print('<span class="LC_nobreak"><label>'
                     .'<input type="radio" name="phase" value="menu"'.$menuchk.'/>&nbsp;');
            if (&Apache::lonnet::allowed('ccc',$crsdom)) {
                if ($type eq 'Community') {
                    $r->print(&mt('View or modify community settings which only a [_1] may modify.',$dctitle));
                } elsif ($type eq 'Placement') {
                    $r->print(&mt('View or modify placement test settings which only a [_1] may modify.',$dctitle));
                } else {
                    $r->print(&mt('View or modify course settings which only a [_1] may modify.',$dctitle));
                }
            } elsif (&Apache::lonnet::allowed('rar',$crsdom)) {
                if ($type eq 'Community') {
                    $r->print(&mt('View community settings which only a [_1] may modify.',$dctitle));
                } elsif ($type eq 'Placement') {
                    $r->print(&mt('View placement test settings which only a [_1] may modify.',$dctitle));
                } else {
                    $r->print(&mt('View course settings which only a [_1] may modify.',$dctitle));
                }
            }
            $r->print('</label></span>'
                     .'</fieldset></div>'
                     .'<br clear="all" />'
                     );
        }
    }
    my %by_descrip;
    foreach my $course (keys(%courses)) {
        my $descr;
        if (ref($courses{$course}) eq 'HASH') {
            $descr = $courses{$course}{'description'};
        } elsif ($courses{$course} =~ m/^([^:]*):/i) {
            $descr = &unescape($1);
        } else {
            $descr = &unescape($courses{$course});
        }
        my $description = $descr;
        push (@{$by_descrip{$description}}, $course);
    }
 
    if ($numcourses > 1 && $multiple) {
        $r->print('<input type="button" value="'.&mt('check all').'"
                  onclick="javascript:checkAll(document.courselist.course_id)" />
                  &nbsp;&nbsp;<input type="button" value="'.&mt('uncheck all').'"
                  onclick="javascript:uncheckAll(document.courselist.course_id)" />
                  <br /><br />');
    }

    if (%courses) {
        $r->print(&Apache::loncommon::start_data_table());
        $r->print(&Apache::loncommon::start_data_table_header_row());
        my $titlehdr = &mt('Course Title');
        if ($type eq 'Community') {
            $titlehdr = &mt('Community Title');
        }
        $r->print('<th>'.&mt('Select').'</th>'
                 .'<th>'.$titlehdr.'</th>'
                 .'<th>'.&mt('Domain').'</th>');
        unless (($type eq 'Community') || ($type eq 'Placement')) {
            $r->print('<th>'.&mt('Course Code').'</th>');
        }
        $r->print('<th>'.&mt('Owner/Co-owner(s)').'</th>');
        if ($showroles) {
            $r->print('<th>'.&mt("Role(s) for [_1]",
                &Apache::loncommon::plainname($env{'form.personfilter'},
                                              $env{'form.persondomfilter'},'firstname')).'</th>');
        }
        $r->print(&Apache::loncommon::end_data_table_header_row());
    }
    my %cc_cloneable;
    if (($env{'form.form'} eq 'ccrs') || ($env{'form.form'} eq 'requestcrs')) {
        my ($coord_cloneable,$warning) =
            &get_coordinator_cloneable($cloneruname,$clonerudom,$type);
        if ($coord_cloneable) {
            map {$cc_cloneable{$_} = 1;} split('&',$coord_cloneable);
        }
    }
    my (%gotdomdefaults,%gotcodedefaults);
    foreach my $description (sort { lc($a) cmp lc($b) } (keys(%by_descrip))) {
        foreach my $course (@{$by_descrip{$description}}) {
            $r->print(&Apache::loncommon::start_data_table_row());
            my $cleandesc=&HTML::Entities::encode($description,'<>&"');
            $cleandesc=~s/'/\\'/g;
            my ($cdom,$cnum)=split(/\_/,$course);
            my ($descr,$instcode,$ttype,$canclone,@owners);
            if (ref($courses{$course}) eq 'HASH') {
                $descr = $courses{$course}{'description'};
                $instcode = $courses{$course}{'inst_code'};
                $ttype = $courses{$course}{'type'};
                if (($env{'form.form'} eq 'ccrs') || ($env{'form.form'} eq 'requestcrs')) {
                    if ($env{'form.form'} eq 'ccrs') {
                        if (($env{'request.role.domain'} eq $cdom) &&
                            (&Apache::lonnet::allowed('ccc',$env{'request.role.domain'}))) {
                            $canclone = 1;
                        }
                    }
                    unless ($canclone) { 
                        if ($cc_cloneable{$cnum.':'.$cdom}) {
                            $canclone = 1;
                        }
                    }
                    unless ($canclone) {
                        my $cloners = $courses{$course}{'cloners'};
                        if ($cloners ne '') {
                            my @cloneable = split(',',$cloners);
                            if (grep(/^\*$/,@cloneable)) {
                                $canclone = 1;
                            }
                            if (grep(/^\*:\Q$clonerudom\E$/,@cloneable)) {
                                $canclone = 1;
                            }
                            if (grep(/^\Q$cloneruname\E:\Q$clonerudom\E$/,@cloneable)) {
                                $canclone = 1;
                            }
                            unless ($canclone) {
                                if (($instcode) && ($crscode) && ($cdom eq $crsdom)) {
                                    foreach my $cloner (@cloneable) {
                                        if (($cloner ne '*') && ($cloner !~ /^\*\:$match_domain$/) &&
                                            ($cloner !~ /^$match_username\:$match_domain$/) && ($cloner ne '')) {
                                            if ($cloner =~ /\=/) {
                                                my (%codedefaults,@code_order);
                                                if (ref($gotcodedefaults{$cdom}) eq 'HASH') {
                                                    if (ref($gotcodedefaults{$cdom}{'defaults'}) eq 'HASH') {
                                                        %codedefaults = %{$gotcodedefaults{$cdom}{'defaults'}};
                                                    }
                                                    if (ref($gotcodedefaults{$cdom}{'order'}) eq 'ARRAY') {
                                                        @code_order = @{$gotcodedefaults{$cdom}{'order'}};
                                                    }
                                                } else {
                                                    &Apache::lonnet::auto_instcode_defaults($cdom,
                                                                                            \%codedefaults,
                                                                                            \@code_order);
                                                    $gotcodedefaults{$cdom}{'defaults'} = \%codedefaults;
                                                    $gotcodedefaults{$cdom}{'order'} = \@code_order;
                                                }
                                                if (@code_order > 0) {
                                                    if (&Apache::lonnet::check_instcode_cloning(\%codedefaults,\@code_order,
                                                                                                $cloner,$instcode,$crscode)) {
                                                        $canclone = 1;
                                                        last;
                                                    }
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                        } else {
                            my %domdefs;
                            if (ref($gotdomdefaults{$cdom}) eq 'HASH') {
                                %domdefs = %{$gotdomdefaults{$cdom}};
                            } else {
                                %domdefs = &Apache::lonnet::get_domain_defaults($cdom);
                                $gotdomdefaults{$cdom} = \%domdefs;
                            }
                            if ($domdefs{'canclone'}) {
                                unless ($domdefs{'canclone'} eq 'none') {
                                    if ($domdefs{'canclone'} eq 'domain') {
                                        if ($clonerudom eq $cdom) {
                                            $canclone = 1;
                                        }
                                    } elsif (($instcode) && ($crscode) &&
                                             ($cdom eq $crsdom)) {
                                        my (%codedefaults,@code_order); 
                                        if (ref($gotcodedefaults{$cdom}) eq 'HASH') {
                                            if (ref($gotcodedefaults{$cdom}{'defaults'}) eq 'HASH') {
                                                %codedefaults = %{$gotcodedefaults{$cdom}{'defaults'}};
                                            }
                                            if (ref($gotcodedefaults{$cdom}{'order'}) eq 'ARRAY') {
                                                @code_order = @{$gotcodedefaults{$cdom}{'order'}};
                                            }
                                        } else {
                                            &Apache::lonnet::auto_instcode_defaults($cdom,
                                                                                    \%codedefaults,
                                                                                    \@code_order);
                                            $gotcodedefaults{$cdom}{'defaults'} = \%codedefaults;
                                            $gotcodedefaults{$cdom}{'order'} = \@code_order;
                                        }
                                        if (@code_order > 0) {
                                            if (&Apache::lonnet::default_instcode_cloning($cdom,$domdefs{'canclone'},
                                                                                          $instcode,$crscode,\%codedefaults,
                                                                                          \@code_order)) {
                                                $canclone = 1;
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
                push(@owners,$courses{$course}{'owner'});
                if ($courses{$course}{'co-owners'} ne '') {
                    foreach my $item (split(/,/,$courses{$course}{'co-owners'})) {
                        push(@owners,$item);
                    }
                }
            } else {
                my $singleowner; 
                ($descr,$instcode,$singleowner,$ttype)=split(/:/,$courses{$course});
                push(@owners,&unescape($singleowner));
            }
            my $ownerstr = join(', ',map { &Apache::loncommon::plainname(split(':',$_)); } @owners);
            $r->print('<td>'.&course_chooser($multiple,$cdom,$cnum,$cleandesc,$canclone).'</td>');
            $r->print('<td>'.$description.'</td>');
            $r->print('<td>');
            $r->print(&Apache::lonnet::domain($cdom,'description')?
                      $cdom.' ('.&Apache::lonnet::domain($cdom,'description').')':$cdom);
            $r->print('</td>');
            unless (($type eq 'Community') || ($type eq 'Placement')) { 
                $r->print('<td>');
                if ($instcode ne '') {
                    $r->print(&unescape($instcode));
                } else {
                    $r->print('&nbsp;');
                }
                $r->print('</td>');
            }
            $r->print('<td>'.$ownerstr.'</td>');
            if ($showroles) {
                $r->print('<td>');
                my $rolestr;
                if (ref($courses{$course}{'roles'}) eq 'ARRAY') {
                    my @roles = sort(@{$courses{$course}{'roles'}});
                    foreach my $role (@roles) {
                        if ($role =~ /^cr/) {
                            my (undef,$crdom,$crname,$crtitle) = split('/',$role);
                            $rolestr .= $crtitle.', ';
                        } else {
                            $rolestr .= &Apache::lonnet::plaintext($role,$type).', ';
                        }
                    }
                    $rolestr =~ s/\, $//;
                }
                $r->print($rolestr.'</td>');
            }
            if ($multiple) { $r->print("</label>\n"); }
            $r->print(&Apache::loncommon::end_data_table_row());
            # $r->print("<br />\n");
        }
    }
    if (%courses) {
        $r->print(&Apache::loncommon::end_data_table());
    }

    if (!%courses) {
        $r->print('<p class="LC_info">'.&mt('None found').'</p>');
    } elsif ($multiple) {
        $r->print('<input type="button" value="'.&mt('Submit').'" onclick="gochoose('."'','','')".'" />');
    }
    $r->print('<input type="hidden" name="form" value="'.$env{'form.form'}.'" />'.
              "\n".'<input type="hidden" name="pickedcourse" value="" />'."\n".
              '<input type="hidden" name="type" value="'.$type.'" />'."\n");
    if ((exists($env{'form.roleelement'})) && ($env{'form.form'} eq 'rolechoice')) {
        $r->print('<input type="hidden" name="roleelement" value="'.
                  $env{'form.roleelement'}.'" />'."\n");
    }
    if ($env{'form.form'} eq 'portform') {
        $r->print('<input type="hidden" name="cnum" value="" />');
        $r->print('<input type="hidden" name="cdom" value="" />');
        $r->print('<input type="hidden" name="setroles" value="'.$env{'form.setroles'}.'" />');
        $r->print('<input type="hidden" name="action" value="rolepicker" />');
    } elsif ($env{'form.form'} eq 'modifycourse') {
        $r->print(&Apache::lonhtmlcommon::echo_form_input(['phase','pickedcourse','type','form','numtitles','state','adhocrole']));
    } else {
        $r->print('<input type="hidden" name="cnumelement" value="'.
                  $env{'form.cnumelement'}.'" />'."\n".  
                  '<input type="hidden" name="cdomelement" value="'.
                  $env{'form.cdomelement'}.'" />'."\n");
        if ($env{'form.typeelement'} ne '') {
            $r->print('<input type="hidden" name="typeelement" value="'.
                      $env{'form.typeelement'}.'" />'."\n");

        }
    }
    if ((exists($env{'form.fixeddom'})) && ($env{'form.form'} eq 'rules')) {
        $r->print('<input type="hidden" name="fixeddom" value="'.
                  $env{'form.fixeddom'}.'" />');
    }
    if ($env{'form.numtitles'}) {
        $r->print('<input type="hidden" name="numtitles" value="'.
                  $env{'form.numtitles'}.'" />');
    }
    $r->print("</form>\n");
    return;
}

sub multiples_tag {
    my $jscript = &Apache::loncommon::check_uncheck_jscript();
    my $multelement = '<input type="hidden" name="multiple" value="1" />';
    return ($jscript,$multelement);
}

sub get_coordinator_cloneable {
    my ($cloneruname,$clonerudom,$type) = @_;
    if (($cloneruname!~/\w/) || ($clonerudom!~/\w/)) {
        my $warning = '<div class="LC_warning">'.&mt('Intended course owner not specified').
                   '</div>';
        return ('',$warning);
    } elsif (&Apache::lonnet::homeserver($cloneruname,$clonerudom) eq 'no_host') {
        my $warning = '<div class="LC_error">'.&mt('Intended course owner does not exist').
                   '</div>';
        return ('',$warning);
    } else {
        my ($cc_clone,$ccrole);
        if ($type eq 'Community') {
            $ccrole = 'co';
        } else {
            $ccrole = 'cc';
        }
        my %ccroles = &Apache::lonnet::get_my_roles($cloneruname,$clonerudom,
                                                    'userroles',['active'], [$ccrole]);
        foreach my $key (sort(keys(%ccroles))) {
            my ($cnum,$cdom,$role) = split(':',$key);
            $cc_clone .= $cdom.':'.$cnum.'&';
        }
        $cc_clone =~ s/\&$//;
        return ($cc_clone);
    }
}

sub course_chooser {
    my ($multiple,$cdom,$cnum,$cleandesc,$canclone) = @_;
    my $output; 
    if ($multiple) {
        $output = '<label><input type="checkbox" name="course_id" value="'.$cdom.'_'.$cnum.'" />'."\n";
    } elsif ((($env{'form.form'} eq 'ccrs') || ($env{'form.form'} eq 'requestcrs')) && (!$canclone))  {
        if ($env{'form.form'} eq 'ccrs') {
            $output = &mt('No cloning for [_1]',$env{'form.cloner'})."\n";
        } else {
            $output = &mt('No rights to clone')."\n";
        }
    } else {
        $output = '<input type="button" value="'.&mt('Select').'" onclick="gochoose('.
                  "'".$cnum."','".$cdom."','".$cleandesc."')".'" />'."\n";
    }
    return $output;
}

sub gochoose_javascript {
    my ($type,$multiple,$autosubmit,$lastaction,$rolename,$rolechooser) = @_;
    my %elements = (
                     'Course' => {
                                 name  => 'coursepick',
                                 total => 'coursetotal',
                                 list  => 'courselist',
                                 },
                     'Community' => {
                                 name  => 'coursepick',
                                 total => 'coursetotal',
                                 list  => 'courselist',
                              },
                     'Placement' => {
                                 name  => 'coursepick',
                                 total => 'coursetotal',
                                 list  => 'courselist',
                                 },
                    );

    my %lt = &Apache::lonlocal::texthash (
        none => 'You are not eligible to use an ad hoc role for the selected course',
        ok => 'OK',
        exit => 'Cancel',       
    );
    &js_escape(\%lt);

    my $output;
    if ($rolechooser) {
        $output .= qq|
\$(document).ready(function(){
    \$( "#LC_adhocrole_chooser" ).dialog({ autoOpen: false });
});
|;
    }
    $output .= qq|
function gochoose(cname,cdom,cdesc) {
    var openerForm = "$env{'form.form'}";
    var openerRole = "$rolename";
    courseCount = 0;
    var courses = '';
|;
    if ($multiple) {
        $output .= <<"ENDSCRIPT";
    courseCount = 0;
    var courses = '';
    if (typeof(document.courselist.course_id.length) == 'undefined') {
        // only 1 course checkbox was created
        if (document.courselist.course_id.checked) {
            courses = courses + document.courselist.course_id.value + "&&";
            courseCount ++;
        }
    } else {
        for (var j=0; j<document.courselist.course_id.length; j++) {
            if (document.courselist.course_id[j].checked) {
                courses = courses + document.courselist.course_id[j].value + "&&";
                courseCount ++;
            }
        }
    }
    opener.document.$env{'form.form'}.$elements{$type}{'total'}.value = courseCount;
    if (typeof(opener.document.$env{'form.form'}.$elements{$type}{'name'}.length) ==
        'undefined') {
        if (opener.document.$env{'form.form'}.$elements{$type}{'name'}.value == 'specific') {
            opener.document.$env{'form.form'}.$elements{$type}{'name'}.checked = true;
        } else {
            opener.document.$env{'form.form'}.$elements{$type}{'name'}.checked = false;
        }
    } else {
        for (var j=0; j<opener.document.$env{'form.form'}.$elements{$type}{'name'}.length; j++) {
            if (opener.document.$env{'form.form'}.$elements{$type}{'name'}\[j].value == 'specific') {
                opener.document.$env{'form.form'}.$elements{$type}{'name'}\[j].checked = true;
            } else {
                opener.document.$env{'form.form'}.$elements{$type}{'name'}\[j].checked = false;
            }
        }
    }
    if (courseCount > 0) {
        courses = courses.substr(0,courses.length-2);
        opener.document.$env{'form.form'}.$elements{$type}{'list'}.value = courses;
    }
ENDSCRIPT
    } else {
        my ($name_code,$type_code);
        if ($env{'form.cnameelement'} ne '') {
            $name_code = <<ENDNAMECODE;  
var showcdesc = cdesc;
if (cdesc.length > 25) {
    showcdesc = cdesc.substr(0,25)+' ...'; 
}
opener.document.$env{'form.form'}.$env{'form.cnameelement'}.value=showcdesc;
ENDNAMECODE
        }
        if ($env{'form.typeelement'} ne '') {
            $type_code = 'opener.document.'.$env{'form.form'}.'.'.
                          $env{'form.typeelement'}.'.value=document.courselist.type;';
        }

        $output .= qq|
        $name_code
        $type_code
        opener.document.$env{'form.form'}.$env{'form.cnumelement'}.value=cname;
        var slct=opener.document.$env{'form.form'}.$env{'form.cdomelement'};
        if (slct.options == undefined) {
            opener.document.$env{'form.form'}.$env{'form.cdomelement'}.value=cdom;
        }
        else {
            var i;
            for (i=0;i<slct.length;i++) {
                if (slct.options[i].value==cdom) { slct.selectedIndex=i; }
            }
        }
|;
    }
    $output .= <<ENDJS;
    if (openerForm == 'portform') {
        document.courselist.cnum.value = cname;
        document.courselist.cdom.value = cdom;
    }
    if ((openerForm == 'rolechoice') && ((openerRole == 'dh') || (openerRole == 'da'))) {
\$("#LC_choose_adhoc").empty();
var http = new XMLHttpRequest();
var url = "/adm/pickcourse";
var params = "cid="+cdom+"_"+cname+"&context=adhoc";
http.open("POST", url, true);
http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
http.onreadystatechange = function() {
    if(http.readyState == 4 && http.status == 200) {
        var data = \$.parseJSON(http.responseText);
        var len = data.roles.length;
        if (len == '' || len == null || len == 0) {
            alert('$lt{none}');  
        } else {
            if (len == 1) {
                process_pick(cdom,data.roles[0].name);
                $lastaction;
            } else {
                var str = '';
                \$("#LC_choose_adhoc").empty();
                for (var i=0; i<data.roles.length; i++) { 
                    \$("<label><input type='radio' value='"+data.roles[i].name+"' name='LC_get_role' id='LC_get_role_"+i+"' />"+data.roles[i].desc+"</label><span>&nbsp;&nbsp;</span>")
                    .appendTo("#LC_choose_adhoc");
                }
                \$( "#LC_adhocrole_chooser" ).toggle( true );
                \$( "#LC_get_role_0").prop("checked", true);
                \$( "#LC_adhocrole_chooser" ).dialog({ autoOpen: false });
                \$( "#LC_adhocrole_chooser" ).dialog("open");
                \$( "#LC_adhocrole_chooser" ).dialog({
                 height: 400,
                 width: 500,
                 modal: true,
                 resizable: false,
                 buttons: [
                       {
                         text: "$lt{'ok'}",
                         click: function() {
                                     var rolename = \$('input[name=LC_get_role]:checked', '#LChelpdeskpicker').val();
                                     process_pick(cdom,rolename);
                                     \$("#LC_adhocrole_chooser").dialog( "close" );
                                     $lastaction;
                                } 
                       },
                       {
                         text: "$lt{'exit'}",
                         click: function() {
                                     \$("#LC_adhocrole_chooser").dialog( "close" );
                                }
                       }
                     ],
                });
                \$( "#LC_adhocrole_chooser" ).find( "form" ).on( "submit", function( event ) {
                   event.preventDefault();
                   var rolename = \$('input[name=LC_get_role]:checked', '#LChelpdeskpicker').val()
                   process_pick(cdom,rolename);
                   \$("#LC_adhocrole_chooser").dialog( "close" );
                   $lastaction;
                   });
            }
        }
    }
}
http.send(params);
    } else {
        $autosubmit
        $lastaction
    }
}

ENDJS
    return $rolechooser.&Apache::lonhtmlcommon::scripttag($output);
}

1;
__END__

=pod

=head1 NAME

Apache::lonpickcourse - Search for course(s) based on user-specified criteria.   

=head1 SYNOPSIS

Invoked by other LON-CAPA modules, when course(s) need to be selected by the user. 

=head1 OVERVIEW

Two screens are typically displayed to the user.  The first is a set of criteria which are used to constrain the search for courses.

=head2 Search Criteria (Screen One)

=head3 Criteria:

=over 4

=item *
Course Activity - how recently was course last visited by anyone.

=item *
Course Domain - the domain of the course

=item *
Type - Course, Community or Placement

=item *
Course Institutional Code - the institutional identifier assigned to the course

=item * 
Course Owner's Username - the username of the owner of the course (assigned by the Domain Coordinator and/or when the course was created).

=item *
Course Owner's Domain - the domain of the owner of the course

=item * 
Course Title - text which appears in the Course Title, as set in the Course Parameters.

=item *
Course ID - the internal course number (course ID part after initial 'domain_') used by LON-CAPA (this criterion is only displayed to Domain Coordinators selecting a course in the same domain as their DC role).

=back

The criteria setting screen is not displayed if course picking is done by a user who does not have advanced privileges (as defined by $env{'user.adv'}).

=head2 Course Display (Screen Two)

A list of courses matching the search criteria is displayed.  If the user is not an advanced user, screen one will have been skipped and the courses displayed will be all courses in which the user has currently active roles. The information displayed for each course is:

=over 4

=item *
Course description

=item *
Domain description of course domain

=item *
Course institutional code

=item * 
Course owner (username:domain)   
 
=back

Depending on context, the display may include a single select box for each course, allowing selection of only a single course, or may include checkboxes allowing selection of more than one course.

Following selection, and/or submission, the course description, number and domain are transferred to the browser window from which the course picker window was opened.  In most cases, the child window containing the course picker screens will be closed.  However, in some cases closure will be delayed until a third screen has been displayed (e.g., setting of course-based conditional access controls for portfolio files).  In this case the page is generated via /adm/portfolio and the page features select boxes to allow the user to select roles, access types, sections and groups.

=head1 SUBROUTINES

=over 4

=item *
X<create_user_javascript()>
B<create_user_javascript($type)>:

Input: 1 - $type  - the course type - Course, Community, or Placement

Output: 1 - $output - javascript wrapped in E<lt>scriptE<gt>E<lt>/scriptE<gt> tags 

Side Effects: None 

javascript code for reporting selected sections (as a string of comma separated sections) and groups in the selected course (as a comma separated list) then calling setSect() javscript function in the opener window (to populate section select box) then closing current window.


=item *
X<display_matched_courses()>
B<display_matched_courses($r,$type,$multiple,$action,$showroles,$cloneruname,$clonerudom,$crsdom,$crscode,%courses)>:

Input: 8 - request object, course type, multiple (0 or 1), form action, whether to show roles (for course personnel filter), username of new course owner, domain of new course owner, domain of new course, institutional code of new course, hash of courses.

Output: 0

Side Effects: prints select buttons (multiple = 0) or checkboxes (multiple = 1) and hidden form elements for selection of one or more courses which met search criteria.

=item *
X<multiples_tag()>
B<multiples_tag()>:


Input: 0

Output: 2 - $jscript - javascript for check all/uncheck all checkboxes; $multelement - hidden form element with multiple set to 1.

Side Effects: None


=item *
X<course_chooser()>
B<course_chooser($multiple,$cdom,$cnum,$cleandesc,$canclone)>:

Input: 5 - single (0) or multiple (1) courses; course domain, course number; course description; can clone course (1 if new course owner has cloning rights). 

Output: 1 - HTML for either checkbox (multiple=1) or select button (multiple=0) for user to indicate course selection.

Side Effects: None


=item *
X<gochoose_javascript()>
B<gochoose_javascript($type,$multiple,$autosubmit,$lastaction,$rolename)>:

Input: 5 - course type; single (0) or multiple courses (1); in context of DC selecting a CC role in a course: javascript code from &processpick(); final action to take after user chooses course(s):  either close window, or submit form for display of next page etc.; rolename (e.g., dh) of user's current role.

Output: 1  $output - javascript wrapped in E<lt>scriptE<gt>E<lt>/scriptE<gt> tags

Side Effects: None

javascript functions used when user selects a course(s). Different behavior depending on context:

=back

=over 8

=item

(a) Domain Coordinator using MAIL to select recipients of broadcast e-mail - && separated list of selected courses written to hidden form element in opener window. Child window closes.

=item

(b) Domain Coordinator choosing a course for adoption of a CC role from roles screen - write course identifying information to hidden form elements in opener window and automatically submit role selection form in opener window. Child window closes.

=item

(c) Domain Coordinator creating a course, and selecting a course to clone - course number and domain written to visible form elements in opener window. Child window closes.

=item

(d) User selecting a course for course-based conditional access control for a portfolio file - form is submitted, and new page is displayed for selection of roles, access types, sections and groups to be used in conditional ACL. New page is generated by /adm/portfolio. 

=item

(e) Domain Coordinator assigning a role to a user - form is submitted, and new page does an onload call to a javascript function to (a) write lists of sections and groups to hidden elements in opener window, (b) call function in opener window to dynamically populate select box showing current sections.

=item

(f) Author modifying a rights entry in a .rights file - selected course number and domain are witten to visible form elements in opener window.  Child window closes. 

=item

(g) Bubblesheet Scanning Operator uploading a bubblesheet file to a course - course number is written to visible form element in opener window. Child window closes.

=item

(h) User requesting creation of a course, and selecting a course to clone - course number and domain written to visible form elements in opener window. Child window closes.

=back
     
=cut

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