--- loncom/interface/loncommon.pm 2001/09/13 19:59:33 1.5
+++ loncom/interface/loncommon.pm 2013/03/20 01:26:15 1.1118
@@ -1,19 +1,3761 @@
-# The LearningOnline Network
+# The LearningOnline Network with CAPA
# a pile of common routines
-# 2/13 Guy Albertelli
+#
+# $Id: loncommon.pm,v 1.1118 2013/03/20 01:26:15 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/
+#
# Makes a table out of the previous attempts
# Inputs result_from_symbread, user, domain, course_id
+# Reads in non-network-related .tab files
+# POD header:
+
+=pod
+
+=head1 NAME
+
+Apache::loncommon - pile of common routines
+
+=head1 SYNOPSIS
+
+Common routines for manipulating connections, student answers,
+ domains, common Javascript fragments, etc.
+
+=head1 OVERVIEW
+
+A collection of commonly used subroutines that don't have a natural
+home anywhere else. This collection helps remove
+redundancy from other modules and increase efficiency of memory usage.
+
+=cut
+
+# End of POD header
package Apache::loncommon;
use strict;
-use Apache::Constants qw(:common);
-use Apache::lonmsg();
+use Apache::lonnet;
+use GDBM_File;
+use POSIX qw(strftime mktime);
+use Apache::lonmenu();
+use Apache::lonenc();
+use Apache::lonlocal;
+use Apache::lonnet();
+use HTML::Entities;
+use Apache::lonhtmlcommon();
+use Apache::loncoursedata();
+use Apache::lontexconvert();
+use Apache::lonclonecourse();
+use Apache::lonuserutils();
+use Apache::lonuserstate();
+use LONCAPA qw(:DEFAULT :match);
+use DateTime::TimeZone;
+use DateTime::Locale::Catalog;
+use Text::Aspell;
+use Authen::Captcha;
+use Captcha::reCAPTCHA;
+
+# ---------------------------------------------- Designs
+use vars qw(%defaultdesign);
+
+my $readit;
+
+
+##
+## Global Variables
+##
+
+
+# ----------------------------------------------- SSI with retries:
+#
+
+=pod
+
+=head1 Server Side include with retries:
+
+=over 4
+
+=item * &ssi_with_retries(resource,retries form)
+
+Performs an ssi with some number of retries. Retries continue either
+until the result is ok or until the retry count supplied by the
+caller is exhausted.
+
+Inputs:
+
+=over 4
+
+resource - Identifies the resource to insert.
+
+retries - Count of the number of retries allowed.
+
+form - Hash that identifies the rendering options.
+
+=back
+
+Returns:
+
+=over 4
+
+content - The content of the response. If retries were exhausted this is empty.
+
+response - The response from the last attempt (which may or may not have been successful.
+
+=back
+
+=back
+
+=cut
+
+sub ssi_with_retries {
+ my ($resource, $retries, %form) = @_;
+
+
+ my $ok = 0; # True if we got a good response.
+ my $content;
+ my $response;
+
+ # Try to get the ssi done. within the retries count:
+
+ do {
+ ($content, $response) = &Apache::lonnet::ssi($resource, %form);
+ $ok = $response->is_success;
+ if (!$ok) {
+ &Apache::lonnet::logthis("Failed ssi_with_retries on $resource: ".$response->is_success.', '.$response->code.', '.$response->message);
+ }
+ $retries--;
+ } while (!$ok && ($retries > 0));
+
+ if (!$ok) {
+ $content = ''; # On error return an empty content.
+ }
+ return ($content, $response);
+
+}
+
+
+
+# ----------------------------------------------- Filetypes/Languages/Copyright
+my %language;
+my %supported_language;
+my %supported_codes;
+my %latex_language; # For choosing hyphenation in
+my %latex_language_bykey; # for choosing hyphenation from metadata
+my %cprtag;
+my %scprtag;
+my %fe; my %fd; my %fm;
+my %category_extensions;
+
+# ---------------------------------------------- Thesaurus variables
+#
+# %Keywords:
+# A hash used by &keyword to determine if a word is considered a keyword.
+# $thesaurus_db_file
+# Scalar containing the full path to the thesaurus database.
+
+my %Keywords;
+my $thesaurus_db_file;
+
+#
+# Initialize values from language.tab, copyright.tab, filetypes.tab,
+# thesaurus.tab, and filecategories.tab.
+#
+BEGIN {
+ # Variable initialization
+ $thesaurus_db_file = $Apache::lonnet::perlvar{'lonTabDir'}."/thesaurus.db";
+ #
+ unless ($readit) {
+# ------------------------------------------------------------------- languages
+ {
+ my $langtabfile = $Apache::lonnet::perlvar{'lonTabDir'}.
+ '/language.tab';
+ if ( open(my $fh,"<$langtabfile") ) {
+ while (my $line = <$fh>) {
+ next if ($line=~/^\#/);
+ chomp($line);
+ my ($key,$code,$country,$three,$enc,$val,$sup,$latex)=(split(/\t/,$line));
+ $language{$key}=$val.' - '.$enc;
+ if ($sup) {
+ $supported_language{$key}=$sup;
+ $supported_codes{$key} = $code;
+ }
+ if ($latex) {
+ $latex_language_bykey{$key} = $latex;
+ $latex_language{$code} = $latex;
+ }
+ }
+ close($fh);
+ }
+ }
+# ------------------------------------------------------------------ copyrights
+ {
+ my $copyrightfile = $Apache::lonnet::perlvar{'lonIncludes'}.
+ '/copyright.tab';
+ if ( open (my $fh,"<$copyrightfile") ) {
+ while (my $line = <$fh>) {
+ next if ($line=~/^\#/);
+ chomp($line);
+ my ($key,$val)=(split(/\s+/,$line,2));
+ $cprtag{$key}=$val;
+ }
+ close($fh);
+ }
+ }
+# ----------------------------------------------------------- source copyrights
+ {
+ my $sourcecopyrightfile = $Apache::lonnet::perlvar{'lonIncludes'}.
+ '/source_copyright.tab';
+ if ( open (my $fh,"<$sourcecopyrightfile") ) {
+ while (my $line = <$fh>) {
+ next if ($line =~ /^\#/);
+ chomp($line);
+ my ($key,$val)=(split(/\s+/,$line,2));
+ $scprtag{$key}=$val;
+ }
+ close($fh);
+ }
+ }
+
+# -------------------------------------------------------------- default domain designs
+ my $designdir=$Apache::lonnet::perlvar{'lonTabDir'}.'/lonDomColors';
+ my $designfile = $designdir.'/default.tab';
+ if ( open (my $fh,"<$designfile") ) {
+ while (my $line = <$fh>) {
+ next if ($line =~ /^\#/);
+ chomp($line);
+ my ($key,$val)=(split(/\=/,$line));
+ if ($val) { $defaultdesign{$key}=$val; }
+ }
+ close($fh);
+ }
+
+# ------------------------------------------------------------- file categories
+ {
+ my $categoryfile = $Apache::lonnet::perlvar{'lonTabDir'}.
+ '/filecategories.tab';
+ if ( open (my $fh,"<$categoryfile") ) {
+ while (my $line = <$fh>) {
+ next if ($line =~ /^\#/);
+ chomp($line);
+ my ($extension,$category)=(split(/\s+/,$line,2));
+ push @{$category_extensions{lc($category)}},$extension;
+ }
+ close($fh);
+ }
+
+ }
+# ------------------------------------------------------------------ file types
+ {
+ my $typesfile = $Apache::lonnet::perlvar{'lonTabDir'}.
+ '/filetypes.tab';
+ if ( open (my $fh,"<$typesfile") ) {
+ while (my $line = <$fh>) {
+ next if ($line =~ /^\#/);
+ chomp($line);
+ my ($ending,$emb,$mime,$descr)=split(/\s+/,$line,4);
+ if ($descr ne '') {
+ $fe{$ending}=lc($emb);
+ $fd{$ending}=$descr;
+ if ($mime ne 'unk') { $fm{$ending}=$mime; }
+ }
+ }
+ close($fh);
+ }
+ }
+ &Apache::lonnet::logthis(
+ "INFO: Read file types");
+ $readit=1;
+ } # end of unless($readit)
+
+}
+
+###############################################################
+## HTML and Javascript Helper Functions ##
+###############################################################
+
+=pod
+
+=head1 HTML and Javascript Functions
+
+=over 4
+
+=item * &browser_and_searcher_javascript()
+
+XXReturns a string
+containing javascript with two functions, C and
+C. Returned string does not contain EscriptE
+tags.
+
+=item * &openbrowser(formname,elementname,only,omit) [javascript]
+
+inputs: formname, elementname, only, omit
+
+formname and elementname indicate the name of the html form and name of
+the element that the results of the browsing selection are to be placed in.
+
+Specifying 'only' will restrict the browser to displaying only files
+with the given extension. Can be a comma separated list.
+
+Specifying 'omit' will restrict the browser to NOT displaying files
+with the given extension. Can be a comma separated list.
+
+=item * &opensearcher(formname,elementname) [javascript]
+
+Inputs: formname, elementname
+
+formname and elementname specify the name of the html form and the name
+of the element the selection from the search results will be placed in.
+
+=cut
+
+sub browser_and_searcher_javascript {
+ my ($mode)=@_;
+ if (!defined($mode)) { $mode='edit'; }
+ my $resurl=&escape_single(&lastresurl());
+ return <
+END
+}
+
+sub lastresurl {
+ if ($env{'environment.lastresurl'}) {
+ return $env{'environment.lastresurl'}
+ } else {
+ return '/res';
+ }
+}
+
+sub storeresurl {
+ my $resurl=&Apache::lonnet::clutter(shift);
+ unless ($resurl=~/^\/res/) { return 0; }
+ $resurl=~s/\/$//;
+ &Apache::lonnet::put('environment',{'lastresurl' => $resurl});
+ &Apache::lonnet::appenv({'environment.lastresurl' => $resurl});
+ return 1;
+}
+
+sub studentbrowser_javascript {
+ unless (
+ (($env{'request.course.id'}) &&
+ (&Apache::lonnet::allowed('srm',$env{'request.course.id'})
+ || &Apache::lonnet::allowed('srm',$env{'request.course.id'}.
+ '/'.$env{'request.course.sec'})
+ ))
+ || ($env{'request.role'}=~/^(au|dc|su)/)
+ ) { return ''; }
+ return (<<'ENDSTDBRW');
+
+ENDSTDBRW
+}
+
+sub resourcebrowser_javascript {
+ unless ($env{'request.course.id'}) { return ''; }
+ return (<<'ENDRESBRW');
+
+ENDRESBRW
+}
+
+sub selectstudent_link {
+ my ($form,$unameele,$udomele,$courseadvonly,$clickerid)=@_;
+ my $callargs = "'".&Apache::lonhtmlcommon::entity_encode($form)."','".
+ &Apache::lonhtmlcommon::entity_encode($unameele)."','".
+ &Apache::lonhtmlcommon::entity_encode($udomele)."'";
+ if ($env{'request.course.id'}) {
+ if (!&Apache::lonnet::allowed('srm',$env{'request.course.id'})
+ && !&Apache::lonnet::allowed('srm',$env{'request.course.id'}.
+ '/'.$env{'request.course.sec'})) {
+ return '';
+ }
+ $callargs.=",'".&Apache::lonhtmlcommon::entity_encode($clickerid)."'";
+ if ($courseadvonly) {
+ $callargs .= ",'',1,1";
+ }
+ return ''.
+ ''.
+ &mt('Select User').'';
+ }
+ if ($env{'request.role'}=~/^(au|dc|su)/) {
+ $callargs .= ",'',1";
+ return ''.
+ ''.
+ &mt('Select User').'';
+ }
+ return '';
+}
+
+sub selectresource_link {
+ my ($form,$reslink,$arg)=@_;
+
+ my $callargs = "'".&Apache::lonhtmlcommon::entity_encode($form)."','".
+ &Apache::lonhtmlcommon::entity_encode($reslink)."'";
+ unless ($env{'request.course.id'}) { return $arg; }
+ return ''.
+ ''.
+ $arg.'';
+}
+
+
+
+sub authorbrowser_javascript {
+ return <<"ENDAUTHORBRW";
+
+ENDAUTHORBRW
+}
+
+sub coursebrowser_javascript {
+ my ($domainfilter,$sec_element,$formname,$role_element,$crstype,
+ $credits_element) = @_;
+ my $wintitle = 'Course_Browser';
+ if ($crstype eq 'Community') {
+ $wintitle = 'Community_Browser';
+ }
+ my $id_functions = &javascript_index_functions();
+ my $output = '
+';
+ return $output;
+}
+
+sub javascript_index_functions {
+ return <<"ENDJS";
+
+function getFormIdByName(formname) {
+ for (var i=0;i -1) {
+ var domid = getIndexByName(formid,udom);
+ if (domid > -1) {
+ if (document.forms[formid].elements[domid].type == 'select-one') {
+ userdom=document.forms[formid].elements[domid].options[document.forms[formid].elements[domid].selectedIndex].value;
+ }
+ if (document.forms[formid].elements[domid].type == 'hidden') {
+ userdom=document.forms[formid].elements[domid].value;
+ }
+ }
+ }
+ return userdom;
+}
+
+ENDJS
+
+}
+
+sub javascript_array_indexof {
+ return <
+// >> 0;
+ if (len === 0) {
+ return -1;
+ }
+ var n = 0;
+ if (arguments.length > 0) {
+ n = Number(arguments[1]);
+ if (n !== n) { // shortcut for verifying if it is NaN
+ n = 0;
+ } else if (n !== 0 && n !== (1 / 0) && n !== -(1 / 0)) {
+ n = (n > 0 || -1) * Math.floor(Math.abs(n));
+ }
+ }
+ if (n >= len) {
+ return -1;
+ }
+ var k = n >= 0 ? n : Math.max(len - Math.abs(n), 0);
+ for (; k < len; k++) {
+ if (k in t && t[k] === searchElement) {
+ return k;
+ }
+ }
+ return -1;
+ }
+}
+
+// ]]>
+
+
+ENDJS
+
+}
+
+sub userbrowser_javascript {
+ my $id_functions = &javascript_index_functions();
+ return <<"ENDUSERBRW";
+
+function openuserbrowser(formname,uname,udom,ulast,ufirst,uemail,hideudom,crsdom,caller) {
+ var url = '/adm/pickuser?';
+ var userdom = getDomainFromSelectbox(formname,udom);
+ if (userdom != null) {
+ if (userdom != '') {
+ url += 'srchdom='+userdom+'&';
+ }
+ }
+ url += 'form=' + formname + '&unameelement='+uname+
+ '&udomelement='+udom+
+ '&ulastelement='+ulast+
+ '&ufirstelement='+ufirst+
+ '&uemailelement='+uemail+
+ '&hideudomelement='+hideudom+
+ '&coursedom='+crsdom;
+ if ((caller != null) && (caller != undefined)) {
+ url += '&caller='+caller;
+ }
+ var title = 'User_Browser';
+ var options = 'scrollbars=1,resizable=1,menubar=0';
+ options += ',width=700,height=600';
+ var stdeditbrowser = open(url,title,options,'1');
+ stdeditbrowser.focus();
+}
+
+function fix_domain (formname,udom,origdom,uname) {
+ var formid = getFormIdByName(formname);
+ if (formid > -1) {
+ var unameid = getIndexByName(formid,uname);
+ var domid = getIndexByName(formid,udom);
+ var hidedomid = getIndexByName(formid,origdom);
+ if (hidedomid > -1) {
+ var fixeddom = document.forms[formid].elements[hidedomid].value;
+ var unameval = document.forms[formid].elements[unameid].value;
+ if ((fixeddom != '') && (fixeddom != undefined) && (fixeddom != null) && (unameval != '') && (unameval != undefined) && (unameval != null)) {
+ if (domid > -1) {
+ var slct = document.forms[formid].elements[domid];
+ if (slct.type == 'select-one') {
+ var i;
+ for (i=0;i'
+ ."".$linktext.''
+ .'';
+}
+
+sub selectauthor_link {
+ my ($form,$udom)=@_;
+ return ''.
+ &mt('Select Author').'';
+}
+
+sub selectuser_link {
+ my ($form,$unameelem,$domelem,$lastelem,$firstelem,$emailelem,$hdomelem,
+ $coursedom,$linktext,$caller) = @_;
+ return ''.$linktext.'';
+}
+
+sub check_uncheck_jscript {
+ my $jscript = <<"ENDSCRT";
+function checkAll(field) {
+ if (field.length > 0) {
+ for (i = 0; i < field.length; i++) {
+ if (!field[i].disabled) {
+ field[i].checked = true;
+ }
+ }
+ } else {
+ if (!field.disabled) {
+ field.checked = true;
+ }
+ }
+}
+
+function uncheckAll(field) {
+ if (field.length > 0) {
+ for (i = 0; i < field.length; i++) {
+ field[i].checked = false ;
+ }
+ } else {
+ field.checked = false ;
+ }
+}
+ENDSCRT
+ return $jscript;
+}
+
+sub select_timezone {
+ my ($name,$selected,$onchange,$includeempty)=@_;
+ my $output='";
+ return $output;
+}
+
+sub select_datelocale {
+ my ($name,$selected,$onchange,$includeempty)=@_;
+ my $output='";
+ return $output;
+}
+
+sub select_language {
+ my ($name,$selected,$includeempty) = @_;
+ my %langchoices;
+ if ($includeempty) {
+ %langchoices = ('' => 'No language preference');
+ }
+ foreach my $id (&languageids()) {
+ my $code = &supportedlanguagecode($id);
+ if ($code) {
+ $langchoices{$code} = &plainlanguagedescription($id);
+ }
+ }
+ %langchoices = &Apache::lonlocal::texthash(%langchoices);
+ return &select_form($selected,$name,\%langchoices);
+}
+
+=pod
+
+
+=item * &list_languages()
+
+Returns an array reference that is suitable for use in language prompters.
+Each array element is itself a two element array. The first element
+is the language code. The second element a descsriptiuon of the
+language itself. This is suitable for use in e.g.
+&Apache::edit::select_arg (once dereferenced that is).
+
+=cut
+
+sub list_languages {
+ my @lang_choices;
+
+ foreach my $id (&languageids()) {
+ my $code = &supportedlanguagecode($id);
+ if ($code) {
+ my $selector = $supported_codes{$id};
+ my $description = &plainlanguagedescription($id);
+ push (@lang_choices, [$selector, $description]);
+ }
+ }
+ return \@lang_choices;
+}
+
+=pod
+
+=item * &linked_select_forms(...)
+
+linked_select_forms returns a string containing a block
+and html for two
'."\n";;
+ }
+
+ sub data_table_caption {
+ my $caption = shift;
+ return "
$caption
";
+ }
+}
+
+=pod
+
+=item * &inhibit_menu_check($arg)
+
+Checks for a inhibitmenu state and generates output to preserve it
+
+Inputs: $arg - can be any of
+ - undef - in which case the return value is a string
+ to add into arguments list of a uri
+ - 'input' - in which case the return value is a HTML
+
field of type hidden to
+ preserve the value
+ - a url - in which case the return value is the url with
+ the neccesary cgi args added to preserve the
+ inhibitmenu state
+ - a ref to a url - no return value, but the string is
+ updated to include the neccessary cgi
+ args to preserve the inhibitmenu state
+
+=cut
+
+sub inhibit_menu_check {
+ my ($arg) = @_;
+ &get_unprocessed_cgi($ENV{'QUERY_STRING'}, ['inhibitmenu']);
+ if ($arg eq 'input') {
+ if ($env{'form.inhibitmenu'}) {
+ return '';
+ } else {
+ return
+ }
+ }
+ if ($env{'form.inhibitmenu'}) {
+ if (ref($arg)) {
+ $$arg .= '?inhibitmenu='.$env{'form.inhibitmenu'};
+ } elsif ($arg eq '') {
+ $arg .= 'inhibitmenu='.$env{'form.inhibitmenu'};
+ } else {
+ $arg .= '?inhibitmenu='.$env{'form.inhibitmenu'};
+ }
+ }
+ if (!ref($arg)) {
+ return $arg;
+ }
+}
+
+###############################################
+
+=pod
+
+=back
+
+=head1 User Information Routines
+
+=over 4
+
+=item * &get_users_function()
+
+Used by &bodytag to determine the current users primary role.
+Returns either 'student','coordinator','admin', or 'author'.
+
+=cut
+
+###############################################
+sub get_users_function {
+ my $function = 'norole';
+ if ($env{'request.role'}=~/^(st)/) {
+ $function='student';
+ }
+ if ($env{'request.role'}=~/^(cc|co|in|ta|ep)/) {
+ $function='coordinator';
+ }
+ if ($env{'request.role'}=~/^(su|dc|ad|li)/) {
+ $function='admin';
+ }
+ if (($env{'request.role'}=~/^(au|ca|aa)/) ||
+ ($ENV{'REQUEST_URI'}=~ m{/^(/priv)})) {
+ $function='author';
+ }
+ return $function;
+}
+
+###############################################
+
+=pod
+
+=item * &show_course()
+
+Used by lonmenu.pm and lonroles.pm to determine whether to use the word
+'Courses' or 'Roles' in inline navigation and on screen displaying user's roles.
+
+Inputs:
+None
+
+Outputs:
+Scalar: 1 if 'Course' to be used, 0 otherwise.
+
+=cut
+
+###############################################
+sub show_course {
+ my $course = !$env{'user.adv'};
+ if (!$env{'user.adv'}) {
+ foreach my $env (keys(%env)) {
+ next if ($env !~ m/^user\.priv\./);
+ if ($env !~ m/^user\.priv\.(?:st|cm)/) {
+ $course = 0;
+ last;
+ }
+ }
+ }
+ return $course;
+}
+
+###############################################
+
+=pod
+
+=item * &check_user_status()
+
+Determines current status of supplied role for a
+specific user. Roles can be active, previous or future.
+
+Inputs:
+user's domain, user's username, course's domain,
+course's number, optional section ID.
+
+Outputs:
+role status: active, previous or future.
+
+=cut
+
+sub check_user_status {
+ my ($udom,$uname,$cdom,$crs,$role,$sec) = @_;
+ my %userinfo = &Apache::lonnet::dump('roles',$udom,$uname);
+ my @uroles = keys %userinfo;
+ my $srchstr;
+ my $active_chk = 'none';
+ my $now = time;
+ if (@uroles > 0) {
+ if (($role eq 'cc') || ($role eq 'co') || ($sec eq '') || (!defined($sec))) {
+ $srchstr = '/'.$cdom.'/'.$crs.'_'.$role;
+ } else {
+ $srchstr = '/'.$cdom.'/'.$crs.'/'.$sec.'_'.$role;
+ }
+ if (grep/^\Q$srchstr\E$/,@uroles) {
+ my $role_end = 0;
+ my $role_start = 0;
+ $active_chk = 'active';
+ if ($userinfo{$srchstr} =~ m/^\Q$role\E_(\d+)/) {
+ $role_end = $1;
+ if ($userinfo{$srchstr} =~ m/^\Q$role\E_\Q$role_end\E_(\d+)$/) {
+ $role_start = $1;
+ }
+ }
+ if ($role_start > 0) {
+ if ($now < $role_start) {
+ $active_chk = 'future';
+ }
+ }
+ if ($role_end > 0) {
+ if ($now > $role_end) {
+ $active_chk = 'previous';
+ }
+ }
+ }
+ }
+ return $active_chk;
+}
+
+###############################################
+
+=pod
+
+=item * &get_sections()
+
+Determines all the sections for a course including
+sections with students and sections containing other roles.
+Incoming parameters:
+
+1. domain
+2. course number
+3. reference to array containing roles for which sections should
+be gathered (optional).
+4. reference to array containing status types for which sections
+should be gathered (optional).
+
+If the third argument is undefined, sections are gathered for any role.
+If the fourth argument is undefined, sections are gathered for any status.
+Permissible values are 'active' or 'future' or 'previous'.
+
+Returns section hash (keys are section IDs, values are
+number of users in each section), subject to the
+optional roles filter, optional status filter
+
+=cut
+
+###############################################
+sub get_sections {
+ my ($cdom,$cnum,$possible_roles,$possible_status) = @_;
+ if (!defined($cdom) || !defined($cnum)) {
+ my $cid = $env{'request.course.id'};
+
+ return if (!defined($cid));
+
+ $cdom = $env{'course.'.$cid.'.domain'};
+ $cnum = $env{'course.'.$cid.'.num'};
+ }
+
+ my %sectioncount;
+ my $now = time;
+
+ my $check_students = 1;
+ my $only_students = 0;
+ if (ref($possible_roles) eq 'ARRAY') {
+ if (grep(/^st$/,@{$possible_roles})) {
+ if (@{$possible_roles} == 1) {
+ $only_students = 1;
+ }
+ } else {
+ $check_students = 0;
+ }
+ }
+
+ if ($check_students) {
+ my ($classlist) = &Apache::loncoursedata::get_classlist($cdom,$cnum);
+ my $sec_index = &Apache::loncoursedata::CL_SECTION();
+ my $status_index = &Apache::loncoursedata::CL_STATUS();
+ my $start_index = &Apache::loncoursedata::CL_START();
+ my $end_index = &Apache::loncoursedata::CL_END();
+ my $status;
+ while (my ($student,$data) = each(%$classlist)) {
+ my ($section,$stu_status,$start,$end) = ($data->[$sec_index],
+ $data->[$status_index],
+ $data->[$start_index],
+ $data->[$end_index]);
+ if ($stu_status eq 'Active') {
+ $status = 'active';
+ } elsif ($end < $now) {
+ $status = 'previous';
+ } elsif ($start > $now) {
+ $status = 'future';
+ }
+ if ($section ne '-1' && $section !~ /^\s*$/) {
+ if ((!defined($possible_status)) || (($status ne '') &&
+ (grep/^\Q$status\E$/,@{$possible_status}))) {
+ $sectioncount{$section}++;
+ }
+ }
+ }
+ }
+ if ($only_students) {
+ return %sectioncount;
+ }
+ my %courseroles = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
+ foreach my $user (sort(keys(%courseroles))) {
+ if ($user !~ /^(\w{2})/) { next; }
+ my ($role) = ($user =~ /^(\w{2})/);
+ if ($possible_roles && !(grep(/^$role$/,@$possible_roles))) { next; }
+ my ($section,$status);
+ if ($role eq 'cr' &&
+ $user =~ m-^$role/[^/]*/[^/]*/[^/]*:[^:]*:[^:]*:(\w+)-) {
+ $section=$1;
+ }
+ if ($user =~ /^$role:[^:]*:[^:]*:(\w+)/) { $section=$1; }
+ if (!defined($section) || $section eq '-1') { next; }
+ my ($end,$start) = ($courseroles{$user} =~ /^([^:]*):([^:]*)$/);
+ if ($end == -1 && $start == -1) {
+ next; #deleted role
+ }
+ if (!defined($possible_status)) {
+ $sectioncount{$section}++;
+ } else {
+ if ((!$end || $end >= $now) && (!$start || $start <= $now)) {
+ $status = 'active';
+ } elsif ($end < $now) {
+ $status = 'future';
+ } elsif ($start > $now) {
+ $status = 'previous';
+ }
+ if (($status ne '') && (grep/^\Q$status\E$/,@{$possible_status})) {
+ $sectioncount{$section}++;
+ }
+ }
+ }
+ return %sectioncount;
+}
+
+###############################################
+
+=pod
+
+=item * &get_course_users()
+
+Retrieves usernames:domains for users in the specified course
+with specific role(s), and access status.
+
+Incoming parameters:
+1. course domain
+2. course number
+3. access status: users must have - either active,
+previous, future, or all.
+4. reference to array of permissible roles
+5. reference to array of section restrictions (optional)
+6. reference to results object (hash of hashes).
+7. reference to optional userdata hash
+8. reference to optional statushash
+9. flag if privileged users (except those set to unhide in
+ course settings) should be excluded
+Keys of top level results hash are roles.
+Keys of inner hashes are username:domain, with
+values set to access type.
+Optional userdata hash returns an array with arguments in the
+same order as loncoursedata::get_classlist() for student data.
+
+Optional statushash returns
+
+Entries for end, start, section and status are blank because
+of the possibility of multiple values for non-student roles.
+
+=cut
+
+###############################################
+
+sub get_course_users {
+ my ($cdom,$cnum,$types,$roles,$sections,$users,$userdata,$statushash,$hidepriv) = @_;
+ my %idx = ();
+ my %seclists;
+
+ $idx{udom} = &Apache::loncoursedata::CL_SDOM();
+ $idx{uname} = &Apache::loncoursedata::CL_SNAME();
+ $idx{end} = &Apache::loncoursedata::CL_END();
+ $idx{start} = &Apache::loncoursedata::CL_START();
+ $idx{id} = &Apache::loncoursedata::CL_ID();
+ $idx{section} = &Apache::loncoursedata::CL_SECTION();
+ $idx{fullname} = &Apache::loncoursedata::CL_FULLNAME();
+ $idx{status} = &Apache::loncoursedata::CL_STATUS();
+
+ if (grep(/^st$/,@{$roles})) {
+ my ($classlist,$keylist)=&Apache::loncoursedata::get_classlist($cdom,$cnum);
+ my $now = time;
+ foreach my $student (keys(%{$classlist})) {
+ my $match = 0;
+ my $secmatch = 0;
+ my $section = $$classlist{$student}[$idx{section}];
+ my $status = $$classlist{$student}[$idx{status}];
+ if ($section eq '') {
+ $section = 'none';
+ }
+ if ((ref($sections) eq 'ARRAY') && (@{$sections} > 0)) {
+ if (grep(/^all$/,@{$sections})) {
+ $secmatch = 1;
+ } elsif ($$classlist{$student}[$idx{section}] eq '') {
+ if (grep(/^none$/,@{$sections})) {
+ $secmatch = 1;
+ }
+ } else {
+ if (grep(/^\Q$section\E$/,@{$sections})) {
+ $secmatch = 1;
+ }
+ }
+ if (!$secmatch) {
+ next;
+ }
+ }
+ if (defined($$types{'active'})) {
+ if ($$classlist{$student}[$idx{status}] eq 'Active') {
+ push(@{$$users{st}{$student}},'active');
+ $match = 1;
+ }
+ }
+ if (defined($$types{'previous'})) {
+ if ($$classlist{$student}[$idx{status}] eq 'Expired') {
+ push(@{$$users{st}{$student}},'previous');
+ $match = 1;
+ }
+ }
+ if (defined($$types{'future'})) {
+ if ($$classlist{$student}[$idx{status}] eq 'Future') {
+ push(@{$$users{st}{$student}},'future');
+ $match = 1;
+ }
+ }
+ if ($match) {
+ push(@{$seclists{$student}},$section);
+ if (ref($userdata) eq 'HASH') {
+ $$userdata{$student} = $$classlist{$student};
+ }
+ if (ref($statushash) eq 'HASH') {
+ $statushash->{$student}{'st'}{$section} = $status;
+ }
+ }
+ }
+ }
+ if ((@{$roles} > 1) || ((@{$roles} == 1) && ($$roles[0] ne "st"))) {
+ my %coursepersonnel = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
+ my $now = time;
+ my %displaystatus = ( previous => 'Expired',
+ active => 'Active',
+ future => 'Future',
+ );
+ my %nothide;
+ if ($hidepriv) {
+ my %coursehash=&Apache::lonnet::coursedescription($cdom.'_'.$cnum);
+ foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
+ if ($user !~ /:/) {
+ $nothide{join(':',split(/[\@]/,$user))}=1;
+ } else {
+ $nothide{$user} = 1;
+ }
+ }
+ }
+ foreach my $person (sort(keys(%coursepersonnel))) {
+ my $match = 0;
+ my $secmatch = 0;
+ my $status;
+ my ($role,$user,$usec) = ($person =~ /^([^:]*):([^:]+:[^:]+):([^:]*)/);
+ $user =~ s/:$//;
+ my ($end,$start) = split(/:/,$coursepersonnel{$person});
+ if ($end == -1 || $start == -1) {
+ next;
+ }
+ if (($role) && ((grep(/^\Q$role\E$/,@{$roles})) ||
+ (grep(/^cr$/,@{$roles}) && $role =~ /^cr\//))) {
+ my ($uname,$udom) = split(/:/,$user);
+ if ((ref($sections) eq 'ARRAY') && (@{$sections} > 0)) {
+ if (grep(/^all$/,@{$sections})) {
+ $secmatch = 1;
+ } elsif ($usec eq '') {
+ if (grep(/^none$/,@{$sections})) {
+ $secmatch = 1;
+ }
+ } else {
+ if (grep(/^\Q$usec\E$/,@{$sections})) {
+ $secmatch = 1;
+ }
+ }
+ if (!$secmatch) {
+ next;
+ }
+ }
+ if ($usec eq '') {
+ $usec = 'none';
+ }
+ if ($uname ne '' && $udom ne '') {
+ if ($hidepriv) {
+ if ((&Apache::lonnet::privileged($uname,$udom)) &&
+ (!$nothide{$uname.':'.$udom})) {
+ next;
+ }
+ }
+ if ($end > 0 && $end < $now) {
+ $status = 'previous';
+ } elsif ($start > $now) {
+ $status = 'future';
+ } else {
+ $status = 'active';
+ }
+ foreach my $type (keys(%{$types})) {
+ if ($status eq $type) {
+ if (!grep(/^\Q$type\E$/,@{$$users{$role}{$user}})) {
+ push(@{$$users{$role}{$user}},$type);
+ }
+ $match = 1;
+ }
+ }
+ if (($match) && (ref($userdata) eq 'HASH')) {
+ if (!exists($$userdata{$uname.':'.$udom})) {
+ &get_user_info($udom,$uname,\%idx,$userdata);
+ }
+ if (!grep(/^\Q$usec\E$/,@{$seclists{$uname.':'.$udom}})) {
+ push(@{$seclists{$uname.':'.$udom}},$usec);
+ }
+ if (ref($statushash) eq 'HASH') {
+ $statushash->{$uname.':'.$udom}{$role}{$usec} = $displaystatus{$status};
+ }
+ }
+ }
+ }
+ }
+ if (grep(/^ow$/,@{$roles})) {
+ if ((defined($cdom)) && (defined($cnum))) {
+ my %csettings = &Apache::lonnet::get('environment',['internal.courseowner'],$cdom,$cnum);
+ if ( defined($csettings{'internal.courseowner'}) ) {
+ my $owner = $csettings{'internal.courseowner'};
+ next if ($owner eq '');
+ my ($ownername,$ownerdom);
+ if ($owner =~ /^([^:]+):([^:]+)$/) {
+ $ownername = $1;
+ $ownerdom = $2;
+ } else {
+ $ownername = $owner;
+ $ownerdom = $cdom;
+ $owner = $ownername.':'.$ownerdom;
+ }
+ @{$$users{'ow'}{$owner}} = 'any';
+ if (defined($userdata) &&
+ !exists($$userdata{$owner})) {
+ &get_user_info($ownerdom,$ownername,\%idx,$userdata);
+ if (!grep(/^none$/,@{$seclists{$owner}})) {
+ push(@{$seclists{$owner}},'none');
+ }
+ if (ref($statushash) eq 'HASH') {
+ $statushash->{$owner}{'ow'}{'none'} = 'Any';
+ }
+ }
+ }
+ }
+ }
+ foreach my $user (keys(%seclists)) {
+ @{$seclists{$user}} = (sort {$a <=> $b} @{$seclists{$user}});
+ $$userdata{$user}[$idx{section}] = join(',',@{$seclists{$user}});
+ }
+ }
+ return;
+}
+
+sub get_user_info {
+ my ($udom,$uname,$idx,$userdata) = @_;
+ $$userdata{$uname.':'.$udom}[$$idx{fullname}] =
+ &plainname($uname,$udom,'lastname');
+ $$userdata{$uname.':'.$udom}[$$idx{uname}] = $uname;
+ $$userdata{$uname.':'.$udom}[$$idx{udom}] = $udom;
+ my %idhash = &Apache::lonnet::idrget($udom,($uname));
+ $$userdata{$uname.':'.$udom}[$$idx{id}] = $idhash{$uname};
+ return;
+}
+
+###############################################
+
+=pod
+
+=item * &get_user_quota()
+
+Retrieves quota assigned for storage of portfolio files for a user
+
+Incoming parameters:
+1. user's username
+2. user's domain
+
+Returns:
+1. Disk quota (in Mb) assigned to student.
+2. (Optional) Type of setting: custom or default
+ (individually assigned or default for user's
+ institutional status).
+3. (Optional) - User's institutional status (e.g., faculty, staff
+ or student - types as defined in localenroll::inst_usertypes
+ for user's domain, which determines default quota for user.
+4. (Optional) - Default quota which would apply to the user.
+
+If a value has been stored in the user's environment,
+it will return that, otherwise it returns the maximal default
+defined for the user's instituional status(es) in the domain.
+
+=cut
+
+###############################################
+
+
+sub get_user_quota {
+ my ($uname,$udom) = @_;
+ my ($quota,$quotatype,$settingstatus,$defquota);
+ if (!defined($udom)) {
+ $udom = $env{'user.domain'};
+ }
+ if (!defined($uname)) {
+ $uname = $env{'user.name'};
+ }
+ if (($udom eq '' || $uname eq '') ||
+ ($udom eq 'public') && ($uname eq 'public')) {
+ $quota = 0;
+ $quotatype = 'default';
+ $defquota = 0;
+ } else {
+ my $inststatus;
+ if ($udom eq $env{'user.domain'} && $uname eq $env{'user.name'}) {
+ $quota = $env{'environment.portfolioquota'};
+ $inststatus = $env{'environment.inststatus'};
+ } else {
+ my %userenv =
+ &Apache::lonnet::get('environment',['portfolioquota',
+ 'inststatus'],$udom,$uname);
+ my ($tmp) = keys(%userenv);
+ if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
+ $quota = $userenv{'portfolioquota'};
+ $inststatus = $userenv{'inststatus'};
+ } else {
+ undef(%userenv);
+ }
+ }
+ ($defquota,$settingstatus) = &default_quota($udom,$inststatus);
+ if ($quota eq '') {
+ $quota = $defquota;
+ $quotatype = 'default';
+ } else {
+ $quotatype = 'custom';
+ }
+ }
+ if (wantarray) {
+ return ($quota,$quotatype,$settingstatus,$defquota);
+ } else {
+ return $quota;
+ }
+}
+
+###############################################
+
+=pod
+
+=item * &default_quota()
+
+Retrieves default quota assigned for storage of user portfolio files,
+given an (optional) user's institutional status.
+
+Incoming parameters:
+1. domain
+2. (Optional) institutional status(es). This is a : separated list of
+ status types (e.g., faculty, staff, student etc.)
+ which apply to the user for whom the default is being retrieved.
+ If the institutional status string in undefined, the domain
+ default quota will be returned.
+
+Returns:
+1. Default disk quota (in Mb) for user portfolios in the domain.
+2. (Optional) institutional type which determined the value of the
+ default quota.
+
+If a value has been stored in the domain's configuration db,
+it will return that, otherwise it returns 20 (for backwards
+compatibility with domains which have not set up a configuration
+db file; the original statically defined portfolio quota was 20 Mb).
+
+If the user's status includes multiple types (e.g., staff and student),
+the largest default quota which applies to the user determines the
+default quota returned.
+
+=back
+
+=cut
+
+###############################################
+
+
+sub default_quota {
+ my ($udom,$inststatus) = @_;
+ my ($defquota,$settingstatus);
+ my %quotahash = &Apache::lonnet::get_dom('configuration',
+ ['quotas'],$udom);
+ if (ref($quotahash{'quotas'}) eq 'HASH') {
+ if ($inststatus ne '') {
+ my @statuses = map { &unescape($_); } split(/:/,$inststatus);
+ foreach my $item (@statuses) {
+ if (ref($quotahash{'quotas'}{'defaultquota'}) eq 'HASH') {
+ if ($quotahash{'quotas'}{'defaultquota'}{$item} ne '') {
+ if ($defquota eq '') {
+ $defquota = $quotahash{'quotas'}{'defaultquota'}{$item};
+ $settingstatus = $item;
+ } elsif ($quotahash{'quotas'}{'defaultquota'}{$item} > $defquota) {
+ $defquota = $quotahash{'quotas'}{'defaultquota'}{$item};
+ $settingstatus = $item;
+ }
+ }
+ } else {
+ if ($quotahash{'quotas'}{$item} ne '') {
+ if ($defquota eq '') {
+ $defquota = $quotahash{'quotas'}{$item};
+ $settingstatus = $item;
+ } elsif ($quotahash{'quotas'}{$item} > $defquota) {
+ $defquota = $quotahash{'quotas'}{$item};
+ $settingstatus = $item;
+ }
+ }
+ }
+ }
+ }
+ if ($defquota eq '') {
+ if (ref($quotahash{'quotas'}{'defaultquota'}) eq 'HASH') {
+ $defquota = $quotahash{'quotas'}{'defaultquota'}{'default'};
+ } else {
+ $defquota = $quotahash{'quotas'}{'default'};
+ }
+ $settingstatus = 'default';
+ }
+ } else {
+ $settingstatus = 'default';
+ $defquota = 20;
+ }
+ if (wantarray) {
+ return ($defquota,$settingstatus);
+ } else {
+ return $defquota;
+ }
+}
+
+sub get_secgrprole_info {
+ my ($cdom,$cnum,$needroles,$type) = @_;
+ my %sections_count = &get_sections($cdom,$cnum);
+ my @sections = (sort {$a <=> $b} keys(%sections_count));
+ my %curr_groups = &Apache::longroup::coursegroups($cdom,$cnum);
+ my @groups = sort(keys(%curr_groups));
+ my $allroles = [];
+ my $rolehash;
+ my $accesshash = {
+ active => 'Currently has access',
+ future => 'Will have future access',
+ previous => 'Previously had access',
+ };
+ if ($needroles) {
+ $rolehash = {'all' => 'all'};
+ my %user_roles = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
+ if (&Apache::lonnet::error(%user_roles)) {
+ undef(%user_roles);
+ }
+ foreach my $item (keys(%user_roles)) {
+ my ($role)=split(/\:/,$item,2);
+ if ($role eq 'cr') { next; }
+ if ($role =~ /^cr/) {
+ $$rolehash{$role} = (split('/',$role))[3];
+ } else {
+ $$rolehash{$role} = &Apache::lonnet::plaintext($role,$type);
+ }
+ }
+ foreach my $key (sort(keys(%{$rolehash}))) {
+ push(@{$allroles},$key);
+ }
+ push (@{$allroles},'st');
+ $$rolehash{'st'} = &Apache::lonnet::plaintext('st',$type);
+ }
+ return (\@sections,\@groups,$allroles,$rolehash,$accesshash);
+}
+
+sub user_picker {
+ my ($dom,$srch,$forcenewuser,$caller,$cancreate,$usertype,$context) = @_;
+ my $currdom = $dom;
+ my %curr_selected = (
+ srchin => 'dom',
+ srchby => 'lastname',
+ );
+ my $srchterm;
+ if ((ref($srch) eq 'HASH') && ($env{'form.origform'} ne 'crtusername')) {
+ if ($srch->{'srchby'} ne '') {
+ $curr_selected{'srchby'} = $srch->{'srchby'};
+ }
+ if ($srch->{'srchin'} ne '') {
+ $curr_selected{'srchin'} = $srch->{'srchin'};
+ }
+ if ($srch->{'srchtype'} ne '') {
+ $curr_selected{'srchtype'} = $srch->{'srchtype'};
+ }
+ if ($srch->{'srchdomain'} ne '') {
+ $currdom = $srch->{'srchdomain'};
+ }
+ $srchterm = $srch->{'srchterm'};
+ }
+ my %lt=&Apache::lonlocal::texthash(
+ 'usr' => 'Search criteria',
+ 'doma' => 'Domain/institution to search',
+ 'uname' => 'username',
+ 'lastname' => 'last name',
+ 'lastfirst' => 'last name, first name',
+ 'crs' => 'in this course',
+ 'dom' => 'in selected LON-CAPA domain',
+ 'alc' => 'all LON-CAPA',
+ 'instd' => 'in institutional directory for selected domain',
+ 'exact' => 'is',
+ 'contains' => 'contains',
+ 'begins' => 'begins with',
+ 'youm' => "You must include some text to search for.",
+ 'thte' => "The text you are searching for must contain at least two characters when using a 'begins' type search.",
+ 'thet' => "The text you are searching for must contain at least three characters when using a 'contains' type search.",
+ 'yomc' => "You must choose a domain when using an institutional directory search.",
+ 'ymcd' => "You must choose a domain when using a domain search.",
+ 'whus' => "When using searching by last,first you must include a comma as separator between last name and first name.",
+ 'whse' => "When searching by last,first you must include at least one character in the first name.",
+ 'thfo' => "The following need to be corrected before the search can be run:",
+ );
+ my $domform = &select_dom_form($currdom,'srchdomain',1,1);
+ my $srchinsel = ' \n";
+
+ my $srchbysel = ' \n";
+
+ my $srchtypesel = ' \n";
+
+ my ($newuserscript,$new_user_create);
+ my $context_dom = $env{'request.role.domain'};
+ if ($context eq 'requestcrs') {
+ if ($env{'form.coursedom'} ne '') {
+ $context_dom = $env{'form.coursedom'};
+ }
+ }
+ if ($forcenewuser) {
+ if (ref($srch) eq 'HASH') {
+ if ($srch->{'srchby'} eq 'uname' && $srch->{'srchtype'} eq 'exact' && $srch->{'srchin'} eq 'dom' && $srch->{'srchdomain'} eq $context_dom) {
+ if ($cancreate) {
+ $new_user_create = '
';
+ } else {
+ my $helplink = 'javascript:helpMenu('."'display'".')';
+ my %usertypetext = (
+ official => 'institutional',
+ unofficial => 'non-institutional',
+ );
+ $new_user_create = '
'
+ .&mt("You are not authorized to create new $usertypetext{$usertype} users in this domain.")
+ .' '
+ .&mt('Please contact the [_1]helpdesk[_2] for assistance.'
+ ,'','')
+ .'
';
+ }
+ }
+ }
+
+ $newuserscript = <<"ENDSCRIPT";
+
+function setSearch(createnew,callingForm) {
+ if (createnew == 1) {
+ for (var i=0; i
+//
+
+
+$new_user_create
+
+END_BLOCK
+
+ $output .= &Apache::lonhtmlcommon::start_pick_box().
+ &Apache::lonhtmlcommon::row_title($lt{'doma'}).
+ $domform.
+ &Apache::lonhtmlcommon::row_closure().
+ &Apache::lonhtmlcommon::row_title($lt{'usr'}).
+ $srchbysel.
+ $srchtypesel.
+ ''.
+ $srchinsel.
+ &Apache::lonhtmlcommon::row_closure(1).
+ &Apache::lonhtmlcommon::end_pick_box().
+ ' ';
+ return $output;
+}
+
+sub user_rule_check {
+ my ($usershash,$checks,$alerts,$rulematch,$inst_results,$curr_rules,$got_rules) = @_;
+ my $response;
+ if (ref($usershash) eq 'HASH') {
+ foreach my $user (keys(%{$usershash})) {
+ my ($uname,$udom) = split(/:/,$user);
+ next if ($udom eq '' || $uname eq '');
+ my ($id,$newuser);
+ if (ref($usershash->{$user}) eq 'HASH') {
+ $newuser = $usershash->{$user}->{'newuser'};
+ $id = $usershash->{$user}->{'id'};
+ }
+ my $inst_response;
+ if (ref($checks) eq 'HASH') {
+ if (defined($checks->{'username'})) {
+ ($inst_response,%{$inst_results->{$user}}) =
+ &Apache::lonnet::get_instuser($udom,$uname);
+ } elsif (defined($checks->{'id'})) {
+ ($inst_response,%{$inst_results->{$user}}) =
+ &Apache::lonnet::get_instuser($udom,undef,$id);
+ }
+ } else {
+ ($inst_response,%{$inst_results->{$user}}) =
+ &Apache::lonnet::get_instuser($udom,$uname);
+ return;
+ }
+ if (!$got_rules->{$udom}) {
+ my %domconfig = &Apache::lonnet::get_dom('configuration',
+ ['usercreation'],$udom);
+ if (ref($domconfig{'usercreation'}) eq 'HASH') {
+ foreach my $item ('username','id') {
+ if (ref($domconfig{'usercreation'}{$item.'_rule'}) eq 'ARRAY') {
+ $$curr_rules{$udom}{$item} =
+ $domconfig{'usercreation'}{$item.'_rule'};
+ }
+ }
+ }
+ $got_rules->{$udom} = 1;
+ }
+ foreach my $item (keys(%{$checks})) {
+ if (ref($$curr_rules{$udom}) eq 'HASH') {
+ if (ref($$curr_rules{$udom}{$item}) eq 'ARRAY') {
+ if (@{$$curr_rules{$udom}{$item}} > 0) {
+ my %rule_check = &Apache::lonnet::inst_rulecheck($udom,$uname,$id,$item,$$curr_rules{$udom}{$item});
+ foreach my $rule (@{$$curr_rules{$udom}{$item}}) {
+ if ($rule_check{$rule}) {
+ $$rulematch{$user}{$item} = $rule;
+ if ($inst_response eq 'ok') {
+ if (ref($inst_results) eq 'HASH') {
+ if (ref($inst_results->{$user}) eq 'HASH') {
+ if (keys(%{$inst_results->{$user}}) == 0) {
+ $$alerts{$item}{$udom}{$uname} = 1;
+ }
+ }
+ }
+ }
+ last;
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+ return;
+}
+
+sub user_rule_formats {
+ my ($domain,$domdesc,$curr_rules,$check) = @_;
+ my %text = (
+ 'username' => 'Usernames',
+ 'id' => 'IDs',
+ );
+ my $output;
+ my ($rules,$ruleorder) = &Apache::lonnet::inst_userrules($domain,$check);
+ if ((ref($rules) eq 'HASH') && (ref($ruleorder) eq 'ARRAY')) {
+ if (@{$ruleorder} > 0) {
+ $output = ' '.
+ &mt($text{$check}.' with the following format(s) may [_1]only[_2] be used for verified users at [_3]:',
+ '','',$domdesc).
+ '
';
+ foreach my $rule (@{$ruleorder}) {
+ if (ref($curr_rules) eq 'ARRAY') {
+ if (grep(/^\Q$rule\E$/,@{$curr_rules})) {
+ if (ref($rules->{$rule}) eq 'HASH') {
+ $output .= '
'.
+ &mt('Warning: decompression of the archive will overwrite the following items which already exist:').' '.
+ &start_data_table().
+ &start_data_table_header_row().
+ '
');
+ if (defined($$hash{$sample})) { $r->print($$hash{$sample}); }
+ $r->print('
');
+ }
+ $r->print(&end_data_table_row());
+ }
+ $r->print(&end_data_table().' '."\n");
+}
+
+######################################################
+######################################################
+
+=pod
+
+=item * &csv_print_select_table($r,$records,$d)
+
+Prints a table to create associations between values and table columns.
+
+$r is an Apache Request ref,
+$records is an arrayref from &Apache::loncommon::upfile_record_sep,
+$d is an array of 2 element arrays (internal name, displayed name,defaultcol)
+
+=cut
+
+######################################################
+######################################################
+sub csv_print_select_table {
+ my ($r,$records,$d) = @_;
+ my $i=0;
+ my $samples = &get_samples($records,1);
+ $r->print(&mt('Associate columns with student attributes.')."\n".
+ &start_data_table().&start_data_table_header_row().
+ '
'.&mt('Attribute').'
'.
+ '
'.&mt('Column').'
'.
+ &end_data_table_header_row()."\n");
+ foreach my $array_ref (@$d) {
+ my ($value,$display,$defaultcol)=@{ $array_ref };
+ $r->print(&start_data_table_row().'
'.$display.'
');
+
+ $r->print('
'.&end_data_table_row()."\n");
+ $i++;
+ }
+ $r->print(&end_data_table());
+ $i--;
+ return $i;
+}
+
+######################################################
+######################################################
+
+=pod
+
+=item * &csv_samples_select_table($r,$records,$d)
+
+Prints a table of sample values from the upload and can make associate samples to internal names.
+
+$r is an Apache Request ref,
+$records is an arrayref from &Apache::loncommon::upfile_record_sep,
+$d is an array of 2 element arrays (internal name, displayed name)
+
+=cut
+
+######################################################
+######################################################
+sub csv_samples_select_table {
+ my ($r,$records,$d) = @_;
+ my $i=0;
+ #
+ my $max_samples = 5;
+ my $samples = &get_samples($records,$max_samples);
+ $r->print(&start_data_table().
+ &start_data_table_header_row().'
');
+ foreach my $line (0..($max_samples-1)) {
+ if (defined($samples->[$line]{$key})) {
+ $r->print($samples->[$line]{$key}." \n");
+ }
+ }
+ $r->print('
'.&end_data_table_row());
+ $i++;
+ }
+ $r->print(&end_data_table());
+ $i--;
+ return($i);
+}
+
+######################################################
+######################################################
+
+=pod
+
+=item * &clean_excel_name($name)
+
+Returns a replacement for $name which does not contain any illegal characters.
+
+=cut
+
+######################################################
+######################################################
+sub clean_excel_name {
+ my ($name) = @_;
+ $name =~ s/[:\*\?\/\\]//g;
+ if (length($name) > 31) {
+ $name = substr($name,0,31);
+ }
+ return $name;
+}
+
+=pod
+
+=item * &check_if_partid_hidden($id,$symb,$udom,$uname)
+
+Returns either 1 or undef
+
+1 if the part is to be hidden, undef if it is to be shown
+
+Arguments are:
+
+$id the id of the part to be checked
+$symb, optional the symb of the resource to check
+$udom, optional the domain of the user to check for
+$uname, optional the username of the user to check for
+
+=cut
+
+sub check_if_partid_hidden {
+ my ($id,$symb,$udom,$uname) = @_;
+ my $hiddenparts=&Apache::lonnet::EXT('resource.0.hiddenparts',
+ $symb,$udom,$uname);
+ my $truth=1;
+ #if the string starts with !, then the list is the list to show not hide
+ if ($hiddenparts=~s/^\s*!//) { $truth=undef; }
+ my @hiddenlist=split(/,/,$hiddenparts);
+ foreach my $checkid (@hiddenlist) {
+ if ($checkid =~ /^\s*\Q$id\E\s*$/) { return $truth; }
+ }
+ return !$truth;
+}
+
+
+############################################################
+############################################################
+
+=pod
+
+=back
+
+=head1 cgi-bin script and graphing routines
+
+=over 4
+
+=item * &get_cgi_id()
+
+Inputs: none
+
+Returns an id which can be used to pass environment variables
+to various cgi-bin scripts. These environment variables will
+be removed from the users environment after a given time by
+the routine &Apache::lonnet::transfer_profile_to_env.
+
+=cut
+
+############################################################
+############################################################
+my $uniq=0;
+sub get_cgi_id {
+ $uniq=($uniq+1)%100000;
+ return (time.'_'.$$.'_'.$uniq);
+}
+
+############################################################
+############################################################
+
+=pod
+
+=item * &DrawBarGraph()
+
+Facilitates the plotting of data in a (stacked) bar graph.
+Puts plot definition data into the users environment in order for
+graph.png to plot it. Returns an tag for the plot.
+The bars on the plot are labeled '1','2',...,'n'.
+
+Inputs:
+
+=over 4
+
+=item $Title: string, the title of the plot
+
+=item $xlabel: string, text describing the X-axis of the plot
+
+=item $ylabel: string, text describing the Y-axis of the plot
+
+=item $Max: scalar, the maximum Y value to use in the plot
+If $Max is < any data point, the graph will not be rendered.
+
+=item $colors: array ref holding the colors to be used for the data sets when
+they are plotted. If undefined, default values will be used.
+
+=item $labels: array ref holding the labels to use on the x-axis for the bars.
+
+=item @Values: An array of array references. Each array reference holds data
+to be plotted in a stacked bar chart.
+
+=item If the final element of @Values is a hash reference the key/value
+pairs will be added to the graph definition.
+
+=back
+
+Returns:
+
+An tag which references graph.png and the appropriate identifying
+information for the plot.
+
+=cut
+
+############################################################
+############################################################
+sub DrawBarGraph {
+ my ($Title,$xlabel,$ylabel,$Max,$colors,$labels,@Values)=@_;
+ #
+ if (! defined($colors)) {
+ $colors = ['#33ff00',
+ '#0033cc', '#990000', '#aaaa66', '#663399', '#ff9933',
+ '#66ccff', '#ff9999', '#cccc33', '#660000', '#33cc66',
+ ];
+ }
+ my $extra_settings = {};
+ if (ref($Values[-1]) eq 'HASH') {
+ $extra_settings = pop(@Values);
+ }
+ #
+ my $identifier = &get_cgi_id();
+ my $id = 'cgi.'.$identifier;
+ if (! @Values || ref($Values[0]) ne 'ARRAY') {
+ return '';
+ }
+ #
+ my @Labels;
+ if (defined($labels)) {
+ @Labels = @$labels;
+ } else {
+ for (my $i=0;$i<@{$Values[0]};$i++) {
+ push (@Labels,$i+1);
+ }
+ }
+ #
+ my $NumBars = scalar(@{$Values[0]});
+ if ($NumBars < scalar(@Labels)) { $NumBars = scalar(@Labels); }
+ my %ValuesHash;
+ my $NumSets=1;
+ foreach my $array (@Values) {
+ next if (! ref($array));
+ $ValuesHash{$id.'.data.'.$NumSets++} =
+ join(',',@$array);
+ }
+ #
+ my ($height,$width,$xskip,$bar_width) = (200,120,1,15);
+ if ($NumBars < 3) {
+ $width = 120+$NumBars*32;
+ $xskip = 1;
+ $bar_width = 30;
+ } elsif ($NumBars < 5) {
+ $width = 120+$NumBars*20;
+ $xskip = 1;
+ $bar_width = 20;
+ } elsif ($NumBars < 10) {
+ $width = 120+$NumBars*15;
+ $xskip = 1;
+ $bar_width = 15;
+ } elsif ($NumBars <= 25) {
+ $width = 120+$NumBars*11;
+ $xskip = 5;
+ $bar_width = 8;
+ } elsif ($NumBars <= 50) {
+ $width = 120+$NumBars*8;
+ $xskip = 5;
+ $bar_width = 4;
+ } else {
+ $width = 120+$NumBars*8;
+ $xskip = 5;
+ $bar_width = 4;
+ }
+ #
+ $Max = 1 if ($Max < 1);
+ if ( int($Max) < $Max ) {
+ $Max++;
+ $Max = int($Max);
+ }
+ $Title = '' if (! defined($Title));
+ $xlabel = '' if (! defined($xlabel));
+ $ylabel = '' if (! defined($ylabel));
+ $ValuesHash{$id.'.title'} = &escape($Title);
+ $ValuesHash{$id.'.xlabel'} = &escape($xlabel);
+ $ValuesHash{$id.'.ylabel'} = &escape($ylabel);
+ $ValuesHash{$id.'.y_max_value'} = $Max;
+ $ValuesHash{$id.'.NumBars'} = $NumBars;
+ $ValuesHash{$id.'.NumSets'} = $NumSets;
+ $ValuesHash{$id.'.PlotType'} = 'bar';
+ $ValuesHash{$id.'.Colors'} = join(',',@{$colors});
+ $ValuesHash{$id.'.height'} = $height;
+ $ValuesHash{$id.'.width'} = $width;
+ $ValuesHash{$id.'.xskip'} = $xskip;
+ $ValuesHash{$id.'.bar_width'} = $bar_width;
+ $ValuesHash{$id.'.labels'} = join(',',@Labels);
+ #
+ # Deal with other parameters
+ while (my ($key,$value) = each(%$extra_settings)) {
+ $ValuesHash{$id.'.'.$key} = $value;
+ }
+ #
+ &Apache::lonnet::appenv(\%ValuesHash);
+ return '';
+}
+
+############################################################
+############################################################
+
+=pod
+
+=item * &DrawXYGraph()
+
+Facilitates the plotting of data in an XY graph.
+Puts plot definition data into the users environment in order for
+graph.png to plot it. Returns an tag for the plot.
+
+Inputs:
+
+=over 4
+
+=item $Title: string, the title of the plot
+
+=item $xlabel: string, text describing the X-axis of the plot
+
+=item $ylabel: string, text describing the Y-axis of the plot
+
+=item $Max: scalar, the maximum Y value to use in the plot
+If $Max is < any data point, the graph will not be rendered.
+
+=item $colors: Array ref containing the hex color codes for the data to be
+plotted in. If undefined, default values will be used.
+
+=item $Xlabels: Array ref containing the labels to be used for the X-axis.
+
+=item $Ydata: Array ref containing Array refs.
+Each of the contained arrays will be plotted as a separate curve.
+
+=item %Values: hash indicating or overriding any default values which are
+passed to graph.png.
+Possible values are: width, xskip, x_ticks, x_tick_offset, among others.
+
+=back
+
+Returns:
+
+An tag which references graph.png and the appropriate identifying
+information for the plot.
+
+=cut
+
+############################################################
+############################################################
+sub DrawXYGraph {
+ my ($Title,$xlabel,$ylabel,$Max,$colors,$Xlabels,$Ydata,%Values)=@_;
+ #
+ # Create the identifier for the graph
+ my $identifier = &get_cgi_id();
+ my $id = 'cgi.'.$identifier;
+ #
+ $Title = '' if (! defined($Title));
+ $xlabel = '' if (! defined($xlabel));
+ $ylabel = '' if (! defined($ylabel));
+ my %ValuesHash =
+ (
+ $id.'.title' => &escape($Title),
+ $id.'.xlabel' => &escape($xlabel),
+ $id.'.ylabel' => &escape($ylabel),
+ $id.'.y_max_value'=> $Max,
+ $id.'.labels' => join(',',@$Xlabels),
+ $id.'.PlotType' => 'XY',
+ );
+ #
+ if (defined($colors) && ref($colors) eq 'ARRAY') {
+ $ValuesHash{$id.'.Colors'} = join(',',@{$colors});
+ }
+ #
+ if (! ref($Ydata) || ref($Ydata) ne 'ARRAY') {
+ return '';
+ }
+ my $NumSets=1;
+ foreach my $array (@{$Ydata}){
+ next if (! ref($array));
+ $ValuesHash{$id.'.data.'.$NumSets++} = join(',',@$array);
+ }
+ $ValuesHash{$id.'.NumSets'} = $NumSets-1;
+ #
+ # Deal with other parameters
+ while (my ($key,$value) = each(%Values)) {
+ $ValuesHash{$id.'.'.$key} = $value;
+ }
+ #
+ &Apache::lonnet::appenv(\%ValuesHash);
+ return '';
+}
+
+############################################################
+############################################################
+
+=pod
+
+=item * &DrawXYYGraph()
+
+Facilitates the plotting of data in an XY graph with two Y axes.
+Puts plot definition data into the users environment in order for
+graph.png to plot it. Returns an tag for the plot.
+
+Inputs:
+
+=over 4
+
+=item $Title: string, the title of the plot
+
+=item $xlabel: string, text describing the X-axis of the plot
+
+=item $ylabel: string, text describing the Y-axis of the plot
+
+=item $colors: Array ref containing the hex color codes for the data to be
+plotted in. If undefined, default values will be used.
+
+=item $Xlabels: Array ref containing the labels to be used for the X-axis.
+
+=item $Ydata1: The first data set
+
+=item $Min1: The minimum value of the left Y-axis
+
+=item $Max1: The maximum value of the left Y-axis
+
+=item $Ydata2: The second data set
+
+=item $Min2: The minimum value of the right Y-axis
+
+=item $Max2: The maximum value of the left Y-axis
+
+=item %Values: hash indicating or overriding any default values which are
+passed to graph.png.
+Possible values are: width, xskip, x_ticks, x_tick_offset, among others.
+
+=back
+
+Returns:
+
+An tag which references graph.png and the appropriate identifying
+information for the plot.
+
+=cut
+
+############################################################
+############################################################
+sub DrawXYYGraph {
+ my ($Title,$xlabel,$ylabel,$colors,$Xlabels,$Ydata1,$Min1,$Max1,
+ $Ydata2,$Min2,$Max2,%Values)=@_;
+ #
+ # Create the identifier for the graph
+ my $identifier = &get_cgi_id();
+ my $id = 'cgi.'.$identifier;
+ #
+ $Title = '' if (! defined($Title));
+ $xlabel = '' if (! defined($xlabel));
+ $ylabel = '' if (! defined($ylabel));
+ my %ValuesHash =
+ (
+ $id.'.title' => &escape($Title),
+ $id.'.xlabel' => &escape($xlabel),
+ $id.'.ylabel' => &escape($ylabel),
+ $id.'.labels' => join(',',@$Xlabels),
+ $id.'.PlotType' => 'XY',
+ $id.'.NumSets' => 2,
+ $id.'.two_axes' => 1,
+ $id.'.y1_max_value' => $Max1,
+ $id.'.y1_min_value' => $Min1,
+ $id.'.y2_max_value' => $Max2,
+ $id.'.y2_min_value' => $Min2,
+ );
+ #
+ if (defined($colors) && ref($colors) eq 'ARRAY') {
+ $ValuesHash{$id.'.Colors'} = join(',',@{$colors});
+ }
+ #
+ if (! ref($Ydata1) || ref($Ydata1) ne 'ARRAY' ||
+ ! ref($Ydata2) || ref($Ydata2) ne 'ARRAY'){
+ return '';
+ }
+ my $NumSets=1;
+ foreach my $array ($Ydata1,$Ydata2){
+ next if (! ref($array));
+ $ValuesHash{$id.'.data.'.$NumSets++} = join(',',@$array);
+ }
+ #
+ # Deal with other parameters
+ while (my ($key,$value) = each(%Values)) {
+ $ValuesHash{$id.'.'.$key} = $value;
+ }
+ #
+ &Apache::lonnet::appenv(\%ValuesHash);
+ return '';
+}
+
+############################################################
+############################################################
+
+=pod
+
+=back
+
+=head1 Statistics helper routines?
+
+Bad place for them but what the hell.
+
+=over 4
+
+=item * &chartlink()
+
+Returns a link to the chart for a specific student.
+
+Inputs:
+
+=over 4
+
+=item $linktext: The text of the link
+
+=item $sname: The students username
+
+=item $sdomain: The students domain
+
+=back
+
+=back
+
+=cut
+
+############################################################
+############################################################
+sub chartlink {
+ my ($linktext, $sname, $sdomain) = @_;
+ my $link = ''.$linktext.'';
+}
+
+#######################################################
+#######################################################
+
+=pod
+
+=head1 Course Environment Routines
+
+=over 4
+
+=item * &restore_course_settings()
+
+=item * &store_course_settings()
+
+Restores/Store indicated form parameters from the course environment.
+Will not overwrite existing values of the form parameters.
+
+Inputs:
+a scalar describing the data (e.g. 'chart', 'problem_analysis')
+
+a hash ref describing the data to be stored. For example:
+
+%Save_Parameters = ('Status' => 'scalar',
+ 'chartoutputmode' => 'scalar',
+ 'chartoutputdata' => 'scalar',
+ 'Section' => 'array',
+ 'Group' => 'array',
+ 'StudentData' => 'array',
+ 'Maps' => 'array');
+
+Returns: both routines return nothing
+
+=back
+
+=cut
+
+#######################################################
+#######################################################
+sub store_course_settings {
+ return &store_settings($env{'request.course.id'},@_);
+}
+
+sub store_settings {
+ # save to the environment
+ # appenv the same items, just to be safe
+ my $udom = $env{'user.domain'};
+ my $uname = $env{'user.name'};
+ my ($context,$prefix,$Settings) = @_;
+ my %SaveHash;
+ my %AppHash;
+ while (my ($setting,$type) = each(%$Settings)) {
+ my $basename = join('.','internal',$context,$prefix,$setting);
+ my $envname = 'environment.'.$basename;
+ if (exists($env{'form.'.$setting})) {
+ # Save this value away
+ if ($type eq 'scalar' &&
+ (! exists($env{$envname}) ||
+ $env{$envname} ne $env{'form.'.$setting})) {
+ $SaveHash{$basename} = $env{'form.'.$setting};
+ $AppHash{$envname} = $env{'form.'.$setting};
+ } elsif ($type eq 'array') {
+ my $stored_form;
+ if (ref($env{'form.'.$setting})) {
+ $stored_form = join(',',
+ map {
+ &escape($_);
+ } sort(@{$env{'form.'.$setting}}));
+ } else {
+ $stored_form =
+ &escape($env{'form.'.$setting});
+ }
+ # Determine if the array contents are the same.
+ if ($stored_form ne $env{$envname}) {
+ $SaveHash{$basename} = $stored_form;
+ $AppHash{$envname} = $stored_form;
+ }
+ }
+ }
+ }
+ my $put_result = &Apache::lonnet::put('environment',\%SaveHash,
+ $udom,$uname);
+ if ($put_result !~ /^(ok|delayed)/) {
+ &Apache::lonnet::logthis('unable to save form parameters, '.
+ 'got error:'.$put_result);
+ }
+ # Make sure these settings stick around in this session, too
+ &Apache::lonnet::appenv(\%AppHash);
+ return;
+}
+
+sub restore_course_settings {
+ return &restore_settings($env{'request.course.id'},@_);
+}
+
+sub restore_settings {
+ my ($context,$prefix,$Settings) = @_;
+ while (my ($setting,$type) = each(%$Settings)) {
+ next if (exists($env{'form.'.$setting}));
+ my $envname = 'environment.internal.'.$context.'.'.$prefix.
+ '.'.$setting;
+ if (exists($env{$envname})) {
+ if ($type eq 'scalar') {
+ $env{'form.'.$setting} = $env{$envname};
+ } elsif ($type eq 'array') {
+ $env{'form.'.$setting} = [
+ map {
+ &unescape($_);
+ } split(',',$env{$envname})
+ ];
+ }
+ }
+ }
+}
+
+#######################################################
+#######################################################
+
+=pod
+
+=head1 Domain E-mail Routines
+
+=over 4
+
+=item * &build_recipient_list()
+
+Build recipient lists for five types of e-mail:
+(a) Error Reports, (b) Package Updates, (c) lonstatus warnings/errors
+(d) Help requests, (e) Course requests needing approval, generated by
+lonerrorhandler.pm, CHECKRPMS, loncron, lonsupportreq.pm and
+loncoursequeueadmin.pm respectively.
+
+Inputs:
+defmail (scalar - email address of default recipient),
+mailing type (scalar - errormail, packagesmail, or helpdeskmail),
+defdom (domain for which to retrieve configuration settings),
+origmail (scalar - email address of recipient from loncapa.conf,
+i.e., predates configuration by DC via domainprefs.pm
+
+Returns: comma separated list of addresses to which to send e-mail.
+
+=back
+
+=cut
+
+############################################################
+############################################################
+sub build_recipient_list {
+ my ($defmail,$mailing,$defdom,$origmail) = @_;
+ my @recipients;
+ my $otheremails;
+ my %domconfig =
+ &Apache::lonnet::get_dom('configuration',['contacts'],$defdom);
+ if (ref($domconfig{'contacts'}) eq 'HASH') {
+ if (exists($domconfig{'contacts'}{$mailing})) {
+ if (ref($domconfig{'contacts'}{$mailing}) eq 'HASH') {
+ my @contacts = ('adminemail','supportemail');
+ foreach my $item (@contacts) {
+ if ($domconfig{'contacts'}{$mailing}{$item}) {
+ my $addr = $domconfig{'contacts'}{$item};
+ if (!grep(/^\Q$addr\E$/,@recipients)) {
+ push(@recipients,$addr);
+ }
+ }
+ $otheremails = $domconfig{'contacts'}{$mailing}{'others'};
+ }
+ }
+ } elsif ($origmail ne '') {
+ push(@recipients,$origmail);
+ }
+ } elsif ($origmail ne '') {
+ push(@recipients,$origmail);
+ }
+ if (defined($defmail)) {
+ if ($defmail ne '') {
+ push(@recipients,$defmail);
+ }
+ }
+ if ($otheremails) {
+ my @others;
+ if ($otheremails =~ /,/) {
+ @others = split(/,/,$otheremails);
+ } else {
+ push(@others,$otheremails);
+ }
+ foreach my $addr (@others) {
+ if (!grep(/^\Q$addr\E$/,@recipients)) {
+ push(@recipients,$addr);
+ }
+ }
+ }
+ my $recipientlist = join(',',@recipients);
+ return $recipientlist;
+}
+
+############################################################
+############################################################
+
+=pod
+
+=head1 Course Catalog Routines
+
+=over 4
+
+=item * &gather_categories()
+
+Converts category definitions - keys of categories hash stored in
+coursecategories in configuration.db on the primary library server in a
+domain - to an array. Also generates javascript and idx hash used to
+generate Domain Coordinator interface for editing Course Categories.
+
+Inputs:
+
+categories (reference to hash of category definitions).
+
+cats (reference to array of arrays/hashes which encapsulates hierarchy of
+ categories and subcategories).
+
+idx (reference to hash of counters used in Domain Coordinator interface for
+ editing Course Categories).
+
+jsarray (reference to array of categories used to create Javascript arrays for
+ Domain Coordinator interface for editing Course Categories).
+
+Returns: nothing
+
+Side effects: populates cats, idx and jsarray.
+
+=cut
+
+sub gather_categories {
+ my ($categories,$cats,$idx,$jsarray) = @_;
+ my %counters;
+ my $num = 0;
+ foreach my $item (keys(%{$categories})) {
+ my ($cat,$container,$depth) = map { &unescape($_); } split(/:/,$item);
+ if ($container eq '' && $depth == 0) {
+ $cats->[$depth][$categories->{$item}] = $cat;
+ } else {
+ $cats->[$depth]{$container}[$categories->{$item}] = $cat;
+ }
+ my ($escitem,$tail) = split(/:/,$item,2);
+ if ($counters{$tail} eq '') {
+ $counters{$tail} = $num;
+ $num ++;
+ }
+ if (ref($idx) eq 'HASH') {
+ $idx->{$item} = $counters{$tail};
+ }
+ if (ref($jsarray) eq 'ARRAY') {
+ push(@{$jsarray->[$counters{$tail}]},$item);
+ }
+ }
+ return;
+}
+
+=pod
+
+=item * &extract_categories()
+
+Used to generate breadcrumb trails for course categories.
+
+Inputs:
+
+categories (reference to hash of category definitions).
+
+cats (reference to array of arrays/hashes which encapsulates hierarchy of
+ categories and subcategories).
+
+trails (reference to array of breacrumb trails for each category).
+
+allitems (reference to hash - key is category key
+ (format: escaped(name):escaped(parent category):depth in hierarchy).
+
+idx (reference to hash of counters used in Domain Coordinator interface for
+ editing Course Categories).
+
+jsarray (reference to array of categories used to create Javascript arrays for
+ Domain Coordinator interface for editing Course Categories).
+
+subcats (reference to hash of arrays containing all subcategories within each
+ category, -recursive)
+
+Returns: nothing
+
+Side effects: populates trails and allitems hash references.
+
+=cut
+
+sub extract_categories {
+ my ($categories,$cats,$trails,$allitems,$idx,$jsarray,$subcats) = @_;
+ if (ref($categories) eq 'HASH') {
+ &gather_categories($categories,$cats,$idx,$jsarray);
+ if (ref($cats->[0]) eq 'ARRAY') {
+ for (my $i=0; $i<@{$cats->[0]}; $i++) {
+ my $name = $cats->[0][$i];
+ my $item = &escape($name).'::0';
+ my $trailstr;
+ if ($name eq 'instcode') {
+ $trailstr = &mt('Official courses (with institutional codes)');
+ } elsif ($name eq 'communities') {
+ $trailstr = &mt('Communities');
+ } else {
+ $trailstr = $name;
+ }
+ if ($allitems->{$item} eq '') {
+ push(@{$trails},$trailstr);
+ $allitems->{$item} = scalar(@{$trails})-1;
+ }
+ my @parents = ($name);
+ if (ref($cats->[1]{$name}) eq 'ARRAY') {
+ for (my $j=0; $j<@{$cats->[1]{$name}}; $j++) {
+ my $category = $cats->[1]{$name}[$j];
+ if (ref($subcats) eq 'HASH') {
+ push(@{$subcats->{$item}},&escape($category).':'.&escape($name).':1');
+ }
+ &recurse_categories($cats,2,$category,$trails,$allitems,\@parents,$subcats);
+ }
+ } else {
+ if (ref($subcats) eq 'HASH') {
+ $subcats->{$item} = [];
+ }
+ }
+ }
+ }
+ }
+ return;
+}
+
+=pod
+
+=item *&recurse_categories()
+
+Recursively used to generate breadcrumb trails for course categories.
+
+Inputs:
+
+cats (reference to array of arrays/hashes which encapsulates hierarchy of
+ categories and subcategories).
+
+depth (current depth in hierarchy of categories and sub-categories - 0 indexed).
+
+category (current course category, for which breadcrumb trail is being generated).
+
+trails (reference to array of breadcrumb trails for each category).
+
+allitems (reference to hash - key is category key
+ (format: escaped(name):escaped(parent category):depth in hierarchy).
+
+parents (array containing containers directories for current category,
+ back to top level).
+
+Returns: nothing
+
+Side effects: populates trails and allitems hash references
+
+=cut
+
+sub recurse_categories {
+ my ($cats,$depth,$category,$trails,$allitems,$parents,$subcats) = @_;
+ my $shallower = $depth - 1;
+ if (ref($cats->[$depth]{$category}) eq 'ARRAY') {
+ for (my $k=0; $k<@{$cats->[$depth]{$category}}; $k++) {
+ my $name = $cats->[$depth]{$category}[$k];
+ my $item = &escape($category).':'.&escape($parents->[-1]).':'.$shallower;
+ my $trailstr = join(' -> ',(@{$parents},$category));
+ if ($allitems->{$item} eq '') {
+ push(@{$trails},$trailstr);
+ $allitems->{$item} = scalar(@{$trails})-1;
+ }
+ my $deeper = $depth+1;
+ push(@{$parents},$category);
+ if (ref($subcats) eq 'HASH') {
+ my $subcat = &escape($name).':'.$category.':'.$depth;
+ for (my $j=@{$parents}; $j>=0; $j--) {
+ my $higher;
+ if ($j > 0) {
+ $higher = &escape($parents->[$j]).':'.
+ &escape($parents->[$j-1]).':'.$j;
+ } else {
+ $higher = &escape($parents->[$j]).'::'.$j;
+ }
+ push(@{$subcats->{$higher}},$subcat);
+ }
+ }
+ &recurse_categories($cats,$deeper,$name,$trails,$allitems,$parents,
+ $subcats);
+ pop(@{$parents});
+ }
+ } else {
+ my $item = &escape($category).':'.&escape($parents->[-1]).':'.$shallower;
+ my $trailstr = join(' -> ',(@{$parents},$category));
+ if ($allitems->{$item} eq '') {
+ push(@{$trails},$trailstr);
+ $allitems->{$item} = scalar(@{$trails})-1;
+ }
+ }
+ return;
+}
+
+=pod
+
+=item *&assign_categories_table()
+
+Create a datatable for display of hierarchical categories in a domain,
+with checkboxes to allow a course to be categorized.
+
+Inputs:
+
+cathash - reference to hash of categories defined for the domain (from
+ configuration.db)
+
+currcat - scalar with an & separated list of categories assigned to a course.
+
+type - scalar contains course type (Course or Community).
+
+Returns: $output (markup to be displayed)
+
+=cut
+
+sub assign_categories_table {
+ my ($cathash,$currcat,$type) = @_;
+ my $output;
+ if (ref($cathash) eq 'HASH') {
+ my (@cats,@trails,%allitems,%idx,@jsarray,@path,$maxdepth);
+ &extract_categories($cathash,\@cats,\@trails,\%allitems,\%idx,\@jsarray);
+ $maxdepth = scalar(@cats);
+ if (@cats > 0) {
+ my $itemcount = 0;
+ if (ref($cats[0]) eq 'ARRAY') {
+ my @currcategories;
+ if ($currcat ne '') {
+ @currcategories = split('&',$currcat);
+ }
+ my $table;
+ for (my $i=0; $i<@{$cats[0]}; $i++) {
+ my $parent = $cats[0][$i];
+ next if ($parent eq 'instcode');
+ if ($type eq 'Community') {
+ next unless ($parent eq 'communities');
+ } else {
+ next if ($parent eq 'communities');
+ }
+ my $css_class = $itemcount%2?' class="LC_odd_row"':'';
+ my $item = &escape($parent).'::0';
+ my $checked = '';
+ if (@currcategories > 0) {
+ if (grep(/^\Q$item\E$/,@currcategories)) {
+ $checked = ' checked="checked"';
+ }
+ }
+ my $parent_title = $parent;
+ if ($parent eq 'communities') {
+ $parent_title = &mt('Communities');
+ }
+ $table .= '
';
+ $itemcount ++;
+ }
+ if ($itemcount) {
+ $output = &Apache::loncommon::start_data_table().
+ $table.
+ &Apache::loncommon::end_data_table();
+ }
+ }
+ }
+ }
+ return $output;
+}
+
+=pod
+
+=item *&assign_category_rows()
+
+Create a datatable row for display of nested categories in a domain,
+with checkboxes to allow a course to be categorized,called recursively.
+
+Inputs:
+
+itemcount - track row number for alternating colors
+
+cats - reference to array of arrays/hashes which encapsulates hierarchy of
+ categories and subcategories.
+
+depth - current depth in hierarchy of categories and sub-categories - 0 indexed.
+
+parent - parent of current category item
+
+path - Array containing all categories back up through the hierarchy from the
+ current category to the top level.
+
+currcategories - reference to array of current categories assigned to the course
+
+Returns: $output (markup to be displayed).
+
+=cut
+
+sub assign_category_rows {
+ my ($itemcount,$cats,$depth,$parent,$path,$currcategories) = @_;
+ my ($text,$name,$item,$chgstr);
+ if (ref($cats) eq 'ARRAY') {
+ my $maxdepth = scalar(@{$cats});
+ if (ref($cats->[$depth]) eq 'HASH') {
+ if (ref($cats->[$depth]{$parent}) eq 'ARRAY') {
+ my $numchildren = @{$cats->[$depth]{$parent}};
+ my $css_class = $itemcount%2?' class="LC_odd_row"':'';
+ $text .= '
';
+ for (my $j=0; $j<$numchildren; $j++) {
+ $name = $cats->[$depth]{$parent}[$j];
+ $item = &escape($name).':'.&escape($parent).':'.$depth;
+ my $deeper = $depth+1;
+ my $checked = '';
+ if (ref($currcategories) eq 'ARRAY') {
+ if (@{$currcategories} > 0) {
+ if (grep(/^\Q$item\E$/,@{$currcategories})) {
+ $checked = ' checked="checked"';
+ }
+ }
+ }
+ $text .= '