File:  [LON-CAPA] / loncom / interface / loncommon.pm
Revision 1.474: download - view: text, annotated - select for diffs
Wed Nov 29 07:46:39 2006 UTC (17 years, 6 months ago) by raeburn
Branches: MAIN
CVS tags: HEAD
evb privilege - with this privilege users evade blocking of communication functionality defined by blocks placed by users with dcm privilege.

dcm privilege - this is now used to determine if link to block setting is displayed.

loncommon::findallcourses() now return a hash, where the keys are courseIDs instead of an array of courseIDs.  Places where findallcourses() was called - lonannounce, lonpickcourse changed accordingly.

loncommon::findallcourses() now reports courses for a user where the user's only role was a custom role.

lonnet::allowed() can now take a fourth optional argument ($role) which allows privs to be investigated for roles other than the user's currently active role

&blockcheck, &parse_block_record(), and &build_block_table() moved from lonmsgdisplay to loncommon, so they are available for evaluation of blocking state for other communication functions besides COM.

Each block record for a blocking event in a course is now a hash, with key=values of the hash being setter = username:domain of user who set block, title=event title for block, and blocks = hash of blocked features ('com','chat','boards','port','groups').

Backwards compatibility retained with previous : separated text for block record value.

    1: # The LearningOnline Network with CAPA
    2: # a pile of common routines
    3: #
    4: # $Id: loncommon.pm,v 1.474 2006/11/29 07:46:39 raeburn Exp $
    5: #
    6: # Copyright Michigan State University Board of Trustees
    7: #
    8: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
    9: #
   10: # LON-CAPA is free software; you can redistribute it and/or modify
   11: # it under the terms of the GNU General Public License as published by
   12: # the Free Software Foundation; either version 2 of the License, or
   13: # (at your option) any later version.
   14: #
   15: # LON-CAPA is distributed in the hope that it will be useful,
   16: # but WITHOUT ANY WARRANTY; without even the implied warranty of
   17: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   18: # GNU General Public License for more details.
   19: #
   20: # You should have received a copy of the GNU General Public License
   21: # along with LON-CAPA; if not, write to the Free Software
   22: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
   23: #
   24: # /home/httpd/html/adm/gpl.txt
   25: #
   26: # http://www.lon-capa.org/
   27: #
   28: 
   29: # Makes a table out of the previous attempts
   30: # Inputs result_from_symbread, user, domain, course_id
   31: # Reads in non-network-related .tab files
   32: 
   33: # POD header:
   34: 
   35: =pod
   36: 
   37: =head1 NAME
   38: 
   39: Apache::loncommon - pile of common routines
   40: 
   41: =head1 SYNOPSIS
   42: 
   43: Common routines for manipulating connections, student answers,
   44:     domains, common Javascript fragments, etc.
   45: 
   46: =head1 OVERVIEW
   47: 
   48: A collection of commonly used subroutines that don't have a natural
   49: home anywhere else. This collection helps remove
   50: redundancy from other modules and increase efficiency of memory usage.
   51: 
   52: =cut 
   53: 
   54: # End of POD header
   55: package Apache::loncommon;
   56: 
   57: use strict;
   58: use Apache::lonnet;
   59: use GDBM_File;
   60: use POSIX qw(strftime mktime);
   61: use Apache::lonmenu();
   62: use Apache::lonlocal;
   63: use HTML::Entities;
   64: use Apache::lonhtmlcommon();
   65: use Apache::loncoursedata();
   66: use Apache::lontexconvert();
   67: use Apache::lonclonecourse();
   68: use LONCAPA;
   69: 
   70: my $readit;
   71: 
   72: ##
   73: ## Global Variables
   74: ##
   75: 
   76: # ----------------------------------------------- Filetypes/Languages/Copyright
   77: my %language;
   78: my %supported_language;
   79: my %cprtag;
   80: my %scprtag;
   81: my %fe; my %fd; my %fm;
   82: my %category_extensions;
   83: 
   84: # ---------------------------------------------- Designs
   85: 
   86: my %designhash;
   87: 
   88: # ---------------------------------------------- Thesaurus variables
   89: #
   90: # %Keywords:
   91: #      A hash used by &keyword to determine if a word is considered a keyword.
   92: # $thesaurus_db_file 
   93: #      Scalar containing the full path to the thesaurus database.
   94: 
   95: my %Keywords;
   96: my $thesaurus_db_file;
   97: 
   98: #
   99: # Initialize values from language.tab, copyright.tab, filetypes.tab,
  100: # thesaurus.tab, and filecategories.tab.
  101: #
  102: BEGIN {
  103:     # Variable initialization
  104:     $thesaurus_db_file = $Apache::lonnet::perlvar{'lonTabDir'}."/thesaurus.db";
  105:     #
  106:     unless ($readit) {
  107: # ------------------------------------------------------------------- languages
  108:     {
  109:         my $langtabfile = $Apache::lonnet::perlvar{'lonTabDir'}.
  110:                                    '/language.tab';
  111:         if ( open(my $fh,"<$langtabfile") ) {
  112:             while (my $line = <$fh>) {
  113:                 next if ($line=~/^\#/);
  114:                 chomp($line);
  115:                 my ($key,$two,$country,$three,$enc,$val,$sup)=(split(/\t/,$line));
  116:                 $language{$key}=$val.' - '.$enc;
  117:                 if ($sup) {
  118:                     $supported_language{$key}=$sup;
  119:                 }
  120:             }
  121:             close($fh);
  122:         }
  123:     }
  124: # ------------------------------------------------------------------ copyrights
  125:     {
  126:         my $copyrightfile = $Apache::lonnet::perlvar{'lonIncludes'}.
  127:                                   '/copyright.tab';
  128:         if ( open (my $fh,"<$copyrightfile") ) {
  129:             while (my $line = <$fh>) {
  130:                 next if ($line=~/^\#/);
  131:                 chomp($line);
  132:                 my ($key,$val)=(split(/\s+/,$line,2));
  133:                 $cprtag{$key}=$val;
  134:             }
  135:             close($fh);
  136:         }
  137:     }
  138: # ----------------------------------------------------------- source copyrights
  139:     {
  140:         my $sourcecopyrightfile = $Apache::lonnet::perlvar{'lonIncludes'}.
  141:                                   '/source_copyright.tab';
  142:         if ( open (my $fh,"<$sourcecopyrightfile") ) {
  143:             while (my $line = <$fh>) {
  144:                 next if ($line =~ /^\#/);
  145:                 chomp($line);
  146:                 my ($key,$val)=(split(/\s+/,$line,2));
  147:                 $scprtag{$key}=$val;
  148:             }
  149:             close($fh);
  150:         }
  151:     }
  152: 
  153: # -------------------------------------------------------------- domain designs
  154: 
  155:     my $filename;
  156:     my $designdir=$Apache::lonnet::perlvar{'lonTabDir'}.'/lonDomColors';
  157:     opendir(DIR,$designdir);
  158:     while ($filename=readdir(DIR)) {
  159: 	if ($filename!~/\.tab$/) { next; }
  160: 	my ($domain)=($filename=~/^(\w+)\./);
  161: 	{
  162: 	    my $designfile = $designdir.'/'.$filename;
  163: 	    if ( open (my $fh,"<$designfile") ) {
  164: 		while (my $line = <$fh>) {
  165: 		    next if ($line =~ /^\#/);
  166: 		    chomp($line);
  167: 		    my ($key,$val)=(split(/\=/,$line));
  168: 		    if ($val) { $designhash{$domain.'.'.$key}=$val; }
  169: 		}
  170: 		close($fh);
  171: 	    }
  172: 	}
  173: 
  174:     }
  175:     closedir(DIR);
  176: 
  177: 
  178: # ------------------------------------------------------------- file categories
  179:     {
  180:         my $categoryfile = $Apache::lonnet::perlvar{'lonTabDir'}.
  181:                                   '/filecategories.tab';
  182:         if ( open (my $fh,"<$categoryfile") ) {
  183: 	    while (my $line = <$fh>) {
  184: 		next if ($line =~ /^\#/);
  185: 		chomp($line);
  186:                 my ($extension,$category)=(split(/\s+/,$line,2));
  187:                 push @{$category_extensions{lc($category)}},$extension;
  188:             }
  189:             close($fh);
  190:         }
  191: 
  192:     }
  193: # ------------------------------------------------------------------ file types
  194:     {
  195:         my $typesfile = $Apache::lonnet::perlvar{'lonTabDir'}.
  196:                '/filetypes.tab';
  197:         if ( open (my $fh,"<$typesfile") ) {
  198:             while (my $line = <$fh>) {
  199: 		next if ($line =~ /^\#/);
  200: 		chomp($line);
  201:                 my ($ending,$emb,$mime,$descr)=split(/\s+/,$line,4);
  202:                 if ($descr ne '') {
  203:                     $fe{$ending}=lc($emb);
  204:                     $fd{$ending}=$descr;
  205:                     if ($mime ne 'unk') { $fm{$ending}=$mime; }
  206:                 }
  207:             }
  208:             close($fh);
  209:         }
  210:     }
  211:     &Apache::lonnet::logthis(
  212:               "<font color=yellow>INFO: Read file types</font>");
  213:     $readit=1;
  214:     }  # end of unless($readit) 
  215:     
  216: }
  217: 
  218: ###############################################################
  219: ##           HTML and Javascript Helper Functions            ##
  220: ###############################################################
  221: 
  222: =pod 
  223: 
  224: =head1 HTML and Javascript Functions
  225: 
  226: =over 4
  227: 
  228: =item * browser_and_searcher_javascript ()
  229: 
  230: X<browsing, javascript>X<searching, javascript>Returns a string
  231: containing javascript with two functions, C<openbrowser> and
  232: C<opensearcher>. Returned string does not contain E<lt>scriptE<gt>
  233: tags.
  234: 
  235: =item * openbrowser(formname,elementname,only,omit) [javascript]
  236: 
  237: inputs: formname, elementname, only, omit
  238: 
  239: formname and elementname indicate the name of the html form and name of
  240: the element that the results of the browsing selection are to be placed in. 
  241: 
  242: Specifying 'only' will restrict the browser to displaying only files
  243: with the given extension.  Can be a comma separated list.
  244: 
  245: Specifying 'omit' will restrict the browser to NOT displaying files
  246: with the given extension.  Can be a comma separated list.
  247: 
  248: =item * opensearcher(formname, elementname) [javascript]
  249: 
  250: Inputs: formname, elementname
  251: 
  252: formname and elementname specify the name of the html form and the name
  253: of the element the selection from the search results will be placed in.
  254: 
  255: =cut
  256: 
  257: sub browser_and_searcher_javascript {
  258:     my ($mode)=@_;
  259:     if (!defined($mode)) { $mode='edit'; }
  260:     my $resurl=&escape_single(&lastresurl());
  261:     return <<END;
  262: // <!-- BEGIN LON-CAPA Internal
  263:     var editbrowser = null;
  264:     function openbrowser(formname,elementname,only,omit,titleelement) {
  265:         var url = '$resurl/?';
  266:         if (editbrowser == null) {
  267:             url += 'launch=1&';
  268:         }
  269:         url += 'catalogmode=interactive&';
  270:         url += 'mode=$mode&';
  271:         url += 'form=' + formname + '&';
  272:         if (only != null) {
  273:             url += 'only=' + only + '&';
  274:         } else {
  275:             url += 'only=&';
  276: 	}
  277:         if (omit != null) {
  278:             url += 'omit=' + omit + '&';
  279:         } else {
  280:             url += 'omit=&';
  281: 	}
  282:         if (titleelement != null) {
  283:             url += 'titleelement=' + titleelement + '&';
  284:         } else {
  285: 	    url += 'titleelement=&';
  286: 	}
  287:         url += 'element=' + elementname + '';
  288:         var title = 'Browser';
  289:         var options = 'scrollbars=1,resizable=1,menubar=0,toolbar=1,location=1';
  290:         options += ',width=700,height=600';
  291:         editbrowser = open(url,title,options,'1');
  292:         editbrowser.focus();
  293:     }
  294:     var editsearcher;
  295:     function opensearcher(formname,elementname,titleelement) {
  296:         var url = '/adm/searchcat?';
  297:         if (editsearcher == null) {
  298:             url += 'launch=1&';
  299:         }
  300:         url += 'catalogmode=interactive&';
  301:         url += 'mode=$mode&';
  302:         url += 'form=' + formname + '&';
  303:         if (titleelement != null) {
  304:             url += 'titleelement=' + titleelement + '&';
  305:         } else {
  306: 	    url += 'titleelement=&';
  307: 	}
  308:         url += 'element=' + elementname + '';
  309:         var title = 'Search';
  310:         var options = 'scrollbars=1,resizable=1,menubar=0,toolbar=1,location=1';
  311:         options += ',width=700,height=600';
  312:         editsearcher = open(url,title,options,'1');
  313:         editsearcher.focus();
  314:     }
  315: // END LON-CAPA Internal -->
  316: END
  317: }
  318: 
  319: sub lastresurl {
  320:     if ($env{'environment.lastresurl'}) {
  321: 	return $env{'environment.lastresurl'}
  322:     } else {
  323: 	return '/res';
  324:     }
  325: }
  326: 
  327: sub storeresurl {
  328:     my $resurl=&Apache::lonnet::clutter(shift);
  329:     unless ($resurl=~/^\/res/) { return 0; }
  330:     $resurl=~s/\/$//;
  331:     &Apache::lonnet::put('environment',{'lastresurl' => $resurl});
  332:     &Apache::lonnet::appenv('environment.lastresurl' => $resurl);
  333:     return 1;
  334: }
  335: 
  336: sub studentbrowser_javascript {
  337:    unless (
  338:             (($env{'request.course.id'}) && 
  339:              (&Apache::lonnet::allowed('srm',$env{'request.course.id'})
  340: 	      || &Apache::lonnet::allowed('srm',$env{'request.course.id'}.
  341: 					  '/'.$env{'request.course.sec'})
  342: 	      ))
  343:          || ($env{'request.role'}=~/^(au|dc|su)/)
  344:           ) { return ''; }  
  345:    return (<<'ENDSTDBRW');
  346: <script type="text/javascript" language="Javascript" >
  347:     var stdeditbrowser;
  348:     function openstdbrowser(formname,uname,udom,roleflag) {
  349:         var url = '/adm/pickstudent?';
  350:         var filter;
  351:         eval('filter=document.'+formname+'.'+uname+'.value;');
  352:         if (filter != null) {
  353:            if (filter != '') {
  354:                url += 'filter='+filter+'&';
  355: 	   }
  356:         }
  357:         url += 'form=' + formname + '&unameelement='+uname+
  358:                                     '&udomelement='+udom;
  359: 	if (roleflag) { url+="&roles=1"; }
  360:         var title = 'Student_Browser';
  361:         var options = 'scrollbars=1,resizable=1,menubar=0';
  362:         options += ',width=700,height=600';
  363:         stdeditbrowser = open(url,title,options,'1');
  364:         stdeditbrowser.focus();
  365:     }
  366: </script>
  367: ENDSTDBRW
  368: }
  369: 
  370: sub selectstudent_link {
  371:    my ($form,$unameele,$udomele)=@_;
  372:    if ($env{'request.course.id'}) {  
  373:        if (!&Apache::lonnet::allowed('srm',$env{'request.course.id'})
  374: 	   && !&Apache::lonnet::allowed('srm',$env{'request.course.id'}.
  375: 					'/'.$env{'request.course.sec'})) {
  376: 	   return '';
  377:        }
  378:        return "<a href='".'javascript:openstdbrowser("'.$form.'","'.$unameele.
  379:         '","'.$udomele.'");'."'>".&mt('Select User')."</a>";
  380:    }
  381:    if ($env{'request.role'}=~/^(au|dc|su)/) {
  382:        return "<a href='".'javascript:openstdbrowser("'.$form.'","'.$unameele.
  383:         '","'.$udomele.'",1);'."'>".&mt('Select User')."</a>";
  384:    }
  385:    return '';
  386: }
  387: 
  388: sub coursebrowser_javascript {
  389:     my ($domainfilter,$sec_element,$formname)=@_;
  390:     my $crs_or_grp_alert = &mt('Please select the type of LON-CAPA entity - Course or Group - for which you wish to add/modify a user role');
  391:    my $output = '
  392: <script type="text/javascript" language="Javascript" >
  393:     var stdeditbrowser;'."\n";
  394:    $output .= <<"ENDSTDBRW";
  395:     function opencrsbrowser(formname,uname,udom,desc,extra_element,multflag,crstype) {
  396:         var url = '/adm/pickcourse?';
  397:         var domainfilter = '';
  398:         var formid = getFormIdByName(formname);
  399:         if (formid > -1) {
  400:             var domid = getIndexByName(formid,udom);
  401:             if (domid > -1) {
  402:                 if (document.forms[formid].elements[domid].type == 'select-one') {
  403:                     domainfilter=document.forms[formid].elements[domid].options[document.forms[formid].elements[domid].selectedIndex].value;
  404:                 }
  405:                 if (document.forms[formid].elements[domid].type == 'hidden') {
  406:                     domainfilter=document.forms[formid].elements[domid].value;
  407:                 }
  408:             }
  409:         }
  410:         if (domainfilter != null) {
  411:            if (domainfilter != '') {
  412:                url += 'domainfilter='+domainfilter+'&';
  413: 	   }
  414:         }
  415:         url += 'form=' + formname + '&cnumelement='+uname+
  416: 	                            '&cdomelement='+udom+
  417:                                     '&cnameelement='+desc;
  418:         if (extra_element !=null && extra_element != '') {
  419:             if (formname == 'rolechoice') {
  420:                 url += '&roleelement='+extra_element;
  421:                 if (domainfilter == null || domainfilter == '') {
  422:                     url += '&domainfilter='+extra_element;
  423:                 }
  424:             }
  425:             else {
  426:                 if (formname == 'portform') {
  427:                     url += '&setroles='+extra_element;
  428:                 }
  429:             }     
  430:         }
  431:         if (multflag !=null && multflag != '') {
  432:             url += '&multiple='+multflag;
  433:         }
  434:         if (crstype == 'Course/Group') {
  435:             if (formname == 'cu') {
  436:                 crstype = document.cu.crstype.options[document.cu.crstype.selectedIndex].value; 
  437:                 if (crstype == "") {
  438:                     alert("$crs_or_grp_alert");
  439:                     return;
  440:                 }
  441:             }
  442:         }
  443:         if (crstype !=null && crstype != '') {
  444:             url += '&type='+crstype;
  445:         }
  446:         var title = 'Course_Browser';
  447:         var options = 'scrollbars=1,resizable=1,menubar=0';
  448:         options += ',width=700,height=600';
  449:         stdeditbrowser = open(url,title,options,'1');
  450:         stdeditbrowser.focus();
  451:     }
  452: 
  453:     function getFormIdByName(formname) {
  454:         for (var i=0;i<document.forms.length;i++) {
  455:             if (document.forms[i].name == formname) {
  456:                 return i;
  457:             }
  458:         }
  459:         return -1; 
  460:     }
  461: 
  462:     function getIndexByName(formid,item) {
  463:         for (var i=0;i<document.forms[formid].elements.length;i++) {
  464:             if (document.forms[formid].elements[i].name == item) {
  465:                 return i;
  466:             }
  467:         }
  468:         return -1;
  469:     }
  470: ENDSTDBRW
  471:     if ($sec_element ne '') {
  472:         $output .= &setsec_javascript($sec_element,$formname);
  473:     }
  474:     $output .= '
  475: </script>';
  476:     return $output;
  477: }
  478: 
  479: sub setsec_javascript {
  480:     my ($sec_element,$formname) = @_;
  481:     my $setsections = qq|
  482: function setSect(sectionlist) {
  483:     var sectionsArray = sectionlist.split(",");
  484:     var numSections = sectionsArray.length;
  485:     document.$formname.$sec_element.length = 0;
  486:     if (numSections == 0) {
  487:         document.$formname.$sec_element.multiple=false;
  488:         document.$formname.$sec_element.size=1;
  489:         document.$formname.$sec_element.options[0] = new Option('No existing sections','',false,false)
  490:     } else {
  491:         if (numSections == 1) {
  492:             document.$formname.$sec_element.multiple=false;
  493:             document.$formname.$sec_element.size=1;
  494:             document.$formname.$sec_element.options[0] = new Option('Select','',true,true);
  495:             document.$formname.$sec_element.options[1] = new Option('No section','',false,false)
  496:             document.$formname.$sec_element.options[2] = new Option(sectionsArray[0],sectionsArray[0],false,false);
  497:         } else {
  498:             for (var i=0; i<numSections; i++) {
  499:                 document.$formname.$sec_element.options[i] = new Option(sectionsArray[i],sectionsArray[i],false,false)
  500:             }
  501:             document.$formname.$sec_element.multiple=true
  502:             if (numSections < 3) {
  503:                 document.$formname.$sec_element.size=numSections;
  504:             } else {
  505:                 document.$formname.$sec_element.size=3;
  506:             }
  507:             document.$formname.$sec_element.options[0].selected = false
  508:         }
  509:     }
  510: }
  511: |;
  512:     return $setsections;
  513: }
  514: 
  515: 
  516: sub selectcourse_link {
  517:    my ($form,$unameele,$udomele,$desc,$extra_element,$multflag,$selecttype)=@_;
  518:     return "<a href='".'javascript:opencrsbrowser("'.$form.'","'.$unameele.
  519:         '","'.$udomele.'","'.$desc.'","'.$extra_element.'","'.$multflag.'","'.$selecttype.'");'."'>".&mt('Select [_1]',$selecttype)."</a>";
  520: }
  521: 
  522: sub check_uncheck_jscript {
  523:     my $jscript = <<"ENDSCRT";
  524: function checkAll(field) {
  525:     if (field.length > 0) {
  526:         for (i = 0; i < field.length; i++) {
  527:             field[i].checked = true ;
  528:         }
  529:     } else {
  530:         field.checked = true
  531:     }
  532: }
  533:  
  534: function uncheckAll(field) {
  535:     if (field.length > 0) {
  536:         for (i = 0; i < field.length; i++) {
  537:             field[i].checked = false ;
  538:         }     } else {
  539:         field.checked = false ;
  540:     }
  541: }
  542: ENDSCRT
  543:     return $jscript;
  544: }
  545: 
  546: 
  547: =pod
  548: 
  549: =item * linked_select_forms(...)
  550: 
  551: linked_select_forms returns a string containing a <script></script> block
  552: and html for two <select> menus.  The select menus will be linked in that
  553: changing the value of the first menu will result in new values being placed
  554: in the second menu.  The values in the select menu will appear in alphabetical
  555: order.
  556: 
  557: linked_select_forms takes the following ordered inputs:
  558: 
  559: =over 4
  560: 
  561: =item * $formname, the name of the <form> tag
  562: 
  563: =item * $middletext, the text which appears between the <select> tags
  564: 
  565: =item * $firstdefault, the default value for the first menu
  566: 
  567: =item * $firstselectname, the name of the first <select> tag
  568: 
  569: =item * $secondselectname, the name of the second <select> tag
  570: 
  571: =item * $hashref, a reference to a hash containing the data for the menus.
  572: 
  573: =back 
  574: 
  575: Below is an example of such a hash.  Only the 'text', 'default', and 
  576: 'select2' keys must appear as stated.  keys(%menu) are the possible 
  577: values for the first select menu.  The text that coincides with the 
  578: first menu value is given in $menu{$choice1}->{'text'}.  The values 
  579: and text for the second menu are given in the hash pointed to by 
  580: $menu{$choice1}->{'select2'}.  
  581: 
  582:  my %menu = ( A1 => { text =>"Choice A1" ,
  583:                        default => "B3",
  584:                        select2 => { 
  585:                            B1 => "Choice B1",
  586:                            B2 => "Choice B2",
  587:                            B3 => "Choice B3",
  588:                            B4 => "Choice B4"
  589:                            }
  590:                    },
  591:                A2 => { text =>"Choice A2" ,
  592:                        default => "C2",
  593:                        select2 => { 
  594:                            C1 => "Choice C1",
  595:                            C2 => "Choice C2",
  596:                            C3 => "Choice C3"
  597:                            }
  598:                    },
  599:                A3 => { text =>"Choice A3" ,
  600:                        default => "D6",
  601:                        select2 => { 
  602:                            D1 => "Choice D1",
  603:                            D2 => "Choice D2",
  604:                            D3 => "Choice D3",
  605:                            D4 => "Choice D4",
  606:                            D5 => "Choice D5",
  607:                            D6 => "Choice D6",
  608:                            D7 => "Choice D7"
  609:                            }
  610:                    }
  611:                );
  612: 
  613: =cut
  614: 
  615: sub linked_select_forms {
  616:     my ($formname,
  617:         $middletext,
  618:         $firstdefault,
  619:         $firstselectname,
  620:         $secondselectname, 
  621:         $hashref
  622:         ) = @_;
  623:     my $second = "document.$formname.$secondselectname";
  624:     my $first = "document.$formname.$firstselectname";
  625:     # output the javascript to do the changing
  626:     my $result = '';
  627:     $result.="<script type=\"text/javascript\">\n";
  628:     $result.="var select2data = new Object();\n";
  629:     $" = '","';
  630:     my $debug = '';
  631:     foreach my $s1 (sort(keys(%$hashref))) {
  632:         $result.="select2data.d_$s1 = new Object();\n";        
  633:         $result.="select2data.d_$s1.def = new String('".
  634:             $hashref->{$s1}->{'default'}."');\n";
  635:         $result.="select2data.d_$s1.values = new Array(";        
  636:         my @s2values = sort(keys( %{ $hashref->{$s1}->{'select2'} } ));
  637:         $result.="\"@s2values\");\n";
  638:         $result.="select2data.d_$s1.texts = new Array(";        
  639:         my @s2texts;
  640:         foreach my $value (@s2values) {
  641:             push @s2texts, $hashref->{$s1}->{'select2'}->{$value};
  642:         }
  643:         $result.="\"@s2texts\");\n";
  644:     }
  645:     $"=' ';
  646:     $result.= <<"END";
  647: 
  648: function select1_changed() {
  649:     // Determine new choice
  650:     var newvalue = "d_" + $first.value;
  651:     // update select2
  652:     var values     = select2data[newvalue].values;
  653:     var texts      = select2data[newvalue].texts;
  654:     var select2def = select2data[newvalue].def;
  655:     var i;
  656:     // out with the old
  657:     for (i = 0; i < $second.options.length; i++) {
  658:         $second.options[i] = null;
  659:     }
  660:     // in with the nuclear
  661:     for (i=0;i<values.length; i++) {
  662:         $second.options[i] = new Option(values[i]);
  663:         $second.options[i].value = values[i];
  664:         $second.options[i].text = texts[i];
  665:         if (values[i] == select2def) {
  666:             $second.options[i].selected = true;
  667:         }
  668:     }
  669: }
  670: </script>
  671: END
  672:     # output the initial values for the selection lists
  673:     $result .= "<select size=\"1\" name=\"$firstselectname\" onchange=\"select1_changed()\">\n";
  674:     foreach my $value (sort(keys(%$hashref))) {
  675:         $result.="    <option value=\"$value\" ";
  676:         $result.=" selected=\"selected\" " if ($value eq $firstdefault);
  677:         $result.=">".&mt($hashref->{$value}->{'text'})."</option>\n";
  678:     }
  679:     $result .= "</select>\n";
  680:     my %select2 = %{$hashref->{$firstdefault}->{'select2'}};
  681:     $result .= $middletext;
  682:     $result .= "<select size=\"1\" name=\"$secondselectname\">\n";
  683:     my $seconddefault = $hashref->{$firstdefault}->{'default'};
  684:     foreach my $value (sort(keys(%select2))) {
  685:         $result.="    <option value=\"$value\" ";        
  686:         $result.=" selected=\"selected\" " if ($value eq $seconddefault);
  687:         $result.=">".&mt($select2{$value})."</option>\n";
  688:     }
  689:     $result .= "</select>\n";
  690:     #    return $debug;
  691:     return $result;
  692: }   #  end of sub linked_select_forms {
  693: 
  694: =pod
  695: 
  696: =item * help_open_topic($topic, $text, $stayOnPage, $width, $height)
  697: 
  698: Returns a string corresponding to an HTML link to the given help
  699: $topic, where $topic corresponds to the name of a .tex file in
  700: /home/httpd/html/adm/help/tex, with underscores replaced by
  701: spaces. 
  702: 
  703: $text will optionally be linked to the same topic, allowing you to
  704: link text in addition to the graphic. If you do not want to link
  705: text, but wish to specify one of the later parameters, pass an
  706: empty string. 
  707: 
  708: $stayOnPage is a value that will be interpreted as a boolean. If true,
  709: the link will not open a new window. If false, the link will open
  710: a new window using Javascript. (Default is false.) 
  711: 
  712: $width and $height are optional numerical parameters that will
  713: override the width and height of the popped up window, which may
  714: be useful for certain help topics with big pictures included. 
  715: 
  716: =cut
  717: 
  718: sub help_open_topic {
  719:     my ($topic, $text, $stayOnPage, $width, $height) = @_;
  720:     $text = "" if (not defined $text);
  721:     $stayOnPage = 0 if (not defined $stayOnPage);
  722:     if ($env{'browser.interface'} eq 'textual' ||
  723: 	$env{'environment.remote'} eq 'off' ) {
  724: 	$stayOnPage=1;
  725:     }
  726:     $width = 350 if (not defined $width);
  727:     $height = 400 if (not defined $height);
  728:     my $filename = $topic;
  729:     $filename =~ s/ /_/g;
  730: 
  731:     my $template = "";
  732:     my $link;
  733: 
  734:     $topic=~s/\W/\_/g;
  735: 
  736:     if (!$stayOnPage)
  737:     {
  738: 	$link = "javascript:void(open('/adm/help/${filename}.hlp', 'Help_for_$topic', 'menubar=0,toolbar=1,scrollbars=1,width=$width,height=$height,resizable=yes'))";
  739:     }
  740:     else
  741:     {
  742: 	$link = "/adm/help/${filename}.hlp";
  743:     }
  744: 
  745:     # Add the text
  746:     if ($text ne "")
  747:     {
  748: 	$template .= 
  749:   "<table bgcolor='#3333AA' cellspacing='1' cellpadding='1' border='0'><tr>".
  750:   "<td bgcolor='#5555FF'><a target=\"_top\" href=\"$link\"><font color='#FFFFFF' size='2'>$text</font></a>";
  751:     }
  752: 
  753:     # Add the graphic
  754:     my $title = &mt('Online Help');
  755:     my $helpicon=&lonhttpdurl("/adm/help/gif/smallHelp.gif");
  756:     $template .= <<"ENDTEMPLATE";
  757:  <a target="_top" href="$link" title="$title"><img src="$helpicon" border="0" alt="(Help: $topic)" /></a>
  758: ENDTEMPLATE
  759:     if ($text ne '') { $template.='</td></tr></table>' };
  760:     return $template;
  761: 
  762: }
  763: 
  764: # This is a quicky function for Latex cheatsheet editing, since it 
  765: # appears in at least four places
  766: sub helpLatexCheatsheet {
  767:     my $other = shift;
  768:     my $addOther = '';
  769:     if ($other) {
  770: 	$addOther = Apache::loncommon::help_open_topic($other, shift,
  771: 						       undef, undef, 600) .
  772: 							   '</td><td>';
  773:     }
  774:     return '<table><tr><td>'.
  775: 	$addOther .
  776: 	&Apache::loncommon::help_open_topic("Greek_Symbols",'Greek Symbols',
  777: 					    undef,undef,600)
  778: 	.'</td><td>'.
  779: 	&Apache::loncommon::help_open_topic("Other_Symbols",'Other Symbols',
  780: 					    undef,undef,600)
  781: 	.'</td></tr></table>';
  782: }
  783: 
  784: sub general_help {
  785:     my $helptopic='Student_Intro';
  786:     if ($env{'request.role'}=~/^(ca|au)/) {
  787: 	$helptopic='Authoring_Intro';
  788:     } elsif ($env{'request.role'}=~/^cc/) {
  789: 	$helptopic='Course_Coordination_Intro';
  790:     }
  791:     return $helptopic;
  792: }
  793: 
  794: sub update_help_link {
  795:     my ($topic,$component_help,$faq,$bug,$stayOnPage) = @_;
  796:     my $origurl = $ENV{'REQUEST_URI'};
  797:     $origurl=~s|^/~|/priv/|;
  798:     my $timestamp = time;
  799:     foreach my $datum (\$topic,\$component_help,\$faq,\$bug,\$origurl) {
  800:         $$datum = &escape($$datum);
  801:     }
  802: 
  803:     my $banner_link = "/adm/helpmenu?page=banner&amp;topic=$topic&amp;component_help=$component_help&amp;faq=$faq&amp;bug=$bug&amp;origurl=$origurl&amp;stamp=$timestamp&amp;stayonpage=$stayOnPage";
  804:     my $output .= <<"ENDOUTPUT";
  805: <script type="text/javascript">
  806: banner_link = '$banner_link';
  807: </script>
  808: ENDOUTPUT
  809:     return $output;
  810: }
  811: 
  812: # now just updates the help link and generates a blue icon
  813: sub help_open_menu {
  814:     my ($topic,$component_help,$faq,$bug,$stayOnPage,$width,$height,$text) 
  815: 	= @_;
  816:     
  817:     $stayOnPage = 0 if (not defined $stayOnPage);
  818:     if ($env{'browser.interface'} eq 'textual' ||
  819: 	$env{'environment.remote'} eq 'off' ) {
  820: 	$stayOnPage=1;
  821:     }
  822:     my $output;
  823:     if ($component_help) {
  824: 	if (!$text) {
  825: 	    $output=&help_open_topic($component_help,undef,$stayOnPage,
  826: 				       $width,$height);
  827: 	} else {
  828: 	    my $help_text;
  829: 	    $help_text=&unescape($topic);
  830: 	    $output='<table><tr><td>'.
  831: 		&help_open_topic($component_help,$help_text,$stayOnPage,
  832: 				 $width,$height).'</td></tr></table>';
  833: 	}
  834:     }
  835:     my $banner_link = &update_help_link($topic,$component_help,$faq,$bug,$stayOnPage);
  836:     return $output.$banner_link;
  837: }
  838: 
  839: sub top_nav_help {
  840:     my ($text) = @_;
  841: 
  842:     $text = &mt($text);
  843: 
  844:     my $stayOnPage = 
  845: 	($env{'browser.interface'}  eq 'textual' ||
  846: 	 $env{'environment.remote'} eq 'off' );
  847:     my $link=  ($stayOnPage) ? "javascript:helpMenu('display')"
  848: 	                     : "javascript:helpMenu('open')";
  849:     my $banner_link = &update_help_link(undef,undef,undef,undef,$stayOnPage);
  850: 
  851:     my $title = &mt('Get help');
  852: 
  853:     return <<"END";
  854: $banner_link
  855:  <a href="$link" title="$title">$text</a>
  856: END
  857: }
  858: 
  859: sub help_menu_js {
  860:     my ($text) = @_;
  861: 
  862:     my $stayOnPage = 
  863: 	($env{'browser.interface'}  eq 'textual' ||
  864: 	 $env{'environment.remote'} eq 'off' );
  865: 
  866:     my $width = 620;
  867:     my $height = 600;
  868:     my $helptopic=&general_help();
  869:     my $details_link = '/adm/help/'.$helptopic.'.hlp';
  870:     my $nothing=&Apache::lonhtmlcommon::javascript_nothing();
  871:     my $start_page =
  872:         &Apache::loncommon::start_page('Help Menu', undef,
  873: 				       {'frameset'    => 1,
  874: 					'js_ready'    => 1,
  875: 					'add_entries' => {
  876: 					    'border' => '0',
  877: 					    'rows'   => "105,*",},});
  878:     my $end_page =
  879:         &Apache::loncommon::end_page({'frameset' => 1,
  880: 				      'js_ready' => 1,});
  881: 
  882:     my $template .= <<"ENDTEMPLATE";
  883: <script type="text/javascript">
  884: // <!-- BEGIN LON-CAPA Internal
  885: // <![CDATA[
  886: var banner_link = '';
  887: function helpMenu(target) {
  888:     var caller = this;
  889:     if (target == 'open') {
  890:         var newWindow = null;
  891:         try {
  892:             newWindow =  window.open($nothing,"helpmenu","HEIGHT=$height,WIDTH=$width,resizable=yes,scrollbars=yes" )
  893:         }
  894:         catch(error) {
  895:             writeHelp(caller);
  896:             return;
  897:         }
  898:         if (newWindow) {
  899:             caller = newWindow;
  900:         }
  901:     }
  902:     writeHelp(caller);
  903:     return;
  904: }
  905: function writeHelp(caller) {
  906:     caller.document.writeln('$start_page<frame name="bannerframe"  src="'+banner_link+'" /><frame name="bodyframe" src="$details_link" /> $end_page')
  907:     caller.document.close()
  908:     caller.focus()
  909: }
  910: // ]]>
  911: // END LON-CAPA Internal -->
  912: </script>
  913: ENDTEMPLATE
  914:     return $template;
  915: }
  916: 
  917: sub help_open_bug {
  918:     my ($topic, $text, $stayOnPage, $width, $height) = @_;
  919:     unless ($env{'user.adv'}) { return ''; }
  920:     unless ($Apache::lonnet::perlvar{'BugzillaHost'}) { return ''; }
  921:     $text = "" if (not defined $text);
  922:     $stayOnPage = 0 if (not defined $stayOnPage);
  923:     if ($env{'browser.interface'} eq 'textual' ||
  924: 	$env{'environment.remote'} eq 'off' ) {
  925: 	$stayOnPage=1;
  926:     }
  927:     $width = 600 if (not defined $width);
  928:     $height = 600 if (not defined $height);
  929: 
  930:     $topic=~s/\W+/\+/g;
  931:     my $link='';
  932:     my $template='';
  933:     my $url=$Apache::lonnet::perlvar{'BugzillaHost'}.'enter_bug.cgi?product=LON-CAPA&amp;bug_file_loc='.
  934: 	&escape($ENV{'REQUEST_URI'}).'&amp;component='.$topic;
  935:     if (!$stayOnPage)
  936:     {
  937: 	$link = "javascript:void(open('$url', 'Bugzilla', 'menubar=0,toolbar=1,scrollbars=1,width=$width,height=$height,resizable=yes'))";
  938:     }
  939:     else
  940:     {
  941: 	$link = $url;
  942:     }
  943:     # Add the text
  944:     if ($text ne "")
  945:     {
  946: 	$template .= 
  947:   "<table bgcolor='#AA3333' cellspacing='1' cellpadding='1' border='0'><tr>".
  948:   "<td bgcolor='#FF5555'><a target=\"_top\" href=\"$link\"><font color='#FFFFFF' size='2'>$text</font></a>";
  949:     }
  950: 
  951:     # Add the graphic
  952:     my $title = &mt('Report a Bug');
  953:     my $bugicon=&lonhttpdurl("/adm/lonMisc/smallBug.gif");
  954:     $template .= <<"ENDTEMPLATE";
  955:  <a target="_top" href="$link" title="$title"><img src="$bugicon" border="0" alt="(Bug: $topic)" /></a>
  956: ENDTEMPLATE
  957:     if ($text ne '') { $template.='</td></tr></table>' };
  958:     return $template;
  959: 
  960: }
  961: 
  962: sub help_open_faq {
  963:     my ($topic, $text, $stayOnPage, $width, $height) = @_;
  964:     unless ($env{'user.adv'}) { return ''; }
  965:     unless ($Apache::lonnet::perlvar{'FAQHost'}) { return ''; }
  966:     $text = "" if (not defined $text);
  967:     $stayOnPage = 0 if (not defined $stayOnPage);
  968:     if ($env{'browser.interface'} eq 'textual' ||
  969: 	$env{'environment.remote'} eq 'off' ) {
  970: 	$stayOnPage=1;
  971:     }
  972:     $width = 350 if (not defined $width);
  973:     $height = 400 if (not defined $height);
  974: 
  975:     $topic=~s/\W+/\+/g;
  976:     my $link='';
  977:     my $template='';
  978:     my $url=$Apache::lonnet::perlvar{'FAQHost'}.'/fom/cache/'.$topic.'.html';
  979:     if (!$stayOnPage)
  980:     {
  981: 	$link = "javascript:void(open('$url', 'FAQ-O-Matic', 'menubar=0,toolbar=1,scrollbars=1,width=$width,height=$height,resizable=yes'))";
  982:     }
  983:     else
  984:     {
  985: 	$link = $url;
  986:     }
  987: 
  988:     # Add the text
  989:     if ($text ne "")
  990:     {
  991: 	$template .= 
  992:   "<table bgcolor='#337733' cellspacing='1' cellpadding='1' border='0'><tr>".
  993:   "<td bgcolor='#448844'><a target=\"_top\" href=\"$link\"><font color='#FFFFFF' size='2'>$text</font></a>";
  994:     }
  995: 
  996:     # Add the graphic
  997:     my $title = &mt('View the FAQ');
  998:     my $faqicon=&lonhttpdurl("/adm/lonMisc/smallFAQ.gif");
  999:     $template .= <<"ENDTEMPLATE";
 1000:  <a target="_top" href="$link" title="$title"><img src="$faqicon" border="0" alt="(FAQ: $topic)" /></a>
 1001: ENDTEMPLATE
 1002:     if ($text ne '') { $template.='</td></tr></table>' };
 1003:     return $template;
 1004: 
 1005: }
 1006: 
 1007: ###############################################################
 1008: ###############################################################
 1009: 
 1010: =pod
 1011: 
 1012: =item * change_content_javascript():
 1013: 
 1014: This and the next function allow you to create small sections of an
 1015: otherwise static HTML page that you can update on the fly with
 1016: Javascript, even in Netscape 4.
 1017: 
 1018: The Javascript fragment returned by this function (no E<lt>scriptE<gt> tag)
 1019: must be written to the HTML page once. It will prove the Javascript
 1020: function "change(name, content)". Calling the change function with the
 1021: name of the section 
 1022: you want to update, matching the name passed to C<changable_area>, and
 1023: the new content you want to put in there, will put the content into
 1024: that area.
 1025: 
 1026: B<Note>: Netscape 4 only reserves enough space for the changable area
 1027: to contain room for the original contents. You need to "make space"
 1028: for whatever changes you wish to make, and be B<sure> to check your
 1029: code in Netscape 4. This feature in Netscape 4 is B<not> powerful;
 1030: it's adequate for updating a one-line status display, but little more.
 1031: This script will set the space to 100% width, so you only need to
 1032: worry about height in Netscape 4.
 1033: 
 1034: Modern browsers are much less limiting, and if you can commit to the
 1035: user not using Netscape 4, this feature may be used freely with
 1036: pretty much any HTML.
 1037: 
 1038: =cut
 1039: 
 1040: sub change_content_javascript {
 1041:     # If we're on Netscape 4, we need to use Layer-based code
 1042:     if ($env{'browser.type'} eq 'netscape' &&
 1043: 	$env{'browser.version'} =~ /^4\./) {
 1044: 	return (<<NETSCAPE4);
 1045: 	function change(name, content) {
 1046: 	    doc = document.layers[name+"___escape"].layers[0].document;
 1047: 	    doc.open();
 1048: 	    doc.write(content);
 1049: 	    doc.close();
 1050: 	}
 1051: NETSCAPE4
 1052:     } else {
 1053: 	# Otherwise, we need to use semi-standards-compliant code
 1054: 	# (technically, "innerHTML" isn't standard but the equivalent
 1055: 	# is really scary, and every useful browser supports it
 1056: 	return (<<DOMBASED);
 1057: 	function change(name, content) {
 1058: 	    element = document.getElementById(name);
 1059: 	    element.innerHTML = content;
 1060: 	}
 1061: DOMBASED
 1062:     }
 1063: }
 1064: 
 1065: =pod
 1066: 
 1067: =item * changable_area($name, $origContent):
 1068: 
 1069: This provides a "changable area" that can be modified on the fly via
 1070: the Javascript code provided in C<change_content_javascript>. $name is
 1071: the name you will use to reference the area later; do not repeat the
 1072: same name on a given HTML page more then once. $origContent is what
 1073: the area will originally contain, which can be left blank.
 1074: 
 1075: =cut
 1076: 
 1077: sub changable_area {
 1078:     my ($name, $origContent) = @_;
 1079: 
 1080:     if ($env{'browser.type'} eq 'netscape' &&
 1081: 	$env{'browser.version'} =~ /^4\./) {
 1082: 	# If this is netscape 4, we need to use the Layer tag
 1083: 	return "<ilayer width='100%' id='${name}___escape' overflow='none'><layer width='100%' id='$name' overflow='none'>$origContent</layer></ilayer>";
 1084:     } else {
 1085: 	return "<span id='$name'>$origContent</span>";
 1086:     }
 1087: }
 1088: 
 1089: =pod
 1090: 
 1091: =back
 1092: 
 1093: =head1 Excel and CSV file utility routines
 1094: 
 1095: =over 4
 1096: 
 1097: =cut
 1098: 
 1099: ###############################################################
 1100: ###############################################################
 1101: 
 1102: =pod
 1103: 
 1104: =item * csv_translate($text) 
 1105: 
 1106: Translate $text to allow it to be output as a 'comma separated values' 
 1107: format.
 1108: 
 1109: =cut
 1110: 
 1111: ###############################################################
 1112: ###############################################################
 1113: sub csv_translate {
 1114:     my $text = shift;
 1115:     $text =~ s/\"/\"\"/g;
 1116:     $text =~ s/\n/ /g;
 1117:     return $text;
 1118: }
 1119: 
 1120: ###############################################################
 1121: ###############################################################
 1122: 
 1123: =pod
 1124: 
 1125: =item * define_excel_formats
 1126: 
 1127: Define some commonly used Excel cell formats.
 1128: 
 1129: Currently supported formats:
 1130: 
 1131: =over 4
 1132: 
 1133: =item header
 1134: 
 1135: =item bold
 1136: 
 1137: =item h1
 1138: 
 1139: =item h2
 1140: 
 1141: =item h3
 1142: 
 1143: =item h4
 1144: 
 1145: =item i
 1146: 
 1147: =item date
 1148: 
 1149: =back
 1150: 
 1151: Inputs: $workbook
 1152: 
 1153: Returns: $format, a hash reference.
 1154: 
 1155: =cut
 1156: 
 1157: ###############################################################
 1158: ###############################################################
 1159: sub define_excel_formats {
 1160:     my ($workbook) = @_;
 1161:     my $format;
 1162:     $format->{'header'} = $workbook->add_format(bold      => 1, 
 1163:                                                 bottom    => 1,
 1164:                                                 align     => 'center');
 1165:     $format->{'bold'} = $workbook->add_format(bold=>1);
 1166:     $format->{'h1'}   = $workbook->add_format(bold=>1, size=>18);
 1167:     $format->{'h2'}   = $workbook->add_format(bold=>1, size=>16);
 1168:     $format->{'h3'}   = $workbook->add_format(bold=>1, size=>14);
 1169:     $format->{'h4'}   = $workbook->add_format(bold=>1, size=>12);
 1170:     $format->{'i'}    = $workbook->add_format(italic=>1);
 1171:     $format->{'date'} = $workbook->add_format(num_format=>
 1172:                                             'mm/dd/yyyy hh:mm:ss');
 1173:     return $format;
 1174: }
 1175: 
 1176: ###############################################################
 1177: ###############################################################
 1178: 
 1179: =pod
 1180: 
 1181: =item * create_workbook
 1182: 
 1183: Create an Excel worksheet.  If it fails, output message on the
 1184: request object and return undefs.
 1185: 
 1186: Inputs: Apache request object
 1187: 
 1188: Returns (undef) on failure, 
 1189:     Excel worksheet object, scalar with filename, and formats 
 1190:     from &Apache::loncommon::define_excel_formats on success
 1191: 
 1192: =cut
 1193: 
 1194: ###############################################################
 1195: ###############################################################
 1196: sub create_workbook {
 1197:     my ($r) = @_;
 1198:         #
 1199:     # Create the excel spreadsheet
 1200:     my $filename = '/prtspool/'.
 1201:         $env{'user.name'}.'_'.$env{'user.domain'}.'_'.
 1202:         time.'_'.rand(1000000000).'.xls';
 1203:     my $workbook  = Spreadsheet::WriteExcel->new('/home/httpd'.$filename);
 1204:     if (! defined($workbook)) {
 1205:         $r->log_error("Error creating excel spreadsheet $filename: $!");
 1206:         $r->print('<p>'.&mt("Unable to create new Excel file.  ".
 1207:                             "This error has been logged.  ".
 1208:                             "Please alert your LON-CAPA administrator").
 1209:                   '</p>');
 1210:         return (undef);
 1211:     }
 1212:     #
 1213:     $workbook->set_tempdir('/home/httpd/perl/tmp');
 1214:     #
 1215:     my $format = &Apache::loncommon::define_excel_formats($workbook);
 1216:     return ($workbook,$filename,$format);
 1217: }
 1218: 
 1219: ###############################################################
 1220: ###############################################################
 1221: 
 1222: =pod
 1223: 
 1224: =item * create_text_file
 1225: 
 1226: Create a file to write to and eventually make available to the usre.
 1227: If file creation fails, outputs an error message on the request object and 
 1228: return undefs.
 1229: 
 1230: Inputs: Apache request object, and file suffix
 1231: 
 1232: Returns (undef) on failure, 
 1233:     Filehandle and filename on success.
 1234: 
 1235: =cut
 1236: 
 1237: ###############################################################
 1238: ###############################################################
 1239: sub create_text_file {
 1240:     my ($r,$suffix) = @_;
 1241:     if (! defined($suffix)) { $suffix = 'txt'; };
 1242:     my $fh;
 1243:     my $filename = '/prtspool/'.
 1244:         $env{'user.name'}.'_'.$env{'user.domain'}.'_'.
 1245:         time.'_'.rand(1000000000).'.'.$suffix;
 1246:     $fh = Apache::File->new('>/home/httpd'.$filename);
 1247:     if (! defined($fh)) {
 1248:         $r->log_error("Couldn't open $filename for output $!");
 1249:         $r->print("Problems occured in creating the output file.  ".
 1250:                   "This error has been logged.  ".
 1251:                   "Please alert your LON-CAPA administrator.");
 1252:     }
 1253:     return ($fh,$filename)
 1254: }
 1255: 
 1256: 
 1257: =pod 
 1258: 
 1259: =back
 1260: 
 1261: =cut
 1262: 
 1263: ###############################################################
 1264: ##        Home server <option> list generating code          ##
 1265: ###############################################################
 1266: 
 1267: =pod
 1268: 
 1269: =head1 Home Server option list generating code
 1270: 
 1271: =over 4
 1272: 
 1273: =item * get_domains()
 1274: 
 1275: Returns an array containing each of the domains listed in the hosts.tab
 1276: file.
 1277: 
 1278: =cut
 1279: 
 1280: #-------------------------------------------
 1281: sub get_domains {
 1282:     # The code below was stolen from "The Perl Cookbook", p 102, 1st ed.
 1283:     my @domains;
 1284:     my %seen;
 1285:     foreach my $dom (sort(values(%Apache::lonnet::hostdom))) {
 1286: 	push(@domains,$dom) unless $seen{$dom}++;
 1287:     }
 1288:     return @domains;
 1289: }
 1290: 
 1291: # ------------------------------------------
 1292: 
 1293: sub domain_select {
 1294:     my ($name,$value,$multiple)=@_;
 1295:     my %domains=map { 
 1296: 	$_ => $_.' '.$Apache::lonnet::domaindescription{$_} 
 1297:     } &get_domains;
 1298:     if ($multiple) {
 1299: 	$domains{''}=&mt('Any domain');
 1300: 	return &multiple_select_form($name,$value,4,\%domains);
 1301:     } else {
 1302: 	return &select_form($name,$value,%domains);
 1303:     }
 1304: }
 1305: 
 1306: #-------------------------------------------
 1307: 
 1308: =pod
 1309: 
 1310: =item * multiple_select_form($name,$value,$size,$hash,$order)
 1311: 
 1312: Returns a string containing a <select> element int multiple mode
 1313: 
 1314: 
 1315: Args:
 1316:   $name - name of the <select> element
 1317:   $value - sclara or array ref of values that should already be selected
 1318:   $size - number of rows long the select element is
 1319:   $hash - the elements should be 'option' => 'shown text'
 1320:           (shown text should already have been &mt())
 1321:   $order - (optional) array ref of the order to show the elments in
 1322: 
 1323: =cut
 1324: 
 1325: #-------------------------------------------
 1326: sub multiple_select_form {
 1327:     my ($name,$value,$size,$hash,$order)=@_;
 1328:     my %selected = map { $_ => 1 } ref($value)?@{$value}:($value);
 1329:     my $output='';
 1330:     if (! defined($size)) {
 1331:         $size = 4;
 1332:         if (scalar(keys(%$hash))<4) {
 1333:             $size = scalar(keys(%$hash));
 1334:         }
 1335:     }
 1336:     $output.="\n<select name='$name' size='$size' multiple='1'>";
 1337:     my @order = ref($order) ? @$order
 1338:                             : sort(keys(%$hash));
 1339:     foreach my $key (@order) {
 1340:         $output.='<option value="'.&HTML::Entities::encode($key,'"<>&').'" ';
 1341:         $output.='selected="selected" ' if ($selected{$key});
 1342:         $output.='>'.$hash->{$key}."</option>\n";
 1343:     }
 1344:     $output.="</select>\n";
 1345:     return $output;
 1346: }
 1347: 
 1348: #-------------------------------------------
 1349: 
 1350: =pod
 1351: 
 1352: =item * select_form($defdom,$name,%hash)
 1353: 
 1354: Returns a string containing a <select name='$name' size='1'> form to 
 1355: allow a user to select options from a hash option_name => displayed text.  
 1356: See lonrights.pm for an example invocation and use.
 1357: 
 1358: =cut
 1359: 
 1360: #-------------------------------------------
 1361: sub select_form {
 1362:     my ($def,$name,%hash) = @_;
 1363:     my $selectform = "<select name=\"$name\" size=\"1\">\n";
 1364:     my @keys;
 1365:     if (exists($hash{'select_form_order'})) {
 1366: 	@keys=@{$hash{'select_form_order'}};
 1367:     } else {
 1368: 	@keys=sort(keys(%hash));
 1369:     }
 1370:     foreach my $key (@keys) {
 1371:         $selectform.=
 1372: 	    '<option value="'.&HTML::Entities::encode($key,'"<>&').'" '.
 1373:             ($key eq $def ? 'selected="selected" ' : '').
 1374:                 ">".&mt($hash{$key})."</option>\n";
 1375:     }
 1376:     $selectform.="</select>";
 1377:     return $selectform;
 1378: }
 1379: 
 1380: sub gradeleveldescription {
 1381:     my $gradelevel=shift;
 1382:     my %gradelevels=(0 => 'Not specified',
 1383: 		     1 => 'Grade 1',
 1384: 		     2 => 'Grade 2',
 1385: 		     3 => 'Grade 3',
 1386: 		     4 => 'Grade 4',
 1387: 		     5 => 'Grade 5',
 1388: 		     6 => 'Grade 6',
 1389: 		     7 => 'Grade 7',
 1390: 		     8 => 'Grade 8',
 1391: 		     9 => 'Grade 9',
 1392: 		     10 => 'Grade 10',
 1393: 		     11 => 'Grade 11',
 1394: 		     12 => 'Grade 12',
 1395: 		     13 => 'Grade 13',
 1396: 		     14 => '100 Level',
 1397: 		     15 => '200 Level',
 1398: 		     16 => '300 Level',
 1399: 		     17 => '400 Level',
 1400: 		     18 => 'Graduate Level');
 1401:     return &mt($gradelevels{$gradelevel});
 1402: }
 1403: 
 1404: sub select_level_form {
 1405:     my ($deflevel,$name)=@_;
 1406:     unless ($deflevel) { $deflevel=0; }
 1407:     my $selectform = "<select name=\"$name\" size=\"1\">\n";
 1408:     for (my $i=0; $i<=18; $i++) {
 1409:         $selectform.="<option value=\"$i\" ".
 1410:             ($i==$deflevel ? 'selected="selected" ' : '').
 1411:                 ">".&gradeleveldescription($i)."</option>\n";
 1412:     }
 1413:     $selectform.="</select>";
 1414:     return $selectform;
 1415: }
 1416: 
 1417: #-------------------------------------------
 1418: 
 1419: =pod
 1420: 
 1421: =item * select_dom_form($defdom,$name,$includeempty)
 1422: 
 1423: Returns a string containing a <select name='$name' size='1'> form to 
 1424: allow a user to select the domain to preform an operation in.  
 1425: See loncreateuser.pm for an example invocation and use.
 1426: 
 1427: If the $includeempty flag is set, it also includes an empty choice ("no domain
 1428: selected");
 1429: 
 1430: =cut
 1431: 
 1432: #-------------------------------------------
 1433: sub select_dom_form {
 1434:     my ($defdom,$name,$includeempty) = @_;
 1435:     my @domains = get_domains();
 1436:     if ($includeempty) { @domains=('',@domains); }
 1437:     my $selectdomain = "<select name=\"$name\" size=\"1\">\n";
 1438:     foreach my $dom (@domains) {
 1439:         $selectdomain.="<option value=\"$dom\" ".
 1440:             ($dom eq $defdom ? 'selected="selected" ' : '').
 1441:                 ">$dom</option>\n";
 1442:     }
 1443:     $selectdomain.="</select>";
 1444:     return $selectdomain;
 1445: }
 1446: 
 1447: #-------------------------------------------
 1448: 
 1449: =pod
 1450: 
 1451: =item * get_library_servers($domain)
 1452: 
 1453: Returns a hash which contains keys like '103l3' and values like 
 1454: 'kirk.lite.msu.edu'.  All of the keys will be for machines in the
 1455: given $domain.
 1456: 
 1457: =cut
 1458: 
 1459: #-------------------------------------------
 1460: sub get_library_servers {
 1461:     my $domain = shift;
 1462:     my %library_servers;
 1463:     foreach my $hostid (keys(%Apache::lonnet::libserv)) {
 1464:         if ($Apache::lonnet::hostdom{$hostid} eq $domain) {
 1465:             $library_servers{$hostid} = $Apache::lonnet::hostname{$hostid};
 1466:         }
 1467:     }
 1468:     return %library_servers;
 1469: }
 1470: 
 1471: #-------------------------------------------
 1472: 
 1473: =pod
 1474: 
 1475: =item * home_server_option_list($domain)
 1476: 
 1477: returns a string which contains an <option> list to be used in a 
 1478: <select> form input.  See loncreateuser.pm for an example.
 1479: 
 1480: =cut
 1481: 
 1482: #-------------------------------------------
 1483: sub home_server_option_list {
 1484:     my $domain = shift;
 1485:     my %servers = &get_library_servers($domain);
 1486:     my $result = '';
 1487:     foreach my $hostid (sort(keys(%servers))) {
 1488:         $result.=
 1489:             '<option value="'.$hostid.'">'.
 1490: 	    $hostid.' '.$servers{$hostid}."</option>\n";
 1491:     }
 1492:     return $result;
 1493: }
 1494: 
 1495: =pod
 1496: 
 1497: =back
 1498: 
 1499: =cut
 1500: 
 1501: ###############################################################
 1502: ##                  Decoding User Agent                      ##
 1503: ###############################################################
 1504: 
 1505: =pod
 1506: 
 1507: =head1 Decoding the User Agent
 1508: 
 1509: =over 4
 1510: 
 1511: =item * &decode_user_agent()
 1512: 
 1513: Inputs: $r
 1514: 
 1515: Outputs:
 1516: 
 1517: =over 4
 1518: 
 1519: =item * $httpbrowser
 1520: 
 1521: =item * $clientbrowser
 1522: 
 1523: =item * $clientversion
 1524: 
 1525: =item * $clientmathml
 1526: 
 1527: =item * $clientunicode
 1528: 
 1529: =item * $clientos
 1530: 
 1531: =back
 1532: 
 1533: =back 
 1534: 
 1535: =cut
 1536: 
 1537: ###############################################################
 1538: ###############################################################
 1539: sub decode_user_agent {
 1540:     my ($r)=@_;
 1541:     my @browsertype=split(/\&/,$Apache::lonnet::perlvar{"lonBrowsDet"});
 1542:     my %mathcap=split(/\&/,$$Apache::lonnet::perlvar{"lonMathML"});
 1543:     my $httpbrowser=$ENV{"HTTP_USER_AGENT"};
 1544:     if (!$httpbrowser && $r) { $httpbrowser=$r->header_in('User-Agent'); }
 1545:     my $clientbrowser='unknown';
 1546:     my $clientversion='0';
 1547:     my $clientmathml='';
 1548:     my $clientunicode='0';
 1549:     for (my $i=0;$i<=$#browsertype;$i++) {
 1550:         my ($bname,$match,$notmatch,$vreg,$minv,$univ)=split(/\:/,$browsertype[$i]);
 1551: 	if (($httpbrowser=~/$match/i)  && ($httpbrowser!~/$notmatch/i)) {
 1552: 	    $clientbrowser=$bname;
 1553:             $httpbrowser=~/$vreg/i;
 1554: 	    $clientversion=$1;
 1555:             $clientmathml=($clientversion>=$minv);
 1556:             $clientunicode=($clientversion>=$univ);
 1557: 	}
 1558:     }
 1559:     my $clientos='unknown';
 1560:     if (($httpbrowser=~/linux/i) ||
 1561:         ($httpbrowser=~/unix/i) ||
 1562:         ($httpbrowser=~/ux/i) ||
 1563:         ($httpbrowser=~/solaris/i)) { $clientos='unix'; }
 1564:     if (($httpbrowser=~/vax/i) ||
 1565:         ($httpbrowser=~/vms/i)) { $clientos='vms'; }
 1566:     if ($httpbrowser=~/next/i) { $clientos='next'; }
 1567:     if (($httpbrowser=~/mac/i) ||
 1568:         ($httpbrowser=~/powerpc/i)) { $clientos='mac'; }
 1569:     if ($httpbrowser=~/win/i) { $clientos='win'; }
 1570:     if ($httpbrowser=~/embed/i) { $clientos='pda'; }
 1571:     return ($httpbrowser,$clientbrowser,$clientversion,$clientmathml,
 1572:             $clientunicode,$clientos,);
 1573: }
 1574: 
 1575: ###############################################################
 1576: ##    Authentication changing form generation subroutines    ##
 1577: ###############################################################
 1578: ##
 1579: ## All of the authform_xxxxxxx subroutines take their inputs in a
 1580: ## hash, and have reasonable default values.
 1581: ##
 1582: ##    formname = the name given in the <form> tag.
 1583: #-------------------------------------------
 1584: 
 1585: =pod
 1586: 
 1587: =head1 Authentication Routines
 1588: 
 1589: =over 4
 1590: 
 1591: =item * authform_xxxxxx
 1592: 
 1593: The authform_xxxxxx subroutines provide javascript and html forms which 
 1594: handle some of the conveniences required for authentication forms.  
 1595: This is not an optimal method, but it works.  
 1596: 
 1597: See loncreateuser.pm for invocation and use examples.
 1598: 
 1599: =over 4
 1600: 
 1601: =item * authform_header
 1602: 
 1603: =item * authform_authorwarning
 1604: 
 1605: =item * authform_nochange
 1606: 
 1607: =item * authform_kerberos
 1608: 
 1609: =item * authform_internal
 1610: 
 1611: =item * authform_filesystem
 1612: 
 1613: =back
 1614: 
 1615: =back 
 1616: 
 1617: =cut
 1618: 
 1619: #-------------------------------------------
 1620: sub authform_header{  
 1621:     my %in = (
 1622:         formname => 'cu',
 1623:         kerb_def_dom => '',
 1624:         @_,
 1625:     );
 1626:     $in{'formname'} = 'document.' . $in{'formname'};
 1627:     my $result='';
 1628: 
 1629: #---------------------------------------------- Code for upper case translation
 1630:     my $Javascript_toUpperCase;
 1631:     unless ($in{kerb_def_dom}) {
 1632:         $Javascript_toUpperCase =<<"END";
 1633:         switch (choice) {
 1634:            case 'krb': currentform.elements[choicearg].value =
 1635:                currentform.elements[choicearg].value.toUpperCase();
 1636:                break;
 1637:            default:
 1638:         }
 1639: END
 1640:     } else {
 1641:         $Javascript_toUpperCase = "";
 1642:     }
 1643: 
 1644:     my $radioval = "'nochange'";
 1645:     if (exists($in{'curr_authtype'}) &&
 1646:         defined($in{'curr_authtype'}) &&
 1647:         $in{'curr_authtype'} ne '') {
 1648:         $radioval = "'$in{'curr_authtype'}arg'";
 1649:     }
 1650:     my $argfield = 'null';
 1651:     if ( grep/^mode$/,(keys %in) ) {
 1652:         if ($in{'mode'} eq 'modifycourse')  {
 1653:             if ( grep/^curr_authtype$/,(keys %in) ) {
 1654:                 $radioval = "'$in{'curr_authtype'}'";
 1655:             }
 1656:             if ( grep/^curr_autharg$/,(keys %in) ) {
 1657:                 unless ($in{'curr_autharg'} eq '') {
 1658:                     $argfield = "'$in{'curr_autharg'}'";
 1659:                 }
 1660:             }
 1661:         }
 1662:     }
 1663: 
 1664:     $result.=<<"END";
 1665: var current = new Object();
 1666: current.radiovalue = $radioval;
 1667: current.argfield = $argfield;
 1668: 
 1669: function changed_radio(choice,currentform) {
 1670:     var choicearg = choice + 'arg';
 1671:     // If a radio button in changed, we need to change the argfield
 1672:     if (current.radiovalue != choice) {
 1673:         current.radiovalue = choice;
 1674:         if (current.argfield != null) {
 1675:             currentform.elements[current.argfield].value = '';
 1676:         }
 1677:         if (choice == 'nochange') {
 1678:             current.argfield = null;
 1679:         } else {
 1680:             current.argfield = choicearg;
 1681:             switch(choice) {
 1682:                 case 'krb': 
 1683:                     currentform.elements[current.argfield].value = 
 1684:                         "$in{'kerb_def_dom'}";
 1685:                 break;
 1686:               default:
 1687:                 break;
 1688:             }
 1689:         }
 1690:     }
 1691:     return;
 1692: }
 1693: 
 1694: function changed_text(choice,currentform) {
 1695:     var choicearg = choice + 'arg';
 1696:     if (currentform.elements[choicearg].value !='') {
 1697:         $Javascript_toUpperCase
 1698:         // clear old field
 1699:         if ((current.argfield != choicearg) && (current.argfield != null)) {
 1700:             currentform.elements[current.argfield].value = '';
 1701:         }
 1702:         current.argfield = choicearg;
 1703:     }
 1704:     set_auth_radio_buttons(choice,currentform);
 1705:     return;
 1706: }
 1707: 
 1708: function set_auth_radio_buttons(newvalue,currentform) {
 1709:     var i=0;
 1710:     while (i < currentform.login.length) {
 1711:         if (currentform.login[i].value == newvalue) { break; }
 1712:         i++;
 1713:     }
 1714:     if (i == currentform.login.length) {
 1715:         return;
 1716:     }
 1717:     current.radiovalue = newvalue;
 1718:     currentform.login[i].checked = true;
 1719:     return;
 1720: }
 1721: END
 1722:     return $result;
 1723: }
 1724: 
 1725: sub authform_authorwarning{
 1726:     my $result='';
 1727:     $result='<i>'.
 1728:         &mt('As a general rule, only authors or co-authors should be '.
 1729:             'filesystem authenticated '.
 1730:             '(which allows access to the server filesystem).')."</i>\n";
 1731:     return $result;
 1732: }
 1733: 
 1734: sub authform_nochange{  
 1735:     my %in = (
 1736:               formname => 'document.cu',
 1737:               kerb_def_dom => 'MSU.EDU',
 1738:               @_,
 1739:           );
 1740:     my $result = '<label>'.&mt('[_1] Do not change login data',
 1741:                      '<input type="radio" name="login" value="nochange" '.
 1742:                      'checked="checked" onclick="'.
 1743:             "javascript:changed_radio('nochange',$in{'formname'});".'" />').
 1744: 	    '</label>';
 1745:     return $result;
 1746: }
 1747: 
 1748: sub authform_kerberos{  
 1749:     my %in = (
 1750:               formname => 'document.cu',
 1751:               kerb_def_dom => 'MSU.EDU',
 1752:               kerb_def_auth => 'krb4',
 1753:               @_,
 1754:               );
 1755:     my ($check4,$check5,$krbarg);
 1756:     if ($in{'kerb_def_auth'} eq 'krb5') {
 1757:        $check5 = " checked=\"on\"";
 1758:     } else {
 1759:        $check4 = " checked=\"on\"";
 1760:     }
 1761:     $krbarg = $in{'kerb_def_dom'};
 1762: 
 1763:     my $krbcheck = "";
 1764:     if ( grep/^curr_authtype$/,(keys %in) ) {
 1765:         if ($in{'curr_authtype'} =~ m/^krb/) {
 1766:             $krbcheck = " checked=\"on\"";
 1767:             if ( grep/^curr_autharg$/,(keys %in) ) {
 1768:                 $krbarg = $in{'curr_autharg'};
 1769:             }
 1770:         }
 1771:     }
 1772: 
 1773:     my $jscall = "javascript:changed_radio('krb',$in{'formname'});";
 1774:     my $result .= &mt
 1775:         ('[_1] Kerberos authenticated with domain [_2] '.
 1776:          '[_3] Version 4 [_4] Version 5 [_5]',
 1777:          '<label><input type="radio" name="login" value="krb" '.
 1778:              'onclick="'.$jscall.'" onchange="'.$jscall.'"'.$krbcheck.' />',
 1779:          '</label><input type="text" size="10" name="krbarg" '.
 1780:              'value="'.$krbarg.'" '.
 1781:              'onchange="'.$jscall.'" />',
 1782:          '<label><input type="radio" name="krbver" value="4" '.$check4.' />',
 1783:          '</label><label><input type="radio" name="krbver" value="5" '.$check5.' />',
 1784: 	 '</label>');
 1785:     return $result;
 1786: }
 1787: 
 1788: sub authform_internal{  
 1789:     my %args = (
 1790:                 formname => 'document.cu',
 1791:                 kerb_def_dom => 'MSU.EDU',
 1792:                 @_,
 1793:                 );
 1794: 
 1795:     my $intcheck = "";
 1796:     my $intarg = 'value=""';
 1797:     if ( grep/^curr_authtype$/,(keys %args) ) {
 1798:         if ($args{'curr_authtype'} eq 'int') {
 1799:             $intcheck = " checked=\"on\"";
 1800:             if ( grep/^curr_autharg$/,(keys %args) ) {
 1801:                 $intarg = "value=\"$args{'curr_autharg'}\"";
 1802:             }
 1803:         }
 1804:     }
 1805: 
 1806:     my $jscall = "javascript:changed_radio('int',$args{'formname'});";
 1807:     my $result.=&mt
 1808:         ('[_1] Internally authenticated (with initial password [_2])',
 1809:          '<label><input type="radio" name="login" value="int" '.$intcheck.
 1810:              ' onchange="'.$jscall.'" onclick="'.$jscall.'" />',
 1811:          '</label><input type="text" size="10" name="intarg" '.$intarg.
 1812:              ' onchange="'.$jscall.'" />');
 1813:     return $result;
 1814: }
 1815: 
 1816: sub authform_local{  
 1817:     my %in = (
 1818:               formname => 'document.cu',
 1819:               kerb_def_dom => 'MSU.EDU',
 1820:               @_,
 1821:               );
 1822: 
 1823:     my $loccheck = "";
 1824:     my $locarg = 'value=""';
 1825:     if ( grep/^curr_authtype$/,(keys %in) ) {
 1826:         if ($in{'curr_authtype'} eq 'loc') {
 1827:             $loccheck = " checked=\"on\"";
 1828:             if ( grep/^curr_autharg$/,(keys %in) ) {
 1829:                 $locarg = "value=\"$in{'curr_autharg'}\"";
 1830:             }
 1831:         }
 1832:     }
 1833: 
 1834:     my $jscall = "javascript:changed_radio('loc',$in{'formname'});";
 1835:     my $result.=&mt('[_1] Local Authentication with argument [_2]',
 1836:                     '<label><input type="radio" name="login" value="loc" '.$loccheck.
 1837:                         ' onchange="'.$jscall.'" onclick="'.$jscall.'" />',
 1838:                     '</label><input type="text" size="10" name="locarg" '.$locarg.
 1839:                         ' onchange="'.$jscall.'" />');
 1840:     return $result;
 1841: }
 1842: 
 1843: sub authform_filesystem{  
 1844:     my %in = (
 1845:               formname => 'document.cu',
 1846:               kerb_def_dom => 'MSU.EDU',
 1847:               @_,
 1848:               );
 1849:     my $jscall = "javascript:changed_radio('fsys',$in{'formname'});";
 1850:     my $result.= &mt
 1851:         ('[_1] Filesystem Authenticated (with initial password [_2])',
 1852:          '<label><input type="radio" name="login" value="fsys" '.
 1853:          'onchange="'.$jscall.'" onclick="'.$jscall.'" />',
 1854:          '</label><input type="text" size="10" name="fsysarg" value="" '.
 1855:                   'onchange="'.$jscall.'" />');
 1856:     return $result;
 1857: }
 1858: 
 1859: ###############################################################
 1860: ##    Get Authentication Defaults for Domain                 ##
 1861: ###############################################################
 1862: 
 1863: =pod
 1864: 
 1865: =head1 Domains and Authentication
 1866: 
 1867: Returns default authentication type and an associated argument as
 1868: listed in file 'domain.tab'.
 1869: 
 1870: =over 4
 1871: 
 1872: =item * get_auth_defaults
 1873: 
 1874: get_auth_defaults($target_domain) returns the default authentication
 1875: type and an associated argument (initial password or a kerberos domain).
 1876: These values are stored in lonTabs/domain.tab
 1877: 
 1878: ($def_auth, $def_arg) = &get_auth_defaults($target_domain);
 1879: 
 1880: If target_domain is not found in domain.tab, returns nothing ('').
 1881: 
 1882: =cut
 1883: 
 1884: #-------------------------------------------
 1885: sub get_auth_defaults {
 1886:     my $domain=shift;
 1887:     return ($Apache::lonnet::domain_auth_def{$domain},$Apache::lonnet::domain_auth_arg_def{$domain});
 1888: }
 1889: ###############################################################
 1890: ##   End Get Authentication Defaults for Domain              ##
 1891: ###############################################################
 1892: 
 1893: ###############################################################
 1894: ##    Get Kerberos Defaults for Domain                 ##
 1895: ###############################################################
 1896: ##
 1897: ## Returns default kerberos version and an associated argument
 1898: ## as listed in file domain.tab. If not listed, provides
 1899: ## appropriate default domain and kerberos version.
 1900: ##
 1901: #-------------------------------------------
 1902: 
 1903: =pod
 1904: 
 1905: =item * get_kerberos_defaults
 1906: 
 1907: get_kerberos_defaults($target_domain) returns the default kerberos
 1908: version and domain. If not found in domain.tabs, it defaults to
 1909: version 4 and the domain of the server.
 1910: 
 1911: ($def_version, $def_krb_domain) = &get_kerberos_defaults($target_domain);
 1912: 
 1913: =cut
 1914: 
 1915: #-------------------------------------------
 1916: sub get_kerberos_defaults {
 1917:     my $domain=shift;
 1918:     my ($krbdef,$krbdefdom) =
 1919:         &Apache::loncommon::get_auth_defaults($domain);
 1920:     unless ($krbdef =~/^krb/ && $krbdefdom) {
 1921:         $ENV{'SERVER_NAME'}=~/(\w+\.\w+)$/;
 1922:         my $krbdefdom=$1;
 1923:         $krbdefdom=~tr/a-z/A-Z/;
 1924:         $krbdef = "krb4";
 1925:     }
 1926:     return ($krbdef,$krbdefdom);
 1927: }
 1928: 
 1929: =pod
 1930: 
 1931: =back
 1932: 
 1933: =cut
 1934: 
 1935: ###############################################################
 1936: ##                Thesaurus Functions                        ##
 1937: ###############################################################
 1938: 
 1939: =pod
 1940: 
 1941: =head1 Thesaurus Functions
 1942: 
 1943: =over 4
 1944: 
 1945: =item * initialize_keywords
 1946: 
 1947: Initializes the package variable %Keywords if it is empty.  Uses the
 1948: package variable $thesaurus_db_file.
 1949: 
 1950: =cut
 1951: 
 1952: ###################################################
 1953: 
 1954: sub initialize_keywords {
 1955:     return 1 if (scalar keys(%Keywords));
 1956:     # If we are here, %Keywords is empty, so fill it up
 1957:     #   Make sure the file we need exists...
 1958:     if (! -e $thesaurus_db_file) {
 1959:         &Apache::lonnet::logthis("Attempt to access $thesaurus_db_file".
 1960:                                  " failed because it does not exist");
 1961:         return 0;
 1962:     }
 1963:     #   Set up the hash as a database
 1964:     my %thesaurus_db;
 1965:     if (! tie(%thesaurus_db,'GDBM_File',
 1966:               $thesaurus_db_file,&GDBM_READER(),0640)){
 1967:         &Apache::lonnet::logthis("Could not tie \%thesaurus_db to ".
 1968:                                  $thesaurus_db_file);
 1969:         return 0;
 1970:     } 
 1971:     #  Get the average number of appearances of a word.
 1972:     my $avecount = $thesaurus_db{'average.count'};
 1973:     #  Put keywords (those that appear > average) into %Keywords
 1974:     while (my ($word,$data)=each (%thesaurus_db)) {
 1975:         my ($count,undef) = split /:/,$data;
 1976:         $Keywords{$word}++ if ($count > $avecount);
 1977:     }
 1978:     untie %thesaurus_db;
 1979:     # Remove special values from %Keywords.
 1980:     foreach my $value ('total.count','average.count') {
 1981:         delete($Keywords{$value}) if (exists($Keywords{$value}));
 1982:     }
 1983:     return 1;
 1984: }
 1985: 
 1986: ###################################################
 1987: 
 1988: =pod
 1989: 
 1990: =item * keyword($word)
 1991: 
 1992: Returns true if $word is a keyword.  A keyword is a word that appears more 
 1993: than the average number of times in the thesaurus database.  Calls 
 1994: &initialize_keywords
 1995: 
 1996: =cut
 1997: 
 1998: ###################################################
 1999: 
 2000: sub keyword {
 2001:     return if (!&initialize_keywords());
 2002:     my $word=lc(shift());
 2003:     $word=~s/\W//g;
 2004:     return exists($Keywords{$word});
 2005: }
 2006: 
 2007: ###############################################################
 2008: 
 2009: =pod 
 2010: 
 2011: =item * get_related_words
 2012: 
 2013: Look up a word in the thesaurus.  Takes a scalar argument and returns
 2014: an array of words.  If the keyword is not in the thesaurus, an empty array
 2015: will be returned.  The order of the words returned is determined by the
 2016: database which holds them.
 2017: 
 2018: Uses global $thesaurus_db_file.
 2019: 
 2020: =cut
 2021: 
 2022: ###############################################################
 2023: sub get_related_words {
 2024:     my $keyword = shift;
 2025:     my %thesaurus_db;
 2026:     if (! -e $thesaurus_db_file) {
 2027:         &Apache::lonnet::logthis("Attempt to access $thesaurus_db_file ".
 2028:                                  "failed because the file does not exist");
 2029:         return ();
 2030:     }
 2031:     if (! tie(%thesaurus_db,'GDBM_File',
 2032:               $thesaurus_db_file,&GDBM_READER(),0640)){
 2033:         return ();
 2034:     } 
 2035:     my @Words=();
 2036:     my $count=0;
 2037:     if (exists($thesaurus_db{$keyword})) {
 2038: 	# The first element is the number of times
 2039: 	# the word appears.  We do not need it now.
 2040: 	my (undef,@RelatedWords) = (split(/:/,$thesaurus_db{$keyword}));
 2041: 	my (undef,$mostfrequentcount)=split(/\,/,$RelatedWords[0]);
 2042: 	my $threshold=$mostfrequentcount/10;
 2043:         foreach my $possibleword (@RelatedWords) {
 2044:             my ($word,$wordcount)=split(/\,/,$possibleword);
 2045:             if ($wordcount>$threshold) {
 2046: 		push(@Words,$word);
 2047:                 $count++;
 2048:                 if ($count>10) { last; }
 2049: 	    }
 2050:         }
 2051:     }
 2052:     untie %thesaurus_db;
 2053:     return @Words;
 2054: }
 2055: 
 2056: =pod
 2057: 
 2058: =back
 2059: 
 2060: =cut
 2061: 
 2062: # -------------------------------------------------------------- Plaintext name
 2063: =pod
 2064: 
 2065: =head1 User Name Functions
 2066: 
 2067: =over 4
 2068: 
 2069: =item * plainname($uname,$udom,$first)
 2070: 
 2071: Takes a users logon name and returns it as a string in
 2072: "first middle last generation" form 
 2073: if $first is set to 'lastname' then it returns it as
 2074: 'lastname generation, firstname middlename' if their is a lastname
 2075: 
 2076: =cut
 2077: 
 2078: 
 2079: ###############################################################
 2080: sub plainname {
 2081:     my ($uname,$udom,$first)=@_;
 2082:     my %names=&getnames($uname,$udom);
 2083:     my $name=&Apache::lonnet::format_name($names{'firstname'},
 2084: 					  $names{'middlename'},
 2085: 					  $names{'lastname'},
 2086: 					  $names{'generation'},$first);
 2087:     $name=~s/^\s+//;
 2088:     $name=~s/\s+$//;
 2089:     $name=~s/\s+/ /g;
 2090:     if ($name !~ /\S/) { $name=$uname.':'.$udom; }
 2091:     return $name;
 2092: }
 2093: 
 2094: # -------------------------------------------------------------------- Nickname
 2095: =pod
 2096: 
 2097: =item * nickname($uname,$udom)
 2098: 
 2099: Gets a users name and returns it as a string as
 2100: 
 2101: "&quot;nickname&quot;"
 2102: 
 2103: if the user has a nickname or
 2104: 
 2105: "first middle last generation"
 2106: 
 2107: if the user does not
 2108: 
 2109: =cut
 2110: 
 2111: sub nickname {
 2112:     my ($uname,$udom)=@_;
 2113:     my %names=&getnames($uname,$udom);
 2114:     my $name=$names{'nickname'};
 2115:     if ($name) {
 2116:        $name='&quot;'.$name.'&quot;'; 
 2117:     } else {
 2118:        $name=$names{'firstname'}.' '.$names{'middlename'}.' '.
 2119: 	     $names{'lastname'}.' '.$names{'generation'};
 2120:        $name=~s/\s+$//;
 2121:        $name=~s/\s+/ /g;
 2122:     }
 2123:     return $name;
 2124: }
 2125: 
 2126: sub getnames {
 2127:     my ($uname,$udom)=@_;
 2128:     if ($udom eq 'public' && $uname eq 'public') {
 2129: 	return ('lastname' => &mt('Public'));
 2130:     }
 2131:     my $id=$uname.':'.$udom;
 2132:     my ($names,$cached)=&Apache::lonnet::is_cached_new('namescache',$id);
 2133:     if ($cached) {
 2134: 	return %{$names};
 2135:     } else {
 2136: 	my %loadnames=&Apache::lonnet::get('environment',
 2137:                     ['firstname','middlename','lastname','generation','nickname'],
 2138: 					 $udom,$uname);
 2139: 	&Apache::lonnet::do_cache_new('namescache',$id,\%loadnames);
 2140: 	return %loadnames;
 2141:     }
 2142: }
 2143: 
 2144: sub getemails {
 2145:     my ($uname,$udom)=@_;
 2146:     if ($udom eq 'public' && $uname eq 'public') {
 2147: 	return;
 2148:     }
 2149:     if (!$udom) { $udom=$env{'user.domain'}; }
 2150:     if (!$uname) { $uname=$env{'user.name'}; }
 2151:     my $id=$uname.':'.$udom;
 2152:     my ($names,$cached)=&Apache::lonnet::is_cached_new('emailscache',$id);
 2153:     if ($cached) {
 2154: 	return %{$names};
 2155:     } else {
 2156: 	my %loadnames=&Apache::lonnet::get('environment',
 2157:                     			   ['notification','critnotification',
 2158: 					    'permanentemail'],
 2159: 					   $udom,$uname);
 2160: 	&Apache::lonnet::do_cache_new('emailscache',$id,\%loadnames);
 2161: 	return %loadnames;
 2162:     }
 2163: }
 2164: 
 2165: # ------------------------------------------------------------------ Screenname
 2166: 
 2167: =pod
 2168: 
 2169: =item * screenname($uname,$udom)
 2170: 
 2171: Gets a users screenname and returns it as a string
 2172: 
 2173: =cut
 2174: 
 2175: sub screenname {
 2176:     my ($uname,$udom)=@_;
 2177:     if ($uname eq $env{'user.name'} &&
 2178: 	$udom eq $env{'user.domain'}) {return $env{'environment.screenname'};}
 2179:     my %names=&Apache::lonnet::get('environment',['screenname'],$udom,$uname);
 2180:     return $names{'screenname'};
 2181: }
 2182: 
 2183: 
 2184: # ------------------------------------------------------------- Message Wrapper
 2185: 
 2186: sub messagewrapper {
 2187:     my ($link,$username,$domain,$subject,$text)=@_;
 2188:     return 
 2189:         '<a href="/adm/email?compose=individual&amp;'.
 2190:         'recname='.$username.'&amp;recdom='.$domain.
 2191: 	'&amp;subject='.&escape($subject).'&amp;text='.&escape($text).'" '.
 2192:         'title="'.&mt('Send message').'">'.$link.'</a>';
 2193: }
 2194: # --------------------------------------------------------------- Notes Wrapper
 2195: 
 2196: sub noteswrapper {
 2197:     my ($link,$un,$do)=@_;
 2198:     return 
 2199: "<a href='/adm/email?recordftf=retrieve&recname=$un&recdom=$do'>$link</a>";
 2200: }
 2201: # ------------------------------------------------------------- Aboutme Wrapper
 2202: 
 2203: sub aboutmewrapper {
 2204:     my ($link,$username,$domain,$target)=@_;
 2205:     if (!defined($username)  && !defined($domain)) {
 2206:         return;
 2207:     }
 2208:     return '<a href="/adm/'.$domain.'/'.$username.'/aboutme"'.
 2209: 	($target?' target="$target"':'').' title="'.&mt("View this user's personal page").'">'.$link.'</a>';
 2210: }
 2211: 
 2212: # ------------------------------------------------------------ Syllabus Wrapper
 2213: 
 2214: 
 2215: sub syllabuswrapper {
 2216:     my ($linktext,$coursedir,$domain,$fontcolor)=@_;
 2217:     if ($fontcolor) { 
 2218:         $linktext='<font color="'.$fontcolor.'">'.$linktext.'</font>'; 
 2219:     }
 2220:     return qq{<a href="/public/$domain/$coursedir/syllabus">$linktext</a>};
 2221: }
 2222: 
 2223: sub track_student_link {
 2224:     my ($linktext,$sname,$sdom,$target,$start) = @_;
 2225:     my $link ="/adm/trackstudent?";
 2226:     my $title = 'View recent activity';
 2227:     if (defined($sname) && $sname !~ /^\s*$/ &&
 2228:         defined($sdom)  && $sdom  !~ /^\s*$/) {
 2229:         $link .= "selected_student=$sname:$sdom";
 2230:         $title .= ' of this student';
 2231:     } 
 2232:     if (defined($target) && $target !~ /^\s*$/) {
 2233:         $target = qq{target="$target"};
 2234:     } else {
 2235:         $target = '';
 2236:     }
 2237:     if ($start) { $link.='&amp;start='.$start; }
 2238:     
 2239:     return qq{<a href="$link" title="$title" $target>$linktext</a>}.
 2240: 	&help_open_topic('View_recent_activity');
 2241: }
 2242: 
 2243: =pod
 2244: 
 2245: =back
 2246: 
 2247: =head1 Access .tab File Data
 2248: 
 2249: =over 4
 2250: 
 2251: =item * languageids() 
 2252: 
 2253: returns list of all language ids
 2254: 
 2255: =cut
 2256: 
 2257: sub languageids {
 2258:     return sort(keys(%language));
 2259: }
 2260: 
 2261: =pod
 2262: 
 2263: =item * languagedescription() 
 2264: 
 2265: returns description of a specified language id
 2266: 
 2267: =cut
 2268: 
 2269: sub languagedescription {
 2270:     my $code=shift;
 2271:     return  ($supported_language{$code}?'* ':'').
 2272:             $language{$code}.
 2273: 	    ($supported_language{$code}?' ('.&mt('interface available').')':'');
 2274: }
 2275: 
 2276: sub plainlanguagedescription {
 2277:     my $code=shift;
 2278:     return $language{$code};
 2279: }
 2280: 
 2281: sub supportedlanguagecode {
 2282:     my $code=shift;
 2283:     return $supported_language{$code};
 2284: }
 2285: 
 2286: =pod
 2287: 
 2288: =item * copyrightids() 
 2289: 
 2290: returns list of all copyrights
 2291: 
 2292: =cut
 2293: 
 2294: sub copyrightids {
 2295:     return sort(keys(%cprtag));
 2296: }
 2297: 
 2298: =pod
 2299: 
 2300: =item * copyrightdescription() 
 2301: 
 2302: returns description of a specified copyright id
 2303: 
 2304: =cut
 2305: 
 2306: sub copyrightdescription {
 2307:     return &mt($cprtag{shift(@_)});
 2308: }
 2309: 
 2310: =pod
 2311: 
 2312: =item * source_copyrightids() 
 2313: 
 2314: returns list of all source copyrights
 2315: 
 2316: =cut
 2317: 
 2318: sub source_copyrightids {
 2319:     return sort(keys(%scprtag));
 2320: }
 2321: 
 2322: =pod
 2323: 
 2324: =item * source_copyrightdescription() 
 2325: 
 2326: returns description of a specified source copyright id
 2327: 
 2328: =cut
 2329: 
 2330: sub source_copyrightdescription {
 2331:     return &mt($scprtag{shift(@_)});
 2332: }
 2333: 
 2334: =pod
 2335: 
 2336: =item * filecategories() 
 2337: 
 2338: returns list of all file categories
 2339: 
 2340: =cut
 2341: 
 2342: sub filecategories {
 2343:     return sort(keys(%category_extensions));
 2344: }
 2345: 
 2346: =pod
 2347: 
 2348: =item * filecategorytypes() 
 2349: 
 2350: returns list of file types belonging to a given file
 2351: category
 2352: 
 2353: =cut
 2354: 
 2355: sub filecategorytypes {
 2356:     my ($cat) = @_;
 2357:     return @{$category_extensions{lc($cat)}};
 2358: }
 2359: 
 2360: =pod
 2361: 
 2362: =item * fileembstyle() 
 2363: 
 2364: returns embedding style for a specified file type
 2365: 
 2366: =cut
 2367: 
 2368: sub fileembstyle {
 2369:     return $fe{lc(shift(@_))};
 2370: }
 2371: 
 2372: sub filemimetype {
 2373:     return $fm{lc(shift(@_))};
 2374: }
 2375: 
 2376: 
 2377: sub filecategoryselect {
 2378:     my ($name,$value)=@_;
 2379:     return &select_form($value,$name,
 2380: 			'' => &mt('Any category'),
 2381: 			map { $_,$_ } sort(keys(%category_extensions)));
 2382: }
 2383: 
 2384: =pod
 2385: 
 2386: =item * filedescription() 
 2387: 
 2388: returns description for a specified file type
 2389: 
 2390: =cut
 2391: 
 2392: sub filedescription {
 2393:     my $file_description = $fd{lc(shift())};
 2394:     $file_description =~ s:([\[\]]):~$1:g;
 2395:     return &mt($file_description);
 2396: }
 2397: 
 2398: =pod
 2399: 
 2400: =item * filedescriptionex() 
 2401: 
 2402: returns description for a specified file type with
 2403: extra formatting
 2404: 
 2405: =cut
 2406: 
 2407: sub filedescriptionex {
 2408:     my $ex=shift;
 2409:     my $file_description = $fd{lc($ex)};
 2410:     $file_description =~ s:([\[\]]):~$1:g;
 2411:     return '.'.$ex.' '.&mt($file_description);
 2412: }
 2413: 
 2414: # End of .tab access
 2415: =pod
 2416: 
 2417: =back
 2418: 
 2419: =cut
 2420: 
 2421: # ------------------------------------------------------------------ File Types
 2422: sub fileextensions {
 2423:     return sort(keys(%fe));
 2424: }
 2425: 
 2426: # ----------------------------------------------------------- Display Languages
 2427: # returns a hash with all desired display languages
 2428: #
 2429: 
 2430: sub display_languages {
 2431:     my %languages=();
 2432:     foreach my $lang (&preferred_languages()) {
 2433: 	$languages{$lang}=1;
 2434:     }
 2435:     &get_unprocessed_cgi($ENV{'QUERY_STRING'},['displaylanguage']);
 2436:     if ($env{'form.displaylanguage'}) {
 2437: 	foreach my $lang (split(/\s*(\,|\;|\:)\s*/,$env{'form.displaylanguage'})) {
 2438: 	    $languages{$lang}=1;
 2439:         }
 2440:     }
 2441:     return %languages;
 2442: }
 2443: 
 2444: sub preferred_languages {
 2445:     my @languages=();
 2446:     if ($env{'course.'.$env{'request.course.id'}.'.languages'}) {
 2447: 	@languages=(@languages,split(/\s*(\,|\;|\:)\s*/,
 2448: 	         $env{'course.'.$env{'request.course.id'}.'.languages'}));
 2449:     }
 2450:     if ($env{'environment.languages'}) {
 2451: 	@languages=(@languages,
 2452: 		    split(/\s*(\,|\;|\:)\s*/,$env{'environment.languages'}));
 2453:     }
 2454:     my $browser=(split(/\;/,$ENV{'HTTP_ACCEPT_LANGUAGE'}))[0];
 2455:     if ($browser) {
 2456: 	@languages=(@languages,split(/\s*(\,|\;|\:)\s*/,$browser));
 2457:     }
 2458:     if ($Apache::lonnet::domain_lang_def{$env{'user.domain'}}) {
 2459: 	@languages=(@languages,
 2460: 		$Apache::lonnet::domain_lang_def{$env{'user.domain'}});
 2461:     }
 2462:     if ($Apache::lonnet::domain_lang_def{$env{'request.role.domain'}}) {
 2463: 	@languages=(@languages,
 2464: 		$Apache::lonnet::domain_lang_def{$env{'request.role.domain'}});
 2465:     }
 2466:     if ($Apache::lonnet::domain_lang_def{
 2467: 	                          $Apache::lonnet::perlvar{'lonDefDomain'}}) {
 2468: 	@languages=(@languages,
 2469: 		$Apache::lonnet::domain_lang_def{
 2470:                                   $Apache::lonnet::perlvar{'lonDefDomain'}});
 2471:     }
 2472: # turn "en-ca" into "en-ca,en"
 2473:     my @genlanguages;
 2474:     foreach my $lang (@languages) {
 2475: 	unless ($lang=~/\w/) { next; }
 2476: 	push (@genlanguages,$lang);
 2477: 	if ($lang=~/(\-|\_)/) {
 2478: 	    push(@genlanguages,(split(/(\-|\_)/,$lang))[0]);
 2479: 	}
 2480:     }
 2481:     return @genlanguages;
 2482: }
 2483: 
 2484: ###############################################################
 2485: ##               Student Answer Attempts                     ##
 2486: ###############################################################
 2487: 
 2488: =pod
 2489: 
 2490: =head1 Alternate Problem Views
 2491: 
 2492: =over 4
 2493: 
 2494: =item * get_previous_attempt($symb, $username, $domain, $course,
 2495:     $getattempt, $regexp, $gradesub)
 2496: 
 2497: Return string with previous attempt on problem. Arguments:
 2498: 
 2499: =over 4
 2500: 
 2501: =item * $symb: Problem, including path
 2502: 
 2503: =item * $username: username of the desired student
 2504: 
 2505: =item * $domain: domain of the desired student
 2506: 
 2507: =item * $course: Course ID
 2508: 
 2509: =item * $getattempt: Leave blank for all attempts, otherwise put
 2510:     something
 2511: 
 2512: =item * $regexp: if string matches this regexp, the string will be
 2513:     sent to $gradesub
 2514: 
 2515: =item * $gradesub: routine that processes the string if it matches $regexp
 2516: 
 2517: =back
 2518: 
 2519: The output string is a table containing all desired attempts, if any.
 2520: 
 2521: =cut
 2522: 
 2523: sub get_previous_attempt {
 2524:   my ($symb,$username,$domain,$course,$getattempt,$regexp,$gradesub)=@_;
 2525:   my $prevattempts='';
 2526:   no strict 'refs';
 2527:   if ($symb) {
 2528:     my (%returnhash)=
 2529:       &Apache::lonnet::restore($symb,$course,$domain,$username);
 2530:     if ($returnhash{'version'}) {
 2531:       my %lasthash=();
 2532:       my $version;
 2533:       for ($version=1;$version<=$returnhash{'version'};$version++) {
 2534:         foreach my $key (sort(split(/\:/,$returnhash{$version.':keys'}))) {
 2535: 	  $lasthash{$key}=$returnhash{$version.':'.$key};
 2536:         }
 2537:       }
 2538:       $prevattempts='<table border="0" width="100%"><tr><td bgcolor="#777777">';
 2539:       $prevattempts.='<table border="0" width="100%"><tr bgcolor="#e6ffff"><td>History</td>';
 2540:       foreach my $key (sort(keys(%lasthash))) {
 2541: 	my ($ign,@parts) = split(/\./,$key);
 2542: 	if ($#parts > 0) {
 2543: 	  my $data=$parts[-1];
 2544: 	  pop(@parts);
 2545: 	  $prevattempts.='<td>Part '.join('.',@parts).'<br />'.$data.'&nbsp;</td>';
 2546: 	} else {
 2547: 	  if ($#parts == 0) {
 2548: 	    $prevattempts.='<th>'.$parts[0].'</th>';
 2549: 	  } else {
 2550: 	    $prevattempts.='<th>'.$ign.'</th>';
 2551: 	  }
 2552: 	}
 2553:       }
 2554:       if ($getattempt eq '') {
 2555: 	for ($version=1;$version<=$returnhash{'version'};$version++) {
 2556: 	  $prevattempts.='</tr><tr bgcolor="#ffffe6"><td>Transaction '.$version.'</td>';
 2557: 	    foreach my $key (sort(keys(%lasthash))) {
 2558: 	       my $value;
 2559: 	       if ($key =~ /timestamp/) {
 2560: 		  $value=scalar(localtime($returnhash{$version.':'.$key}));
 2561: 	       } else {
 2562: 		  $value=$returnhash{$version.':'.$key};
 2563: 	       }
 2564: 	       $prevattempts.='<td>'.&unescape($value).'&nbsp;</td>';   
 2565: 	    }
 2566: 	 }
 2567:       }
 2568:       $prevattempts.='</tr><tr bgcolor="#ffffe6"><td>Current</td>';
 2569:       foreach my $key (sort(keys(%lasthash))) {
 2570: 	my $value;
 2571: 	if ($key =~ /timestamp/) {
 2572: 	  $value=scalar(localtime($lasthash{$key}));
 2573: 	} else {
 2574: 	  $value=$lasthash{$key};
 2575: 	}
 2576: 	$value=&unescape($value);
 2577: 	if ($key =~/$regexp$/ && (defined &$gradesub)) {$value = &$gradesub($value)}
 2578: 	$prevattempts.='<td>'.$value.'&nbsp;</td>';
 2579:       }
 2580:       $prevattempts.='</tr></table></td></tr></table>';
 2581:     } else {
 2582:       $prevattempts='Nothing submitted - no attempts.';
 2583:     }
 2584:   } else {
 2585:     $prevattempts='No data.';
 2586:   }
 2587: }
 2588: 
 2589: sub relative_to_absolute {
 2590:     my ($url,$output)=@_;
 2591:     my $parser=HTML::TokeParser->new(\$output);
 2592:     my $token;
 2593:     my $thisdir=$url;
 2594:     my @rlinks=();
 2595:     while ($token=$parser->get_token) {
 2596: 	if ($token->[0] eq 'S') {
 2597: 	    if ($token->[1] eq 'a') {
 2598: 		if ($token->[2]->{'href'}) {
 2599: 		    $rlinks[$#rlinks+1]=$token->[2]->{'href'};
 2600: 		}
 2601: 	    } elsif ($token->[1] eq 'img' || $token->[1] eq 'embed' ) {
 2602: 		$rlinks[$#rlinks+1]=$token->[2]->{'src'};
 2603: 	    } elsif ($token->[1] eq 'base') {
 2604: 		$thisdir=$token->[2]->{'href'};
 2605: 	    }
 2606: 	}
 2607:     }
 2608:     $thisdir=~s-/[^/]*$--;
 2609:     foreach my $link (@rlinks) {
 2610: 	unless (($link=~/^http:\/\//i) ||
 2611: 		($link=~/^\//) ||
 2612: 		($link=~/^javascript:/i) ||
 2613: 		($link=~/^mailto:/i) ||
 2614: 		($link=~/^\#/)) {
 2615: 	    my $newlocation=&Apache::lonnet::hreflocation($thisdir,$link);
 2616: 	    $output=~s/(\"|\'|\=\s*)\Q$link\E(\"|\'|\s|\>)/$1$newlocation$2/;
 2617: 	}
 2618:     }
 2619: # -------------------------------------------------- Deal with Applet codebases
 2620:     $output=~s/(\<applet[^\>]+)(codebase\=[^\S\>]+)*([^\>]*)\>/$1.($2?$2:' codebase="'.$thisdir.'"').$3.'>'/gei;
 2621:     return $output;
 2622: }
 2623: 
 2624: =pod
 2625: 
 2626: =item * get_student_view
 2627: 
 2628: show a snapshot of what student was looking at
 2629: 
 2630: =cut
 2631: 
 2632: sub get_student_view {
 2633:   my ($symb,$username,$domain,$courseid,$target,$moreenv) = @_;
 2634:   my ($map,$id,$feedurl) = &Apache::lonnet::decode_symb($symb);
 2635:   my (%form);
 2636:   my @elements=('symb','courseid','domain','username');
 2637:   foreach my $element (@elements) {
 2638:       $form{'grade_'.$element}=eval '$'.$element #'
 2639:   }
 2640:   if (defined($moreenv)) {
 2641:       %form=(%form,%{$moreenv});
 2642:   }
 2643:   if (defined($target)) { $form{'grade_target'} = $target; }
 2644:   $feedurl=&Apache::lonnet::clutter($feedurl);
 2645:   my $userview=&Apache::lonnet::ssi_body($feedurl,%form);
 2646:   $userview=~s/\<body[^\>]*\>//gi;
 2647:   $userview=~s/\<\/body\>//gi;
 2648:   $userview=~s/\<html\>//gi;
 2649:   $userview=~s/\<\/html\>//gi;
 2650:   $userview=~s/\<head\>//gi;
 2651:   $userview=~s/\<\/head\>//gi;
 2652:   $userview=~s/action\s*\=/would_be_action\=/gi;
 2653:   $userview=&relative_to_absolute($feedurl,$userview);
 2654:   return $userview;
 2655: }
 2656: 
 2657: =pod
 2658: 
 2659: =item * get_student_answers() 
 2660: 
 2661: show a snapshot of how student was answering problem
 2662: 
 2663: =cut
 2664: 
 2665: sub get_student_answers {
 2666:   my ($symb,$username,$domain,$courseid,%form) = @_;
 2667:   my ($map,$id,$feedurl) = &Apache::lonnet::decode_symb($symb);
 2668:   my (%moreenv);
 2669:   my @elements=('symb','courseid','domain','username');
 2670:   foreach my $element (@elements) {
 2671:     $moreenv{'grade_'.$element}=eval '$'.$element #'
 2672:   }
 2673:   $moreenv{'grade_target'}='answer';
 2674:   %moreenv=(%form,%moreenv);
 2675:   my $userview=&Apache::lonnet::ssi('/res/'.$feedurl,%moreenv);
 2676:   return $userview;
 2677: }
 2678: 
 2679: =pod
 2680: 
 2681: =item * &submlink()
 2682: 
 2683: Inputs: $text $uname $udom $symb $target
 2684: 
 2685: Returns: A link to grades.pm such as to see the SUBM view of a student
 2686: 
 2687: =cut
 2688: 
 2689: ###############################################
 2690: sub submlink {
 2691:     my ($text,$uname,$udom,$symb,$target)=@_;
 2692:     if (!($uname && $udom)) {
 2693: 	(my $cursymb, my $courseid,$udom,$uname)=
 2694: 	    &Apache::lonnet::whichuser($symb);
 2695: 	if (!$symb) { $symb=$cursymb; }
 2696:     }
 2697:     if (!$symb) { $symb=&Apache::lonnet::symbread(); }
 2698:     $symb=&escape($symb);
 2699:     if ($target) { $target="target=\"$target\""; }
 2700:     return '<a href="/adm/grades?&command=submission&'.
 2701: 	'symb='.$symb.'&student='.$uname.
 2702: 	'&userdom='.$udom.'" '.$target.'>'.$text.'</a>';
 2703: }
 2704: ##############################################
 2705: 
 2706: =pod
 2707: 
 2708: =item * &pgrdlink()
 2709: 
 2710: Inputs: $text $uname $udom $symb $target
 2711: 
 2712: Returns: A link to grades.pm such as to see the PGRD view of a student
 2713: 
 2714: =cut
 2715: 
 2716: ###############################################
 2717: sub pgrdlink {
 2718:     my $link=&submlink(@_);
 2719:     $link=~s/(&command=submission)/$1&showgrading=yes/;
 2720:     return $link;
 2721: }
 2722: ##############################################
 2723: 
 2724: =pod
 2725: 
 2726: =item * &pprmlink()
 2727: 
 2728: Inputs: $text $uname $udom $symb $target
 2729: 
 2730: Returns: A link to parmset.pm such as to see the PPRM view of a
 2731: student and a specific resource
 2732: 
 2733: =cut
 2734: 
 2735: ###############################################
 2736: sub pprmlink {
 2737:     my ($text,$uname,$udom,$symb,$target)=@_;
 2738:     if (!($uname && $udom)) {
 2739: 	(my $cursymb, my $courseid,$udom,$uname)=
 2740: 	    &Apache::lonnet::whichuser($symb);
 2741: 	if (!$symb) { $symb=$cursymb; }
 2742:     }
 2743:     if (!$symb) { $symb=&Apache::lonnet::symbread(); }
 2744:     $symb=&escape($symb);
 2745:     if ($target) { $target="target=\"$target\""; }
 2746:     return '<a href="/adm/parmset?&command=set&'.
 2747: 	'symb='.$symb.'&uname='.$uname.
 2748: 	'&udom='.$udom.'" '.$target.'>'.$text.'</a>';
 2749: }
 2750: ##############################################
 2751: 
 2752: =pod
 2753: 
 2754: =back
 2755: 
 2756: =cut
 2757: 
 2758: ###############################################
 2759: 
 2760: 
 2761: sub timehash {
 2762:     my @ltime=localtime(shift);
 2763:     return ( 'seconds' => $ltime[0],
 2764:              'minutes' => $ltime[1],
 2765:              'hours'   => $ltime[2],
 2766:              'day'     => $ltime[3],
 2767:              'month'   => $ltime[4]+1,
 2768:              'year'    => $ltime[5]+1900,
 2769:              'weekday' => $ltime[6],
 2770:              'dayyear' => $ltime[7]+1,
 2771:              'dlsav'   => $ltime[8] );
 2772: }
 2773: 
 2774: sub utc_string {
 2775:     my ($date)=@_;
 2776:     return strftime("%Y%m%dT%H%M%SZ",gmtime($date));
 2777: }
 2778: 
 2779: sub maketime {
 2780:     my %th=@_;
 2781:     return POSIX::mktime(
 2782:         ($th{'seconds'},$th{'minutes'},$th{'hours'},
 2783:          $th{'day'},$th{'month'}-1,$th{'year'}-1900,0,0,-1));
 2784: }
 2785: 
 2786: #########################################
 2787: 
 2788: sub findallcourses {
 2789:     my ($roles) = @_;
 2790:     my %roles;
 2791:     if (ref($roles)) { %roles = map { $_ => 1 } @{$roles}; }
 2792:     my %courses;
 2793:     my $now=time;
 2794:     foreach my $key (keys(%env)) {
 2795: 	if ( $key=~m{^user\.role\.(\w+)\./(\w+)/(\w+)/?(\w*)$} ||
 2796:              $key=~m{^user\.role\.(cr/\w+/\w+/\w+)\./(\w+)/(\w+)}) {
 2797: 	    my ($role,$domain,$id,$sec) = ($1,$2,$3,$4);
 2798: 	    next if ($role eq 'ca' || $role eq 'aa');
 2799: 	    next if (%roles && !exists($roles{$role}));
 2800: 	    my ($starttime,$endtime)=split(/\./,$env{$key});
 2801:             my $active=1;
 2802:             if ($starttime) {
 2803: 		if ($now<$starttime) { $active=0; }
 2804:             }
 2805:             if ($endtime) {
 2806:                 if ($now>$endtime) { $active=0; }
 2807:             }
 2808:             if ($active) {
 2809:                 if ($sec eq '') {
 2810:                     $sec = 'none';
 2811:                 }
 2812:                 $courses{$domain.'_'.$id}{$sec} = 1;
 2813:             }
 2814:         }
 2815:     }
 2816:     return %courses;
 2817: }
 2818: 
 2819: ###############################################
 2820: 
 2821: sub blockcheck {
 2822:     my ($setters,$activity) = @_;
 2823:     # Retrieve active student roles and active course coordinator/instructor roles
 2824: 
 2825:     my %live_courses = &findallcourses();
 2826: 
 2827:     # Retrieve blocking times and identity of blocker for active courses
 2828:     # unless user has 'evb' privilege.
 2829: 
 2830:     my $startblock = 0;
 2831:     my $endblock = 0;
 2832: 
 2833:     foreach my $course (keys(%live_courses)) {
 2834:         my $cdom = $env{'course.'.$course.'.domain'};
 2835:         my $cnum = $env{'course.'.$course.'.num'};
 2836:         my $noblock = 0;
 2837:         foreach my $sec (keys(%{$live_courses{$course}})) {
 2838:             my $role = 'cm./'.$cdom.'/'.$cnum;
 2839:             if ($sec ne 'none') {
 2840:                 $role .= '/'.$sec;
 2841:             }
 2842:             if (&Apache::lonnet::allowed('evb',undef,undef,$role)) {
 2843:                 $noblock = 1;
 2844:                 last;
 2845:             }
 2846:         }
 2847:         # if they have the evb priv and are currently not playing student
 2848:         next if (($noblock) &&
 2849:                  ($env{'request.role'} !~ m{^st\./$cdom/$cnum}));
 2850: 
 2851:         $setters->{$course} = {};
 2852:         $setters->{$course}{'staff'} = [];
 2853:         $setters->{$course}{'times'} = [];
 2854:         my %records = &Apache::lonnet::dump('comm_block',$cdom,$cnum);
 2855:         foreach my $record (keys(%records)) {
 2856:             my ($start,$end) = ($record =~ m/^(\d+)____(\d+)$/);
 2857:             if ($start <= time && $end >= time) {
 2858:                 my ($staff_name,$staff_dom,$title,$blocks) =
 2859:                     &parse_block_record($records{$record});
 2860:                 if ($blocks->{$activity} eq 'on') {
 2861:                     push(@{$$setters{$course}{'staff'}}, [$staff_name,$staff_dom]);                    push(@{$$setters{$course}{'times'}}, [$start,$end]);
 2862:                     if ( ($startblock == 0) || ($startblock > $1) ) {
 2863:                         $startblock = $1;
 2864:                     }
 2865:                     if ( ($endblock == 0) || ($endblock < $2) ) {
 2866:                         $endblock = $2;
 2867:                     }
 2868:                 }
 2869:             }
 2870:         }
 2871:     }
 2872:     return ($startblock,$endblock);
 2873: }
 2874: 
 2875: sub parse_block_record {
 2876:     my ($record) = @_;
 2877:     my ($setuname,$setudom,$title,$blocks);
 2878:     if (ref($record) eq 'HASH') {
 2879:         ($setuname,$setudom) = split(/:/,$record->{'setter'});
 2880:         $title = &unescape($record->{'event'});
 2881:         $blocks = $record->{'blocks'};
 2882: 
 2883:     } else {
 2884:         my @data = split(/:/,$record,3);
 2885:         if (scalar(@data) eq 2) {
 2886:             $title = $data[1];
 2887:             ($setuname,$setudom) = split(/@/,$data[0]);
 2888:         } else {
 2889:             ($setuname,$setudom,$title) = @data;
 2890:         }
 2891:         $blocks = { 'com' => 'on' };
 2892:     }
 2893:     return ($setuname,$setudom,$title,$blocks);
 2894: }
 2895: 
 2896: sub build_block_table {
 2897:     my ($startblock,$endblock,$setters) = @_;
 2898:     my %lt = &Apache::lonlocal::texthash(
 2899:         'cacb' => 'Currently active communication blocks',
 2900:         'cour' => 'Course',
 2901:         'dura' => 'Duration',
 2902:         'blse' => 'Block set by'
 2903:     );
 2904:     my $output;
 2905:     $output = '<br /><br />'.$lt{'cacb'}.':<br /><br />';
 2906:     $output .= &start_data_table();
 2907:     $output .= '
 2908: <tr>
 2909:  <th>'.$lt{'cour'}.'</th>
 2910:  <th>'.$lt{'dura'}.'</th>
 2911:  <th>'.$lt{'blse'}.'</th>
 2912: </tr>
 2913: ';
 2914:     foreach my $course (keys(%{$setters})) {
 2915:         my %courseinfo=&Apache::lonnet::coursedescription($course);
 2916:         for (my $i=0; $i<@{$$setters{$course}{staff}}; $i++) {
 2917:             my ($uname,$udom) = @{$$setters{$course}{staff}[$i]};
 2918:             my $fullname = &Apache::loncommon::plainname($uname,$udom);
 2919:             my ($openblock,$closeblock) = @{$$setters{$course}{times}[$i]};
 2920:             $openblock = &Apache::lonlocal::locallocaltime($openblock);
 2921:             $closeblock= &Apache::lonlocal::locallocaltime($closeblock);
 2922:             $output .= &Apache::loncommon::start_data_table_row().
 2923:                        '<td>'.$courseinfo{'description'}.'</td>'.
 2924:                        '<td>'.$openblock.' to '.$closeblock.'</td>'.
 2925:                        '<td>'.$fullname.' ('.$uname.':'.$udom.
 2926:                        ')</td>'.
 2927:                         &Apache::loncommon::end_data_table_row();
 2928:         }
 2929:     }
 2930:     $output .= &end_data_table();
 2931: }
 2932: 
 2933: ###############################################
 2934: 
 2935: =pod
 2936: 
 2937: =head1 Domain Template Functions
 2938: 
 2939: =over 4
 2940: 
 2941: =item * &determinedomain()
 2942: 
 2943: Inputs: $domain (usually will be undef)
 2944: 
 2945: Returns: Determines which domain should be used for designs
 2946: 
 2947: =cut
 2948: 
 2949: ###############################################
 2950: sub determinedomain {
 2951:     my $domain=shift;
 2952:    if (! $domain) {
 2953:         # Determine domain if we have not been given one
 2954:         $domain = $Apache::lonnet::perlvar{'lonDefDomain'};
 2955:         if ($env{'user.domain'}) { $domain=$env{'user.domain'}; }
 2956:         if ($env{'request.role.domain'}) { 
 2957:             $domain=$env{'request.role.domain'}; 
 2958:         }
 2959:     }
 2960:     return $domain;
 2961: }
 2962: ###############################################
 2963: =pod
 2964: 
 2965: =item * &domainlogo()
 2966: 
 2967: Inputs: $domain (usually will be undef)
 2968: 
 2969: Returns: A link to a domain logo, if the domain logo exists.
 2970: If the domain logo does not exist, a description of the domain.
 2971: 
 2972: =cut
 2973: 
 2974: ###############################################
 2975: sub domainlogo {
 2976:     my $domain = &determinedomain(shift);    
 2977:      # See if there is a logo
 2978:     if (-e '/home/httpd/html/adm/lonDomLogos/'.$domain.'.gif') {
 2979: 	my $logo=&lonhttpdurl("/adm/lonDomLogos/$domain.gif");
 2980:         return '<img src="'.$logo.'" alt="'.$domain.'" />';
 2981:     } elsif(exists($Apache::lonnet::domaindescription{$domain})) {
 2982:         return $Apache::lonnet::domaindescription{$domain};
 2983:     } else {
 2984:         return '';
 2985:     }
 2986: }
 2987: ##############################################
 2988: 
 2989: =pod
 2990: 
 2991: =item * &designparm()
 2992: 
 2993: Inputs: $which parameter; $domain (usually will be undef)
 2994: 
 2995: Returns: value of designparamter $which
 2996: 
 2997: =cut
 2998: 
 2999: 
 3000: ##############################################
 3001: sub designparm {
 3002:     my ($which,$domain)=@_;
 3003:     if ($env{'browser.blackwhite'} eq 'on') {
 3004: 	if ($which=~/\.(font|alink|vlink|link)$/) {
 3005: 	    return '#000000';
 3006: 	}
 3007: 	if ($which=~/\.(pgbg|sidebg)$/) {
 3008: 	    return '#FFFFFF';
 3009: 	}
 3010: 	if ($which=~/\.tabbg$/) {
 3011: 	    return '#CCCCCC';
 3012: 	}
 3013:     }
 3014:     if (exists($env{'environment.color.'.$which})) {
 3015: 	return $env{'environment.color.'.$which};
 3016:     }
 3017:     $domain=&determinedomain($domain);
 3018:     if (exists($designhash{$domain.'.'.$which})) {
 3019: 	return $designhash{$domain.'.'.$which};
 3020:     } else {
 3021:         return $designhash{'default.'.$which};
 3022:     }
 3023: }
 3024: 
 3025: ###############################################
 3026: ###############################################
 3027: 
 3028: =pod
 3029: 
 3030: =back
 3031: 
 3032: =head1 HTTP Helpers
 3033: 
 3034: =over 4
 3035: 
 3036: =item * &bodytag()
 3037: 
 3038: Returns a uniform header for LON-CAPA web pages.
 3039: 
 3040: Inputs: 
 3041: 
 3042: =over 4
 3043: 
 3044: =item * $title, A title to be displayed on the page.
 3045: 
 3046: =item * $function, the current role (can be undef).
 3047: 
 3048: =item * $addentries, extra parameters for the <body> tag.
 3049: 
 3050: =item * $bodyonly, if defined, only return the <body> tag.
 3051: 
 3052: =item * $domain, if defined, force a given domain.
 3053: 
 3054: =item * $forcereg, if page should register as content page (relevant for 
 3055:             text interface only)
 3056: 
 3057: =item * $customtitle, alternate text to use instead of $title
 3058:                       in the title box that appears, this text
 3059:                       is not auto translated like the $title is
 3060: 
 3061: =item * $notopbar, if true, keep the 'what is this' info but remove the
 3062:                    navigational links
 3063: 
 3064: =item * $bgcolor, used to override the bgcolor on a webpage to a specific value
 3065: 
 3066: =item * $notitle, if true keep the nav controls, but remove the title bar
 3067: 
 3068: =item * $no_inline_link, if true and in remote mode, don't show the 
 3069:          'Switch To Inline Menu' link
 3070: 
 3071: =item * $args, optional argument valid values are
 3072:             no_auto_mt_title -> prevents &mt()ing the title arg
 3073: 
 3074: =back
 3075: 
 3076: Returns: A uniform header for LON-CAPA web pages.  
 3077: If $bodyonly is nonzero, a string containing a <body> tag will be returned.
 3078: If $bodyonly is undef or zero, an html string containing a <body> tag and 
 3079: other decorations will be returned.
 3080: 
 3081: =cut
 3082: 
 3083: sub bodytag {
 3084:     my ($title,$function,$addentries,$bodyonly,$domain,$forcereg,$customtitle,
 3085: 	$notopbar,$bgcolor,$notitle,$no_inline_link,$args)=@_;
 3086: 
 3087:     if (!$args->{'no_auto_mt_title'}) { $title = &mt($title); }
 3088: 
 3089:     $function = &get_users_function() if (!$function);
 3090:     my $img =    &designparm($function.'.img',$domain);
 3091:     my $font =   &designparm($function.'.font',$domain);
 3092:     my $pgbg   = $bgcolor || &designparm($function.'.pgbg',$domain);
 3093: 
 3094:     my %design = ( 'style'   => 'margin-top: 0px',
 3095: 		   'bgcolor' => $pgbg,
 3096: 		   'text'    => $font,
 3097:                    'alink'   => &designparm($function.'.alink',$domain),
 3098: 		   'vlink'   => &designparm($function.'.vlink',$domain),
 3099: 		   'link'    => &designparm($function.'.link',$domain),);
 3100:     @design{keys(%$addentries)} = @$addentries{keys(%$addentries)}; 
 3101: 
 3102:  # role and realm
 3103:     my ($role,$realm) = split(/\./,$env{'request.role'},2);
 3104:     if ($role  eq 'ca') {
 3105:         my ($rdom,$rname) = ($realm =~ m-^/(\w+)/(\w+)$-);
 3106:         $realm = &plainname($rname,$rdom).':'.$rdom;
 3107:     } 
 3108: # realm
 3109:     if ($env{'request.course.id'}) {
 3110:         if ($env{'request.role'} !~ /^cr/) {
 3111:             $role = &Apache::lonnet::plaintext($role,&course_type());
 3112:         }
 3113: 	$realm = $env{'course.'.$env{'request.course.id'}.'.description'};
 3114:     } else {
 3115:         $role = &Apache::lonnet::plaintext($role);
 3116:     }
 3117: 
 3118:     if (!$realm) { $realm='&nbsp;'; }
 3119: # Set messages
 3120:     my $messages=&domainlogo($domain);
 3121: # Port for miniserver
 3122:     my $lonhttpdPort=$Apache::lonnet::perlvar{'lonhttpdPort'};
 3123:     if (!defined($lonhttpdPort)) { $lonhttpdPort='8080'; }
 3124: 
 3125:     my $extra_body_attr = &make_attr_string($forcereg,\%design);
 3126: 
 3127: # construct main body tag
 3128:     my $bodytag = "<body $extra_body_attr>".
 3129: 	&Apache::lontexconvert::init_math_support();
 3130: 
 3131:     if ($bodyonly 
 3132: 	|| ($env{'request.state'} eq 'construct' 
 3133: 	    && $env{'environment.remote'} ne 'off' )) {
 3134:         return $bodytag;
 3135:     } elsif ($env{'browser.interface'} eq 'textual') {
 3136: # Accessibility
 3137:           
 3138: 	$bodytag.=&Apache::lonmenu::menubuttons($forcereg,$forcereg);
 3139: 	if (!$notitle) {
 3140: 	    $bodytag.='<h1>LON-CAPA: '.$title.'</h1>';
 3141: 	}
 3142: 	return $bodytag;
 3143:     }
 3144: 
 3145:     my $name = &plainname($env{'user.name'},$env{'user.domain'});
 3146:     if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
 3147: 	undef($role);
 3148:     } else {
 3149: 	$name = &aboutmewrapper($name,$env{'user.name'},$env{'user.domain'});
 3150:     }
 3151:     
 3152:     my $roleinfo=(<<ENDROLE);
 3153: <td class="LC_title_bar_who">
 3154: <div class="LC_title_bar_name">
 3155:     $name
 3156:     &nbsp;
 3157: </div>
 3158: <div class="LC_title_bar_role">
 3159: $role&nbsp;
 3160: </div>
 3161: <div class="LC_title_bar_realm">
 3162: $realm&nbsp;
 3163: </div>
 3164: </td>
 3165: ENDROLE
 3166: 
 3167:     my $titleinfo = '<span class="LC_title_bar_title">'.$title.'</span>';
 3168:     if ($customtitle) {
 3169:         $titleinfo = $customtitle;
 3170:     }
 3171:     #
 3172:     # Extra info if you are the DC
 3173:     my $dc_info = '';
 3174:     if ($env{'user.adv'} && exists($env{'user.role.dc./'.
 3175:                         $env{'course.'.$env{'request.course.id'}.
 3176:                                  '.domain'}.'/'})) {
 3177:         my $cid = $env{'request.course.id'};
 3178:         $dc_info.= $cid.' '.$env{'course.'.$cid.'.internal.coursecode'};
 3179:         $dc_info =~ s/\s+$//;
 3180:         $dc_info = '('.$dc_info.')';
 3181:     }
 3182: 
 3183:     if ($env{'environment.remote'} eq 'off') {
 3184:         # No Remote
 3185: 	if ($env{'request.state'} eq 'construct') {
 3186: 	    $forcereg=1;
 3187: 	}
 3188: 
 3189: 	if (!$customtitle && $env{'request.state'} eq 'construct') {
 3190: 	    # this is for resources; directories have customtitle, and crumbs
 3191:             # and select recent are created in lonpubdir.pm  
 3192: 	    my ($uname,$thisdisfn)=
 3193: 		($env{'request.filename'} =~ m|^/home/([^/]+)/public_html/(.*)|);
 3194: 	    my $formaction='/priv/'.$uname.'/'.$thisdisfn;
 3195: 	    $formaction=~s/\/+/\//g;
 3196: 
 3197: 	    my $parentpath = '';
 3198: 	    my $lastitem = '';
 3199: 	    if ($thisdisfn =~ m-(.+/)([^/]*)$-) {
 3200: 		$parentpath = $1;
 3201: 		$lastitem = $2;
 3202: 	    } else {
 3203: 		$lastitem = $thisdisfn;
 3204: 	    }
 3205: 	    $titleinfo = 
 3206: 		&Apache::loncommon::help_open_menu('','',3,'Authoring').
 3207: 		'<b>Construction Space</b>:&nbsp;'. 
 3208: 		'<form name="dirs" method="post" action="'.$formaction
 3209: 		.'" target="_top"><tt><b>'
 3210: 		.&Apache::lonhtmlcommon::crumbs($uname.'/'.$parentpath,'_top','/priv','','+1',1)."<font size=\"+1\">$lastitem</font></b></tt><br />"
 3211: 		.&Apache::lonhtmlcommon::select_recent('construct','recent','this.form.action=this.form.recent.value;this.form.submit()')
 3212: 		.'</form>'
 3213: 		.&Apache::lonmenu::constspaceform();
 3214:         }
 3215: 
 3216:         my $titletable;
 3217: 	if (!$notitle) {
 3218: 	    $titletable =
 3219: 		'<table id="LC_title_bar">'.
 3220:                          "<tr><td> $titleinfo $dc_info</td>".$roleinfo.
 3221: 			 '</tr></table>';
 3222: 	}
 3223: 	if ($notopbar) {
 3224: 	    $bodytag .= $titletable;
 3225: 	} else {
 3226: 	    if ($env{'request.state'} eq 'construct') {
 3227:                 $bodytag .= &Apache::lonmenu::menubuttons($forcereg,$forcereg,
 3228: 							  $titletable);
 3229:             } else {
 3230:                 $bodytag .= &Apache::lonmenu::menubuttons($forcereg,$forcereg).
 3231: 		    $titletable;
 3232:             }
 3233:         }
 3234:         return $bodytag;
 3235:     }
 3236: 
 3237: #
 3238: # Top frame rendering, Remote is up
 3239: #
 3240: 
 3241:     my $upperleft='<img src="http://'.$ENV{'HTTP_HOST'}.':'.
 3242:         $lonhttpdPort.$img.'" alt="'.$function.'" />';
 3243: 
 3244:     # Explicit link to get inline menu
 3245:     my $menu= ($no_inline_link?''
 3246: 	       :'<br /><a href="/adm/remote?action=collapse">'.&mt('Switch to Inline Menu Mode').'</a>');
 3247:     #
 3248:     if ($notitle) {
 3249: 	return $bodytag;
 3250:     }
 3251:     return(<<ENDBODY);
 3252: $bodytag
 3253: <table id="LC_title_bar" class="LC_with_remote">
 3254: <tr><td class="LC_title_bar_role_logo">$upperleft</td>
 3255:     <td class="LC_title_bar_domain_logo">$messages&nbsp;</td>
 3256: </tr>
 3257: <tr><td>$titleinfo $dc_info $menu</td>
 3258: $roleinfo
 3259: </tr>
 3260: </table>
 3261: ENDBODY
 3262: }
 3263: 
 3264: sub make_attr_string {
 3265:     my ($register,$attr_ref) = @_;
 3266: 
 3267:     if ($attr_ref && !ref($attr_ref)) {
 3268: 	die("addentries Must be a hash ref ".
 3269: 	    join(':',caller(1))." ".
 3270: 	    join(':',caller(0))." ");
 3271:     }
 3272: 
 3273:     if ($register) {
 3274: 	my ($on_load,$on_unload);
 3275: 	foreach my $key (keys(%{$attr_ref})) {
 3276: 	    if      (lc($key) eq 'onload') {
 3277: 		$on_load.=$attr_ref->{$key}.';';
 3278: 		delete($attr_ref->{$key});
 3279: 
 3280: 	    } elsif (lc($key) eq 'onunload') {
 3281: 		$on_unload.=$attr_ref->{$key}.';';
 3282: 		delete($attr_ref->{$key});
 3283: 	    }
 3284: 	}
 3285: 	$attr_ref->{'onload'}  =
 3286: 	    &Apache::lonmenu::loadevents().  $on_load;
 3287: 	$attr_ref->{'onunload'}=
 3288: 	    &Apache::lonmenu::unloadevents().$on_unload;
 3289:     }
 3290: 
 3291: # Accessibility font enhance
 3292:     if ($env{'browser.fontenhance'} eq 'on') {
 3293: 	my $style;
 3294: 	foreach my $key (keys(%{$attr_ref})) {
 3295: 	    if (lc($key) eq 'style') {
 3296: 		$style.=$attr_ref->{$key}.';';
 3297: 		delete($attr_ref->{$key});
 3298: 	    }
 3299: 	}
 3300: 	$attr_ref->{'style'}=$style.'; font-size: x-large;';
 3301:     }
 3302: 
 3303:     if ($env{'browser.blackwhite'} eq 'on') {
 3304: 	delete($attr_ref->{'font'});
 3305: 	delete($attr_ref->{'link'});
 3306: 	delete($attr_ref->{'alink'});
 3307: 	delete($attr_ref->{'vlink'});
 3308: 	delete($attr_ref->{'bgcolor'});
 3309: 	delete($attr_ref->{'background'});
 3310:     }
 3311: 
 3312:     my $attr_string;
 3313:     foreach my $attr (keys(%$attr_ref)) {
 3314: 	$attr_string .= " $attr=\"".$attr_ref->{$attr}.'" ';
 3315:     }
 3316:     return $attr_string;
 3317: }
 3318: 
 3319: 
 3320: ###############################################
 3321: ###############################################
 3322: 
 3323: =pod
 3324: 
 3325: =back
 3326: 
 3327: =head1 HTML Helpers
 3328: 
 3329: =over 4
 3330: 
 3331: =item * &endbodytag()
 3332: 
 3333: Returns a uniform footer for LON-CAPA web pages.
 3334: 
 3335: Inputs: none
 3336: 
 3337: =back
 3338: 
 3339: =cut
 3340: 
 3341: sub endbodytag {
 3342:     my $endbodytag='</body>';
 3343:     $endbodytag=&Apache::lontexconvert::jsMath_process()."\n".$endbodytag;
 3344:     if ( exists( $env{'internal.head.redirect'} ) ) {
 3345: 	$endbodytag=
 3346: 	    "<br /><a href=\"$env{'internal.head.redirect'}\">".
 3347: 	    &mt('Continue').'</a>'.
 3348: 	    $endbodytag;
 3349:     }
 3350:     return $endbodytag;
 3351: }
 3352: 
 3353: =pod
 3354: 
 3355: =over 4
 3356: 
 3357: =item * &standard_css()
 3358: 
 3359: Returns a style sheet
 3360: 
 3361: Inputs: (all optional)
 3362:             domain         -> force to color decorate a page for a specific
 3363:                                domain
 3364:             function       -> force usage of a specific rolish color scheme
 3365:             bgcolor        -> override the default page bgcolor
 3366: 
 3367: =back
 3368: 
 3369: =cut
 3370: 
 3371: sub standard_css {
 3372:     my ($function,$domain,$bgcolor) = @_;
 3373:     $function  = &get_users_function() if (!$function);
 3374:     my $img    = &designparm($function.'.img',   $domain);
 3375:     my $tabbg  = &designparm($function.'.tabbg', $domain);
 3376:     my $font   = &designparm($function.'.font',  $domain);
 3377:     my $sidebg = &designparm($function.'.sidebg',$domain);
 3378:     my $pgbg_or_bgcolor =
 3379: 	         $bgcolor ||
 3380: 	         &designparm($function.'.pgbg',  $domain);
 3381:     my $pgbg   = &designparm($function.'.pgbg',  $domain);
 3382:     my $alink  = &designparm($function.'.alink', $domain);
 3383:     my $vlink  = &designparm($function.'.vlink', $domain);
 3384:     my $link   = &designparm($function.'.link',  $domain);
 3385: 
 3386:     my $sans                 = 'Arial,Helvetica,sans-serif';
 3387:     my $mono                 = 'monospace';
 3388:     my $data_table_head      = $tabbg;
 3389:     my $data_table_light     = '#EEEEEE';
 3390:     my $data_table_dark      = '#DDDDDD';
 3391:     my $data_table_darker    = '#CCCCCC';
 3392:     my $data_table_highlight = '#FFFF00';
 3393:     my $mail_new             = '#FFBB77';
 3394:     my $mail_new_hover       = '#DD9955';
 3395:     my $mail_read            = '#BBBB77';
 3396:     my $mail_read_hover      = '#999944';
 3397:     my $mail_replied         = '#AAAA88';
 3398:     my $mail_replied_hover   = '#888855';
 3399:     my $mail_other           = '#99BBBB';
 3400:     my $mail_other_hover     = '#669999';
 3401:     my $table_header         = '#DDDDDD';
 3402: 
 3403:     my $border = ($env{'browser.type'} eq 'explorer') ? '0px 2px 0px 2px'
 3404: 	                                              : '0px 3px 0px 4px';
 3405: 
 3406:     return <<END;
 3407: h1, h2, h3, th { font-family: $sans }
 3408: a:focus { color: red; background: yellow } 
 3409: table.thinborder { border-collapse: collapse; }
 3410: table.thinborder tr th {  border-style: solid; border-width: 1px; background: $tabbg;}
 3411: table.thinborder tr td { border-style: solid; border-width: 1px}
 3412: 
 3413: form, .inline { display: inline; }
 3414: .center { text-align: center; }
 3415: .LC_filename {font-family: $mono;}
 3416: .LC_error {
 3417:   color: red;
 3418:   font-size: larger;
 3419: }
 3420: .LC_warning,
 3421: .LC_diff_removed {
 3422:   color: red;
 3423: }
 3424: .LC_success,
 3425: .LC_diff_added {
 3426:   color: green;
 3427: }
 3428: .LC_icon {
 3429:   border: 0px;
 3430: }
 3431: 
 3432: table.LC_pastsubmission {
 3433:   border: 1px solid black;
 3434:   margin: 2px;
 3435: }
 3436: 
 3437: table#LC_top_nav, table#LC_menubuttons {
 3438:   width: 100%;
 3439:   background: $pgbg;
 3440:   border: 2px;
 3441:   border-collapse: separate;
 3442:   padding: 0px;
 3443: }
 3444: 
 3445: table#LC_title_bar, table.LC_breadcrumbs, table#LC_nav_location,
 3446: table#LC_title_bar.LC_with_remote {
 3447:   width: 100%;
 3448:   border-color: $pgbg;
 3449:   border-style: solid;
 3450:   border-width: $border;
 3451: 
 3452:   background: $pgbg;
 3453:   font-family: $sans;
 3454:   border-collapse: collapse;
 3455:   padding: 0px;
 3456: }
 3457: 
 3458: table.LC_docs_path {
 3459:   width: 100%;
 3460:   border: 0;
 3461:   background: $pgbg;
 3462:   font-family: $sans;
 3463:   border-collapse: collapse;
 3464:   padding: 0px;
 3465: }
 3466: 
 3467: table#LC_title_bar td {
 3468:   background: $tabbg;
 3469: }
 3470: table#LC_title_bar td.LC_title_bar_who {
 3471:   background: $tabbg;
 3472:   color: $font;
 3473:   font: small $sans;
 3474:   text-align: right;
 3475: }
 3476: span.LC_metadata {
 3477:     font-family: $sans;
 3478: }
 3479: span.LC_title_bar_title {
 3480:   font: bold x-large $sans;
 3481: }
 3482: table#LC_title_bar td.LC_title_bar_domain_logo {
 3483:   background: $sidebg;
 3484:   text-align: right;
 3485:   padding: 0px;
 3486: }
 3487: table#LC_title_bar td.LC_title_bar_role_logo {
 3488:   background: $sidebg;
 3489:   padding: 0px;
 3490: }
 3491: 
 3492: table#LC_menubuttons_mainmenu {
 3493:   background: $pgbg;
 3494:   border: 0px;
 3495:   border-spacing: 1px;
 3496:   padding: 0px 1px;
 3497:   margin: 0px;
 3498:   border-collapse: separate;
 3499: }
 3500: table#LC_menubuttons img, table#LC_menubuttons_mainmenu img {
 3501:   border: 0px;
 3502: }
 3503: table#LC_top_nav td {
 3504:   background: $tabbg;
 3505:   border: 0px;
 3506:   font-size: small;
 3507: }
 3508: table#LC_top_nav td a, div#LC_top_nav a {
 3509:   color: $font;
 3510:   font-family: $sans;
 3511: }
 3512: table#LC_top_nav td.LC_top_nav_logo {
 3513:   background: $tabbg;
 3514:   text-align: left;
 3515:   white-space: nowrap;
 3516:   width: 31px;
 3517: }
 3518: table#LC_top_nav td.LC_top_nav_logo img {
 3519:   border: 0px;
 3520:   vertical-align: bottom;
 3521: }
 3522: table#LC_top_nav td.LC_top_nav_exit,
 3523: table#LC_top_nav td.LC_top_nav_help {
 3524:   width: 2.0em;
 3525: }
 3526: table#LC_top_nav td.LC_top_nav_login {
 3527:   width: 4.0em;
 3528:   text-align: center;
 3529: }
 3530: table.LC_breadcrumbs td, table.LC_docs_path td  {
 3531:   background: $tabbg;
 3532:   color: $font;
 3533:   font-family: $sans;
 3534:   font-size: smaller;
 3535: }
 3536: table.LC_breadcrumbs td.LC_breadcrumbs_component,
 3537: table.LC_docs_path td.LC_docs_path_component {
 3538:   background: $tabbg;
 3539:   color: $font;
 3540:   font-family: $sans;
 3541:   font-size: larger;
 3542:   text-align: right;
 3543: }
 3544: td.LC_table_cell_checkbox {
 3545:   text-align: center;
 3546: }
 3547: 
 3548: .LC_menubuttons_inline_text {
 3549:   color: $font;
 3550:   font-family: $sans;
 3551:   font-size: smaller;
 3552: }
 3553: 
 3554: td.LC_menubuttons_text {
 3555:   color: $font;
 3556:   font-family: $sans;
 3557: }
 3558: td.LC_menubuttons_img {
 3559:   background: $tabbg;
 3560: }
 3561: .LC_current_location {
 3562:   font-family: $sans;
 3563:   background: $tabbg;
 3564: }
 3565: .LC_new_mail {
 3566:   font-family: $sans;
 3567:   font-weight: bold;
 3568: }
 3569: 
 3570: table.LC_aboutme_port {
 3571:   border: 0px;
 3572:   border-collapse: collapse;
 3573:   border-spacing: 0px;
 3574: }
 3575: table.LC_data_table, table.LC_mail_list {
 3576:   border: 1px solid #000000;
 3577:   border-collapse: separate;
 3578:   border-spacing: 1px;
 3579: }
 3580: .LC_data_table_dense {
 3581:   font-size: small;
 3582: }
 3583: table.LC_data_table tr th, table.LC_calendar tr th, table.LC_mail_list tr th {
 3584:   font-weight: bold;
 3585:   background-color: $data_table_head;
 3586:   font-size: smaller;
 3587: }
 3588: table.LC_data_table tr td, 
 3589: table.LC_aboutme_port tr td {
 3590:   background-color: $data_table_light;
 3591:   padding: 2px;
 3592: }
 3593: table.LC_data_table tr.LC_even_row td,
 3594: table.LC_aboutme_port tr.LC_even_row td {
 3595:   background-color: $data_table_dark;
 3596: }
 3597: table.LC_data_table tr.LC_data_table_highlight td {
 3598:   background-color: $data_table_darker;
 3599: }
 3600: table.LC_data_table tr.LC_empty_row td,
 3601: table.LC_whatsnew tr.LC_empty_row td {
 3602:   background-color: #FFFFFF;
 3603:   font-weight: bold;
 3604:   font-style: italic;
 3605:   text-align: center;
 3606:   padding: 8px;
 3607: }
 3608: table.LC_whatsnew tr.LC_empty_row td {
 3609:   padding: 4ex
 3610: }
 3611: 
 3612: 
 3613: table.LC_whatsnew {
 3614: }
 3615: 
 3616: table.LC_whatsnew tr th,
 3617: table.LC_whatsnew tr.LC_info_row td {
 3618:   background-color: #CCC;
 3619:   font-weight: bold;
 3620:   font-size: small;
 3621:   text-align: right;
 3622: }
 3623: table.LC_whatsnew tr td {
 3624:   background-color: #FFF;
 3625:   font-size: small;
 3626:   text-align: right;
 3627: }
 3628: table.LC_whatsnew tr td.LC_first_item {
 3629:   text-align: left;
 3630: }
 3631: 
 3632: table.LC_whatsnew tr.LC_odd_row td {
 3633:   background-color: #EEE;
 3634: }
 3635: 
 3636: table.LC_createuser {
 3637: }
 3638: 
 3639: table.LC_createuser tr.LC_section_row td {
 3640:   font-size: smaller;
 3641: }
 3642: 
 3643: table.LC_createuser tr.LC_info_row td  {
 3644:   background-color: #CCC;
 3645:   font-weight: bold;
 3646:   text-align: center;
 3647: }
 3648: 
 3649: table.LC_calendar {
 3650:   border: 1px solid #000000;
 3651:   border-collapse: collapse;
 3652: }
 3653: table.LC_calendar_pickdate {
 3654:   font-size: xx-small;
 3655: }
 3656: table.LC_calendar tr td {
 3657:   border: 1px solid #000000;
 3658:   vertical-align: top;
 3659: }
 3660: table.LC_calendar tr td.LC_calendar_day_empty {
 3661:   background-color: $data_table_dark;
 3662: }
 3663: table.LC_calendar tr td.LC_calendar_day_current {
 3664:   background-color: $data_table_highlight;
 3665: }
 3666: 
 3667: table.LC_mail_list tr.LC_mail_new {
 3668:   background-color: $mail_new;
 3669: }
 3670: table.LC_mail_list tr.LC_mail_new:hover {
 3671:   background-color: $mail_new_hover;
 3672: }
 3673: table.LC_mail_list tr.LC_mail_read {
 3674:   background-color: $mail_read;
 3675: }
 3676: table.LC_mail_list tr.LC_mail_read:hover {
 3677:   background-color: $mail_read_hover;
 3678: }
 3679: table.LC_mail_list tr.LC_mail_replied {
 3680:   background-color: $mail_replied;
 3681: }
 3682: table.LC_mail_list tr.LC_mail_replied:hover {
 3683:   background-color: $mail_replied_hover;
 3684: }
 3685: table.LC_mail_list tr.LC_mail_other {
 3686:   background-color: $mail_other;
 3687: }
 3688: table.LC_mail_list tr.LC_mail_other:hover {
 3689:   background-color: $mail_other_hover;
 3690: }
 3691: 
 3692: table#LC_portfolio_actions {
 3693:   width: auto;
 3694:   background: $pgbg;
 3695:   border: 0px;
 3696:   border-spacing: 2px 2px;
 3697:   padding: 0px;
 3698:   margin: 0px;
 3699:   border-collapse: separate;
 3700: }
 3701: table#LC_portfolio_actions td.LC_label {
 3702:   background: $tabbg;
 3703:   text-align: right;
 3704: }
 3705: table#LC_portfolio_actions td.LC_value {
 3706:   background: $tabbg;
 3707: }
 3708: 
 3709: table#LC_cstr_controls {
 3710:   width: 100%;
 3711:   border-collapse: collapse;
 3712: }
 3713: table#LC_cstr_controls tr td {
 3714:   border: 4px solid $pgbg;
 3715:   padding: 4px;
 3716:   text-align: center;
 3717:   background: $tabbg;
 3718: }
 3719: table#LC_cstr_controls tr th {
 3720:   border: 4px solid $pgbg;
 3721:   background: $table_header;
 3722:   text-align: center;
 3723:   font-family: $sans;
 3724:   font-size: smaller;
 3725: }
 3726: 
 3727: table#LC_browser {
 3728:  
 3729: }
 3730: table#LC_browser tr th {
 3731:   background: $table_header;
 3732: }
 3733: table#LC_browser tr td {
 3734:   padding: 2px;
 3735: }
 3736: table#LC_browser tr.LC_browser_file,
 3737: table#LC_browser tr.LC_browser_file_published {
 3738:   background: #CCFF88;
 3739: }
 3740: table#LC_browser tr.LC_browser_file_locked,
 3741: table#LC_browser tr.LC_browser_file_unpublished {
 3742:   background: #FFAA99;
 3743: }
 3744: table#LC_browser tr.LC_browser_file_obsolete {
 3745:   background: #AAAAAA;
 3746: }
 3747: table#LC_browser tr.LC_browser_file_modified,
 3748: table#LC_browser tr.LC_browser_file_metamodified {
 3749:   background: #FFFF77;
 3750: }
 3751: table#LC_browser tr.LC_browser_folder {
 3752:   background: #CCCCFF;
 3753: }
 3754: span.LC_current_location {
 3755:   font-size: x-large;
 3756:   background: $pgbg;
 3757: }
 3758: 
 3759: span.LC_parm_menu_item {
 3760:   font-size: larger;
 3761:   font-family: $sans;
 3762: }
 3763: span.LC_parm_scope_all {
 3764:   color: red;
 3765: }
 3766: span.LC_parm_scope_folder {
 3767:   color: green;
 3768: }
 3769: span.LC_parm_scope_resource {
 3770:   color: orange;
 3771: }
 3772: span.LC_parm_part {
 3773:   color: blue;
 3774: }
 3775: span.LC_parm_folder, span.LC_parm_symb {
 3776:   font-size: x-small;
 3777:   font-family: $mono;
 3778:   color: #AAAAAA;
 3779: }
 3780: 
 3781: td.LC_parm_overview_level_menu, td.LC_parm_overview_map_menu,
 3782: td.LC_parm_overview_parm_selectors, td.LC_parm_overview_parm_restrictions {
 3783:   border: 1px solid black;
 3784:   border-collapse: collapse;
 3785: }
 3786: table.LC_parm_overview_restrictions td {
 3787:   border-width: 1px 4px 1px 4px;
 3788:   border-style: solid;
 3789:   border-color: $pgbg;
 3790:   text-align: center;
 3791: }
 3792: table.LC_parm_overview_restrictions th {
 3793:   background: $tabbg;
 3794:   border-width: 1px 4px 1px 4px;
 3795:   border-style: solid;
 3796:   border-color: $pgbg;
 3797: }
 3798: table#LC_helpmenu {
 3799:   border: 0px;
 3800:   height: 55px;
 3801:   border-spacing: 0px;
 3802: }
 3803: 
 3804: table#LC_helpmenu fieldset legend {
 3805:   font-size: larger;
 3806:   font-weight: bold;
 3807: }
 3808: table#LC_helpmenu_links {
 3809:   width: 100%;
 3810:   border: 1px solid black;
 3811:   background: $pgbg;
 3812:   padding: 0px;
 3813:   border-spacing: 1px;
 3814: }
 3815: table#LC_helpmenu_links tr td {
 3816:   padding: 1px;
 3817:   background: $tabbg;
 3818:   text-align: center;
 3819:   font-weight: bold;
 3820: }
 3821: 
 3822: table#LC_helpmenu_links a:link, table#LC_helpmenu_links a:visited,
 3823: table#LC_helpmenu_links a:active {
 3824:   text-decoration: none;
 3825:   color: $font;
 3826: }
 3827: table#LC_helpmenu_links a:hover {
 3828:   text-decoration: underline;
 3829:   color: $vlink;
 3830: }
 3831: 
 3832: .LC_chrt_popup_exists {
 3833:   border: 1px solid #339933;
 3834:   margin: -1px;
 3835: }
 3836: .LC_chrt_popup_up {
 3837:   border: 1px solid yellow;
 3838:   margin: -1px;
 3839: }
 3840: .LC_chrt_popup {
 3841:   border: 1px solid #8888FF;
 3842:   background: #CCCCFF;
 3843: }
 3844: 
 3845: table.LC_pick_box {
 3846:   width: 100%;
 3847:   border-collapse: separate;
 3848:   background: white;
 3849:   border: 1px solid black;
 3850:   border-spacing: 1px;
 3851: }
 3852: table.LC_pick_box td.LC_pick_box_title {
 3853:   background: $tabbg;
 3854:   font-weight: bold;
 3855:   text-align: right;
 3856:   width: 184px;
 3857:   padding: 8px;
 3858: }
 3859: table.LC_pick_box td.LC_pick_box_separator {
 3860:   padding: 0px;
 3861:   height: 1px;
 3862:   background: black;
 3863: }
 3864: table.LC_pick_box td.LC_pick_box_submit {
 3865:   text-align: right;
 3866: }
 3867: 
 3868: table.LC_group_priv_box {
 3869:   background: white;
 3870:   border: 1px solid black;
 3871:   border-spacing: 1px;
 3872: }
 3873: table.LC_group_priv_box td.LC_pick_box_title {
 3874:   background: $tabbg;
 3875:   font-weight: bold;
 3876:   text-align: right;
 3877:   width: 184px;
 3878: }
 3879: table.LC_group_priv_box td.LC_groups_fixed {
 3880:   background: $data_table_light;
 3881:   text-align: center;
 3882: }
 3883: table.LC_group_priv_box td.LC_groups_optional {
 3884:   background: $data_table_dark;
 3885:   text-align: center;
 3886: }
 3887: table.LC_group_priv_box td.LC_groups_functionality {
 3888:   background: $data_table_darker;
 3889:   text-align: center;
 3890:   font-weight: bold;
 3891: }
 3892: table.LC_group_priv td {
 3893:   text-align: left;
 3894:   padding: 0px;
 3895: }
 3896: 
 3897: table.LC_notify_front_page {
 3898:   background: white;
 3899:   border: 1px solid black;
 3900:   padding: 8px;
 3901: }
 3902: table.LC_notify_front_page td {
 3903:   padding: 8px;
 3904: }
 3905: .LC_navbuttons {
 3906:   margin: 2ex 0ex 2ex 0ex;
 3907: }
 3908: .LC_topic_bar {
 3909:   font-family: $sans;
 3910:   font-weight: bold;
 3911:   width: 100%;
 3912:   background: $tabbg;
 3913:   vertical-align: middle;
 3914:   margin: 2ex 0ex 2ex 0ex;
 3915: }
 3916: .LC_topic_bar span {
 3917:   vertical-align: middle;
 3918: }
 3919: .LC_topic_bar img {
 3920:   vertical-align: bottom;
 3921: }
 3922: table.LC_course_group_status {
 3923:   margin: 20px;
 3924: }
 3925: table.LC_status_selector td {
 3926:   vertical-align: top;
 3927:   text-align: center;
 3928:   padding: 4px;
 3929: }
 3930: table.LC_descriptive_input td.LC_description {
 3931:   vertical-align: top;
 3932:   text-align: right;
 3933:   font-weight: bold;
 3934: }
 3935: 
 3936: END
 3937: }
 3938: 
 3939: =pod
 3940: 
 3941: =over 4
 3942: 
 3943: =item * &headtag()
 3944: 
 3945: Returns a uniform footer for LON-CAPA web pages.
 3946: 
 3947: Inputs: $title - optional title for the head
 3948:         $head_extra - optional extra HTML to put inside the <head>
 3949:         $args - optional arguments
 3950:             force_register - if is true call registerurl so the remote is 
 3951:                              informed
 3952:             redirect       -> array ref of
 3953:                                    1- seconds before redirect occurs
 3954:                                    2- url to redirect to
 3955:                                    3- whether the side effect should occur
 3956:                            (side effect of setting 
 3957:                                $env{'internal.head.redirect'} to the url 
 3958:                                redirected too)
 3959:             domain         -> force to color decorate a page for a specific
 3960:                                domain
 3961:             function       -> force usage of a specific rolish color scheme
 3962:             bgcolor        -> override the default page bgcolor
 3963:             no_auto_mt_title
 3964:                            -> prevent &mt()ing the title arg
 3965: 
 3966: =back
 3967: 
 3968: =cut
 3969: 
 3970: sub headtag {
 3971:     my ($title,$head_extra,$args) = @_;
 3972:     
 3973:     my $function = $args->{'function'} || &get_users_function();
 3974:     my $domain   = $args->{'domain'}   || &determinedomain();
 3975:     my $bgcolor  = $args->{'bgcolor'}  || &designparm($function.'.pgbg',$domain);
 3976:     my $url = join(':',$env{'user.name'},$env{'user.domain'},
 3977: 		   $Apache::lonnet::perlvar{'lonVersion'},
 3978: 		   #time(),
 3979: 		   $env{'environment.color.timestamp'},
 3980: 		   $function,$domain,$bgcolor);
 3981: 
 3982:     $url = '/adm/css/'.&escape($url).'.css';
 3983: 
 3984:     my $result =
 3985: 	'<head>'.
 3986: 	&font_settings();
 3987: 
 3988:     if (!$args->{'frameset'}) {
 3989: 	$result .= &Apache::lonhtmlcommon::htmlareaheaders();
 3990:     }
 3991:     if ($args->{'force_register'}) {
 3992: 	$result .= &Apache::lonmenu::registerurl(1);
 3993:     }
 3994:     if (!$args->{'no_nav_bar'} 
 3995: 	&& !$args->{'only_body'}
 3996: 	&& !$args->{'frameset'}) {
 3997: 	$result .= &help_menu_js();
 3998:     }
 3999: 
 4000:     if (ref($args->{'redirect'})) {
 4001: 	my ($time,$url,$inhibit_continue) = @{$args->{'redirect'}};
 4002: 	$url = &Apache::lonenc::check_encrypt($url);
 4003: 	if (!$inhibit_continue) {
 4004: 	    $env{'internal.head.redirect'} = $url;
 4005: 	}
 4006: 	$result.=<<ADDMETA
 4007: <meta http-equiv="pragma" content="no-cache" />
 4008: <meta http-equiv="Refresh" content="$time; url=$url" />
 4009: ADDMETA
 4010:     }
 4011:     if (!defined($title)) {
 4012: 	$title = 'The LearningOnline Network with CAPA';
 4013:     }
 4014:     if (!$args->{'no_auto_mt_title'}) { $title = &mt($title); }
 4015:     $result .= '<title> LON-CAPA '.$title.'</title>'
 4016: 	.'<link rel="stylesheet" type="text/css" href="'.$url.'" />'
 4017: 	.$head_extra;
 4018:     return $result;
 4019: }
 4020: 
 4021: =pod
 4022: 
 4023: =over 4
 4024: 
 4025: =item * &font_settings()
 4026: 
 4027: Returns neccessary <meta> to set the proper encoding
 4028: 
 4029: Inputs: none
 4030: 
 4031: =back
 4032: 
 4033: =cut
 4034: 
 4035: sub font_settings {
 4036:     my $headerstring='';
 4037:     if (($env{'browser.os'} eq 'mac') && (!$env{'browser.mathml'})) { 
 4038: 	$headerstring.=
 4039: 	    '<meta Content-Type="text/html; charset=x-mac-roman" />';
 4040:     } elsif (!$env{'browser.mathml'} && $env{'browser.unicode'}) {
 4041: 	$headerstring.=
 4042: 	    '<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />';
 4043:     }
 4044:     return $headerstring;
 4045: }
 4046: 
 4047: =pod
 4048: 
 4049: =over 4
 4050: 
 4051: =item * &xml_begin()
 4052: 
 4053: Returns the needed doctype and <html>
 4054: 
 4055: Inputs: none
 4056: 
 4057: =back
 4058: 
 4059: =cut
 4060: 
 4061: sub xml_begin {
 4062:     my $output='';
 4063: 
 4064:     &Apache::lonhtmlcommon::init_htmlareafields();
 4065: 
 4066:     if ($env{'browser.mathml'}) {
 4067: 	$output='<?xml version="1.0"?>'
 4068:             #.'<?xml-stylesheet type="text/css" href="/adm/MathML/mathml.css"?>'."\n"
 4069: #            .'<!DOCTYPE html SYSTEM "/adm/MathML/mathml.dtd" '
 4070:             
 4071: #	    .'<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd" [<!ENTITY mathns "http://www.w3.org/1998/Math/MathML">] >'
 4072: 	    .'<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1 plus MathML 2.0 plus SVG 1.1//EN" "http://www.w3.org/2002/04/xhtml-math-svg/xhtml-math-svg.dtd">'
 4073:             .'<html xmlns:math="http://www.w3.org/1998/Math/MathML" ' 
 4074: 	    .'xmlns="http://www.w3.org/1999/xhtml">';
 4075:     } else {
 4076: 	$output='<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html>';
 4077:     }
 4078:     return $output;
 4079: }
 4080: 
 4081: =pod
 4082: 
 4083: =over 4
 4084: 
 4085: =item * &endheadtag()
 4086: 
 4087: Returns a uniform </head> for LON-CAPA web pages.
 4088: 
 4089: Inputs: none
 4090: 
 4091: =back
 4092: 
 4093: =cut
 4094: 
 4095: sub endheadtag {
 4096:     return '</head>';
 4097: }
 4098: 
 4099: =pod
 4100: 
 4101: =over 4
 4102: 
 4103: =item * &head()
 4104: 
 4105: Returns a uniform complete <head>..</head> section for LON-CAPA web pages.
 4106: 
 4107: Inputs: $title - optional title for the page
 4108:         $head_extra - optional extra HTML to put inside the <head>
 4109: 
 4110: =back
 4111: 
 4112: =cut
 4113: 
 4114: sub head {
 4115:     my ($title,$head_extra,$args) = @_;
 4116:     return &headtag($title,$head_extra,$args).&endheadtag();
 4117: }
 4118: 
 4119: =pod
 4120: 
 4121: =over 4
 4122: 
 4123: =item * &start_page()
 4124: 
 4125: Returns a complete <html> .. <body> section for LON-CAPA web pages.
 4126: 
 4127: Inputs: $title - optional title for the page
 4128:         $head_extra - optional extra HTML to incude inside the <head>
 4129:         $args - additional optional args supported are:
 4130:                   only_body      -> is true will set &bodytag() onlybodytag
 4131:                                     arg on
 4132:                   no_nav_bar     -> is true will set &bodytag() notopbar arg on
 4133:                   add_entries    -> additional attributes to add to the  <body>
 4134:                   domain         -> force to color decorate a page for a 
 4135:                                     specific domain
 4136:                   function       -> force usage of a specific rolish color
 4137:                                     scheme
 4138:                   redirect       -> see &headtag()
 4139:                   bgcolor        -> override the default page bg color
 4140:                   js_ready       -> return a string ready for being used in 
 4141:                                     a javascript writeln
 4142:                   html_encode    -> return a string ready for being used in 
 4143:                                     a html attribute
 4144:                   force_register -> if is true will turn on the &bodytag()
 4145:                                     $forcereg arg
 4146:                   body_title     -> alternate text to use instead of $title
 4147:                                     in the title box that appears, this text
 4148:                                     is not auto translated like the $title is
 4149:                   frameset       -> if true will start with a <frameset>
 4150:                                     rather than <body>
 4151:                   no_title       -> if true the title bar won't be shown
 4152:                   skip_phases    -> hash ref of 
 4153:                                     head -> skip the <html><head> generation
 4154:                                     body -> skip all <body> generation
 4155: 
 4156:                   no_inline_link -> if true and in remote mode, don't show the 
 4157:                                     'Switch To Inline Menu' link
 4158: 
 4159:                   no_auto_mt_title -> prevent &mt()ing the title arg
 4160: 
 4161: =back
 4162: 
 4163: =cut
 4164: 
 4165: sub start_page {
 4166:     my ($title,$head_extra,$args) = @_;
 4167:     #&Apache::lonnet::logthis("start_page ".join(':',caller(0)));
 4168:     my %head_args;
 4169:     foreach my $arg ('redirect','force_register','domain','function',
 4170: 		     'bgcolor','frameset','no_nav_bar','only_body',
 4171: 		     'no_auto_mt_title') {
 4172: 	if (defined($args->{$arg})) {
 4173: 	    $head_args{$arg} = $args->{$arg};
 4174: 	}
 4175:     }
 4176: 
 4177:     $env{'internal.start_page'}++;
 4178:     my $result;
 4179:     if (! exists($args->{'skip_phases'}{'head'}) ) {
 4180: 	$result.=
 4181: 	    &xml_begin().
 4182: 	    &headtag($title,$head_extra,\%head_args).&endheadtag();
 4183:     }
 4184:     
 4185:     if (! exists($args->{'skip_phases'}{'body'}) ) {
 4186: 	if ($args->{'frameset'}) {
 4187: 	    my $attr_string = &make_attr_string($args->{'force_register'},
 4188: 						$args->{'add_entries'});
 4189: 	    $result .= "\n<frameset $attr_string>\n";
 4190: 	} else {
 4191: 	    $result .=
 4192: 		&bodytag($title, 
 4193: 			 $args->{'function'},       $args->{'add_entries'},
 4194: 			 $args->{'only_body'},      $args->{'domain'},
 4195: 			 $args->{'force_register'}, $args->{'body_title'},
 4196: 			 $args->{'no_nav_bar'},     $args->{'bgcolor'},
 4197: 			 $args->{'no_title'},       $args->{'no_inline_link'},
 4198: 			 $args);
 4199: 	}
 4200:     }
 4201: 
 4202:     if ($args->{'js_ready'}) {
 4203: 	$result = &js_ready($result);
 4204:     }
 4205:     if ($args->{'html_encode'}) {
 4206: 	$result = &html_encode($result);
 4207:     }
 4208:     return $result;
 4209: }
 4210: 
 4211: 
 4212: =pod
 4213: 
 4214: =over 4
 4215: 
 4216: =item * &head()
 4217: 
 4218: Returns a complete </body></html> section for LON-CAPA web pages.
 4219: 
 4220: Inputs:         $args - additional optional args supported are:
 4221:                  js_ready     -> return a string ready for being used in 
 4222:                                  a javascript writeln
 4223:                  html_encode  -> return a string ready for being used in 
 4224:                                  a html attribute
 4225:                  frameset     -> if true will start with a <frameset>
 4226:                                  rather than <body>
 4227: 
 4228: =cut
 4229: 
 4230: sub end_page {
 4231:     my ($args) = @_;
 4232:     $env{'internal.end_page'}++;
 4233:     my $result;
 4234:     if ($args->{'discussion'}) {
 4235: 	my ($target,$parser);
 4236: 	if (ref($args->{'discussion'})) {
 4237: 	    ($target,$parser) =($args->{'discussion'}{'target'},
 4238: 				$args->{'discussion'}{'parser'});
 4239: 	}
 4240: 	$result .= &Apache::lonxml::xmlend($target,$parser);
 4241:     }
 4242: 
 4243:     if ($args->{'frameset'}) {
 4244: 	$result .= '</frameset>';
 4245:     } else {
 4246: 	$result .= &endbodytag();
 4247:     }
 4248:     $result .= "\n</html>";
 4249: 
 4250:     if ($args->{'js_ready'}) {
 4251: 	$result = &js_ready($result);
 4252:     }
 4253: 
 4254:     if ($args->{'html_encode'}) {
 4255: 	$result = &html_encode($result);
 4256:     }
 4257: 
 4258:     return $result;
 4259: }
 4260: 
 4261: sub html_encode {
 4262:     my ($result) = @_;
 4263: 
 4264:     $result = &HTML::Entities::encode($result,'<>&"');
 4265:     
 4266:     return $result;
 4267: }
 4268: sub js_ready {
 4269:     my ($result) = @_;
 4270: 
 4271:     $result =~ s/[\n\r]/ /xmsg;
 4272:     $result =~ s/\\/\\\\/xmsg;
 4273:     $result =~ s/'/\\'/xmsg;
 4274:     $result =~ s{</}{<\\/}xmsg;
 4275:     
 4276:     return $result;
 4277: }
 4278: 
 4279: sub validate_page {
 4280:     if (  exists($env{'internal.start_page'})
 4281: 	  &&     $env{'internal.start_page'} > 1) {
 4282: 	&Apache::lonnet::logthis('start_page called multiple times '.
 4283: 				 $env{'internal.start_page'}.' '.
 4284: 				 $ENV{'request.filename'});
 4285:     }
 4286:     if (  exists($env{'internal.end_page'})
 4287: 	  &&     $env{'internal.end_page'} > 1) {
 4288: 	&Apache::lonnet::logthis('end_page called multiple times '.
 4289: 				 $env{'internal.end_page'}.' '.
 4290: 				 $env{'request.filename'});
 4291:     }
 4292:     if (     exists($env{'internal.start_page'})
 4293: 	&& ! exists($env{'internal.end_page'})) {
 4294: 	&Apache::lonnet::logthis('start_page called without end_page '.
 4295: 				 $env{'request.filename'});
 4296:     }
 4297:     if (   ! exists($env{'internal.start_page'})
 4298: 	&&   exists($env{'internal.end_page'})) {
 4299: 	&Apache::lonnet::logthis('end_page called without start_page'.
 4300: 				 $env{'request.filename'});
 4301:     }
 4302: }
 4303: 
 4304: sub simple_error_page {
 4305:     my ($r,$title,$msg) = @_;
 4306:     my $page =
 4307: 	&Apache::loncommon::start_page($title).
 4308: 	&mt($msg).
 4309: 	&Apache::loncommon::end_page();
 4310:     if (ref($r)) {
 4311: 	$r->print($page);
 4312: 	return;
 4313:     }
 4314:     return $page;
 4315: }
 4316: 
 4317: {
 4318:     my $row_count;
 4319:     sub start_data_table {
 4320: 	my ($add_class) = @_;
 4321: 	my $css_class = (join(' ','LC_data_table',$add_class));
 4322: 	undef($row_count);
 4323: 	return '<table class="'.$css_class.'">'."\n";
 4324:     }
 4325: 
 4326:     sub end_data_table {
 4327: 	undef($row_count);
 4328: 	return '</table>'."\n";;
 4329:     }
 4330: 
 4331:     sub start_data_table_row {
 4332: 	my ($add_class) = @_;
 4333: 	$row_count++;
 4334: 	my $css_class = ($row_count % 2)?'':'LC_even_row';
 4335: 	$css_class = (join(' ',$css_class,$add_class));
 4336: 	return  '<tr class="'.$css_class.'">'."\n";;
 4337:     }
 4338:     
 4339:     sub continue_data_table_row {
 4340: 	my ($add_class) = @_;
 4341: 	my $css_class = ($row_count % 2)?'':'LC_even_row';
 4342: 	$css_class = (join(' ',$css_class,$add_class));
 4343: 	return  '<tr class="'.$css_class.'">'."\n";;
 4344:     }
 4345: 
 4346:     sub end_data_table_row {
 4347: 	return '</tr>'."\n";;
 4348:     }
 4349: 
 4350:     sub start_data_table_empty_row {
 4351: 	$row_count++;
 4352: 	return  '<tr class="LC_empty_row" >'."\n";;
 4353:     }
 4354: 
 4355:     sub end_data_table_empty_row {
 4356: 	return '</tr>'."\n";;
 4357:     }
 4358: 
 4359:     sub start_data_table_header_row {
 4360: 	return  '<tr class="LC_header_row">'."\n";;
 4361:     }
 4362: 
 4363:     sub end_data_table_header_row {
 4364: 	return '</tr>'."\n";;
 4365:     }
 4366: }
 4367: 
 4368: ###############################################
 4369: 
 4370: =pod
 4371: 
 4372: =item * &get_users_function()
 4373: 
 4374: Used by &bodytag to determine the current users primary role.
 4375: Returns either 'student','coordinator','admin', or 'author'.
 4376: 
 4377: =cut
 4378: 
 4379: ###############################################
 4380: sub get_users_function {
 4381:     my $function = 'student';
 4382:     if ($env{'request.role'}=~/^(cc|in|ta|ep)/) {
 4383:         $function='coordinator';
 4384:     }
 4385:     if ($env{'request.role'}=~/^(su|dc|ad|li)/) {
 4386:         $function='admin';
 4387:     }
 4388:     if (($env{'request.role'}=~/^(au|ca)/) ||
 4389:         ($ENV{'REQUEST_URI'}=~/^(\/priv|\~)/)) {
 4390:         $function='author';
 4391:     }
 4392:     return $function;
 4393: }
 4394: 
 4395: ###############################################
 4396: 
 4397: =pod
 4398: 
 4399: =item * &check_user_status
 4400: 
 4401: Determines current status of supplied role for a
 4402: specific user. Roles can be active, previous or future.
 4403: 
 4404: Inputs: 
 4405: user's domain, user's username, course's domain,
 4406: course's number, optional section ID.
 4407: 
 4408: Outputs:
 4409: role status: active, previous or future. 
 4410: 
 4411: =cut
 4412: 
 4413: sub check_user_status {
 4414:     my ($udom,$uname,$cdom,$crs,$role,$sec) = @_;
 4415:     my %userinfo = &Apache::lonnet::dump('roles',$udom,$uname);
 4416:     my @uroles = keys %userinfo;
 4417:     my $srchstr;
 4418:     my $active_chk = 'none';
 4419:     my $now = time;
 4420:     if (@uroles > 0) {
 4421:         if (($role eq 'cc') || ($sec eq '') || (!defined($sec))) {
 4422:             $srchstr = '/'.$cdom.'/'.$crs.'_'.$role;
 4423:         } else {
 4424:             $srchstr = '/'.$cdom.'/'.$crs.'/'.$sec.'_'.$role;
 4425:         }
 4426:         if (grep/^\Q$srchstr\E$/,@uroles) {
 4427:             my $role_end = 0;
 4428:             my $role_start = 0;
 4429:             $active_chk = 'active';
 4430:             if ($userinfo{$srchstr} =~ m/^\Q$role\E_(\d+)/) {
 4431:                 $role_end = $1;
 4432:                 if ($userinfo{$srchstr} =~ m/^\Q$role\E_\Q$role_end\E_(\d+)$/) {
 4433:                     $role_start = $1;
 4434:                 }
 4435:             }
 4436:             if ($role_start > 0) {
 4437:                 if ($now < $role_start) {
 4438:                     $active_chk = 'future';
 4439:                 }
 4440:             }
 4441:             if ($role_end > 0) {
 4442:                 if ($now > $role_end) {
 4443:                     $active_chk = 'previous';
 4444:                 }
 4445:             }
 4446:         }
 4447:     }
 4448:     return $active_chk;
 4449: }
 4450: 
 4451: ###############################################
 4452: 
 4453: =pod
 4454: 
 4455: =item * &get_sections()
 4456: 
 4457: Determines all the sections for a course including
 4458: sections with students and sections containing other roles.
 4459: Incoming parameters: 
 4460: 
 4461: 1. domain
 4462: 2. course number 
 4463: 3. reference to array containing roles for which sections should 
 4464: be gathered (optional).
 4465: 4. reference to array containing status types for which sections 
 4466: should be gathered (optional).
 4467: 
 4468: If the third argument is undefined, sections are gathered for any role. 
 4469: If the fourth argument is undefined, sections are gathered for any status.
 4470: Permissible values are 'active' or 'future' or 'previous'.
 4471:  
 4472: Returns section hash (keys are section IDs, values are
 4473: number of users in each section), subject to the
 4474: optional roles filter, optional status filter 
 4475: 
 4476: =cut
 4477: 
 4478: ###############################################
 4479: sub get_sections {
 4480:     my ($cdom,$cnum,$possible_roles,$possible_status) = @_;
 4481:     if (!defined($cdom) || !defined($cnum)) {
 4482:         my $cid =  $env{'request.course.id'};
 4483: 
 4484: 	return if (!defined($cid));
 4485: 
 4486:         $cdom = $env{'course.'.$cid.'.domain'};
 4487:         $cnum = $env{'course.'.$cid.'.num'};
 4488:     }
 4489: 
 4490:     my %sectioncount;
 4491:     my $now = time;
 4492: 
 4493:     if (!defined($possible_roles) || (grep(/^st$/,@$possible_roles))) {
 4494: 	my ($classlist) = &Apache::loncoursedata::get_classlist($cdom,$cnum);
 4495: 	my $sec_index = &Apache::loncoursedata::CL_SECTION();
 4496: 	my $status_index = &Apache::loncoursedata::CL_STATUS();
 4497:         my $start_index = &Apache::loncoursedata::CL_START();
 4498:         my $end_index = &Apache::loncoursedata::CL_END();
 4499:         my $status;
 4500: 	while (my ($student,$data) = each(%$classlist)) {
 4501: 	    my ($section,$stu_status,$start,$end) = ($data->[$sec_index],
 4502: 				                     $data->[$status_index],
 4503:                                                      $data->[$start_index],
 4504:                                                      $data->[$end_index]);
 4505:             if ($stu_status eq 'Active') {
 4506:                 $status = 'active';
 4507:             } elsif ($end < $now) {
 4508:                 $status = 'previous';
 4509:             } elsif ($start > $now) {
 4510:                 $status = 'future';
 4511:             } 
 4512: 	    if ($section ne '-1' && $section !~ /^\s*$/) {
 4513:                 if ((!defined($possible_status)) || (($status ne '') && 
 4514:                     (grep/^\Q$status\E$/,@{$possible_status}))) { 
 4515: 		    $sectioncount{$section}++;
 4516:                 }
 4517: 	    }
 4518: 	}
 4519:     }
 4520:     my %courseroles = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
 4521:     foreach my $user (sort(keys(%courseroles))) {
 4522: 	if ($user !~ /^(\w{2})/) { next; }
 4523: 	my ($role) = ($user =~ /^(\w{2})/);
 4524: 	if ($possible_roles && !(grep(/^$role$/,@$possible_roles))) { next; }
 4525: 	my ($section,$status);
 4526: 	if ($role eq 'cr' &&
 4527: 	    $user =~ m-^$role/[^/]*/[^/]*/[^/]*:[^:]*:[^:]*:(\w+)-) {
 4528: 	    $section=$1;
 4529: 	}
 4530: 	if ($user =~ /^$role:[^:]*:[^:]*:(\w+)/) { $section=$1; }
 4531: 	if (!defined($section) || $section eq '-1') { next; }
 4532:         my ($end,$start) = ($courseroles{$user} =~ /^([^:]*):([^:]*)$/);
 4533:         if ($end == -1 && $start == -1) {
 4534:             next; #deleted role
 4535:         }
 4536:         if (!defined($possible_status)) { 
 4537:             $sectioncount{$section}++;
 4538:         } else {
 4539:             if ((!$end || $end >= $now) && (!$start || $start <= $now)) {
 4540:                 $status = 'active';
 4541:             } elsif ($end < $now) {
 4542:                 $status = 'future';
 4543:             } elsif ($start > $now) {
 4544:                 $status = 'previous';
 4545:             }
 4546:             if (($status ne '') && (grep/^\Q$status\E$/,@{$possible_status})) {
 4547:                 $sectioncount{$section}++;
 4548:             }
 4549:         }
 4550:     }
 4551:     return %sectioncount;
 4552: }
 4553: 
 4554: ###############################################
 4555: 
 4556: =pod
 4557: 
 4558: =item * &get_course_users()
 4559: 
 4560: Retrieves usernames:domains for users in the specified course
 4561: with specific role(s), and access status. 
 4562: 
 4563: Incoming parameters:
 4564: 1. course domain
 4565: 2. course number
 4566: 3. access status: users must have - either active, 
 4567: previous, future, or all.
 4568: 4. reference to array of permissible roles
 4569: 5. reference to array of section restrictions (optional)
 4570: 6. reference to results object (hash of hashes).
 4571: 7. reference to optional userdata hash
 4572: Keys of top level hash are roles.
 4573: Keys of inner hashes are username:domain, with 
 4574: values set to access type.
 4575: Optional userdata hash returns an array with arguments in the 
 4576: same order as loncoursedata::get_classlist() for student data.
 4577: 
 4578: Entries for end, start, section and status are blank because
 4579: of the possibility of multiple values for non-student roles.
 4580: 
 4581: =cut
 4582: 
 4583: ###############################################
 4584: 
 4585: sub get_course_users {
 4586:     my ($cdom,$cnum,$types,$roles,$sections,$users,$userdata) = @_;
 4587:     my %idx = ();
 4588:     my %seclists;
 4589: 
 4590:     $idx{udom} = &Apache::loncoursedata::CL_SDOM();
 4591:     $idx{uname} =  &Apache::loncoursedata::CL_SNAME();
 4592:     $idx{end} = &Apache::loncoursedata::CL_END();
 4593:     $idx{start} = &Apache::loncoursedata::CL_START();
 4594:     $idx{id} = &Apache::loncoursedata::CL_ID();
 4595:     $idx{section} = &Apache::loncoursedata::CL_SECTION();
 4596:     $idx{fullname} = &Apache::loncoursedata::CL_FULLNAME();
 4597:     $idx{status} = &Apache::loncoursedata::CL_STATUS();
 4598: 
 4599:     if (grep(/^st$/,@{$roles})) {
 4600:         my ($classlist,$keylist)=&Apache::loncoursedata::get_classlist($cdom,$cnum);
 4601:         my $now = time;
 4602:         foreach my $student (keys(%{$classlist})) {
 4603:             my $match = 0;
 4604:             my $secmatch = 0;
 4605:             my $section = $$classlist{$student}[$idx{section}];
 4606:             if ($section eq '') {
 4607:                 $section = 'none';
 4608:             }
 4609:             if ((ref($sections) eq 'ARRAY') && (@{$sections} > 0)) {
 4610:                 if (grep(/^all$/,@{$sections})) {
 4611:                     $secmatch = 1;
 4612:                 } elsif ($$classlist{$student}[$idx{section}] eq '') {
 4613:                     if (grep(/^none$/,@{$sections})) {
 4614:                         $secmatch = 1;
 4615:                     }
 4616:                 } else {  
 4617: 		    if (grep(/^\Q$section\E$/,@{$sections})) {
 4618: 		        $secmatch = 1;
 4619:                     }
 4620: 		}
 4621:                 if (!$secmatch) {
 4622:                     next;
 4623:                 }
 4624:             }
 4625:             push(@{$seclists{$student}},$section); 
 4626:             if (defined($$types{'active'})) {
 4627:                 if ($$classlist{$student}[$idx{status}] eq 'Active') {
 4628:                     push(@{$$users{st}{$student}},'active');
 4629:                     $match = 1;
 4630:                 }
 4631:             }
 4632:             if (defined($$types{'previous'})) {
 4633:                 if ($$classlist{$student}[$idx{end}] <= $now) {
 4634:                     push(@{$$users{st}{$student}},'previous');
 4635:                     $match = 1;
 4636:                 }
 4637:             }
 4638:             if (defined($$types{'future'})) {
 4639:                 if (($$classlist{$student}[$idx{start}] > $now) && ($$classlist{$student}[$idx{end}] > $now) || ($$classlist{$student}[$idx{end}] == 0) || ($$classlist{$student}[$idx{end}] eq '')) {
 4640:                     push(@{$$users{st}{$student}},'future');
 4641:                     $match = 1;
 4642:                 }
 4643:             }
 4644:             if ($match && ref($userdata) eq 'HASH') {
 4645:                 $$userdata{$student} = $$classlist{$student};
 4646:             }
 4647:         }
 4648:     }
 4649:     if ((@{$roles} > 1) || ((@{$roles} == 1) && ($$roles[0] ne "st"))) {
 4650:         my %coursepersonnel = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
 4651:         my $now = time;
 4652:         foreach my $person (sort(keys(%coursepersonnel))) {
 4653:             my $match = 0;
 4654:             my $secmatch = 0;
 4655:             my $status;
 4656:             my ($role,$user,$usec) = ($person =~ /^([^:]*):([^:]+:[^:]+):([^:]*)/);
 4657:             $user =~ s/:$//;
 4658:             my ($end,$start) = split(/:/,$coursepersonnel{$person});
 4659:             if ($end == -1 || $start == -1) {
 4660:                 next;
 4661:             }
 4662:             if (($role) && ((grep(/^\Q$role\E$/,@{$roles})) ||
 4663:                 (grep(/^cr$/,@{$roles}) && $role =~ /^cr\//))) {
 4664:                 my ($uname,$udom) = split(/:/,$user);
 4665:                 if ((ref($sections) eq 'ARRAY') && (@{$sections} > 0)) {
 4666:                     if (grep(/^all$/,@{$sections})) {
 4667:                         $secmatch = 1;
 4668:                     } elsif ($usec eq '') {
 4669:                         if (grep(/^none$/,@{$sections})) {
 4670:                             $secmatch = 1;
 4671:                         }
 4672:                     } else {
 4673:                         if (grep(/^\Q$usec\E$/,@{$sections})) {
 4674:                             $secmatch = 1;
 4675:                         }
 4676:                     }
 4677:                     if (!$secmatch) {
 4678:                         next;
 4679:                     }
 4680:                 }
 4681:                 if ($usec eq '') {
 4682:                     $usec = 'none';
 4683:                 }
 4684:                 if ($uname ne '' && $udom ne '') {
 4685:                     if ($end < $now) {
 4686:                         $status = 'previous';
 4687:                     } elsif ($start > $now) {
 4688:                         $status = 'future';
 4689:                     } else {
 4690:                         $status = 'active';
 4691:                     }
 4692:                     foreach my $type (keys(%{$types})) { 
 4693:                         if ($status eq $type) {
 4694:                             if (!grep(/^\Q$type\E$/,@{$$users{$role}{$user}})) {
 4695:                                 push(@{$$users{$role}{$user}},$type);
 4696:                             }
 4697:                             $match = 1;
 4698:                         }
 4699:                     }
 4700:                     if (($match) && (ref($userdata) eq 'HASH')) {
 4701:                         if (!exists($$userdata{$uname.':'.$udom})) {
 4702: 			    &get_user_info($udom,$uname,\%idx,$userdata);
 4703:                         }
 4704:                         if (!grep(/^\Q$usec\E$/,@{$seclists{$uname.':'.$udom}})) {
 4705:                             push(@{$seclists{$uname.':'.$udom}},$usec);
 4706:                         }
 4707:                     }
 4708:                 }
 4709:             }
 4710:         }
 4711:         if (grep(/^ow$/,@{$roles})) {
 4712:             if ((defined($cdom)) && (defined($cnum))) {
 4713:                 my %csettings = &Apache::lonnet::get('environment',['internal.courseowner'],$cdom,$cnum);
 4714:                 if ( defined($csettings{'internal.courseowner'}) ) {
 4715:                     my $owner = $csettings{'internal.courseowner'};
 4716:                     if ($owner !~ /^[^:]+:[^:]+$/) {
 4717:                         $owner = $owner.':'.$cdom;
 4718:                     }
 4719:                     @{$$users{'ow'}{$owner}} = 'any';
 4720:                     if (defined($userdata) && 
 4721: 			!exists($$userdata{$owner.':'.$cdom})) {
 4722: 			&get_user_info($cdom,$owner,\%idx,$userdata);
 4723:                         if (!grep(/^none$/,@{$seclists{$owner.':'.$cdom}})) {
 4724:                             push(@{$seclists{$owner.':'.$cdom}},'none');
 4725:                         }
 4726: 		    }
 4727:                 }
 4728:             }
 4729:         }
 4730:         foreach my $user (keys(%seclists)) {
 4731:             @{$seclists{$user}} = (sort {$a <=> $b} @{$seclists{$user}});
 4732:             $$userdata{$user}[$idx{section}] = join(',',@{$seclists{$user}});
 4733:         }
 4734:     }
 4735:     return;
 4736: }
 4737: 
 4738: sub get_user_info {
 4739:     my ($udom,$uname,$idx,$userdata) = @_;
 4740:     $$userdata{$uname.':'.$udom}[$$idx{fullname}] = 
 4741: 	&plainname($uname,$udom,'lastname');
 4742:     $$userdata{$uname.':'.$udom}[$$idx{uname}] = $uname;
 4743:     $$userdata{$uname.':'.$udom}[$$idx{udom}] = $udom;
 4744:     return;
 4745: }
 4746: 
 4747: ###############################################
 4748: 
 4749: =pod
 4750: 
 4751: =item * &get_user_quota()
 4752: 
 4753: Retrieves quota assigned for storage of portfolio files for a user  
 4754: 
 4755: Incoming parameters:
 4756: 1. user's username
 4757: 2. user's domain
 4758: 
 4759: Returns:
 4760: 1. Disk quota (in Mb) assigned to student. 
 4761: 
 4762: If a value has been stored in the user's environment, 
 4763: it will return that, otherwise it returns the default
 4764: for users in the domain.
 4765: 
 4766: =cut
 4767: 
 4768: ###############################################
 4769: 
 4770: 
 4771: sub get_user_quota {
 4772:     my ($uname,$udom) = @_;
 4773:     my $quota;
 4774:     if (!defined($udom)) {
 4775:         $udom = $env{'user.domain'};
 4776:     }
 4777:     if (!defined($uname)) {
 4778:         $uname = $env{'user.name'};
 4779:     }
 4780:     if (($udom eq '' || $uname eq '') ||
 4781:         ($udom eq 'public') && ($uname eq 'public')) {
 4782:         $quota = 0;
 4783:     } else {
 4784:         if ($udom eq $env{'user.domain'} && $uname eq $env{'user.name'}) {
 4785:             $quota = $env{'environment.portfolioquota'};
 4786:         } else {
 4787:             my %userenv = &Apache::lonnet::dump('environment',$udom,$uname);
 4788:             my ($tmp) = keys(%userenv);
 4789:             if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
 4790:                 $quota = $userenv{'portfolioquota'};
 4791:             } else {
 4792:                 undef(%userenv);
 4793:             }
 4794:         }
 4795:         if ($quota eq '') {
 4796:             $quota = &default_quota($udom);
 4797:         }
 4798:     }
 4799:     return $quota;
 4800: }
 4801: 
 4802: ###############################################
 4803: 
 4804: =pod
 4805: 
 4806: =item * &default_quota()
 4807: 
 4808: Retrieves default quota assigned for storage of user portfolio files
 4809: 
 4810: Incoming parameters:
 4811: 1. domain
 4812: 
 4813: Returns:
 4814: 1. Default disk quota (in Mb) for user portfolios in the domain.
 4815: 
 4816: If a value has been stored in the domain's configuration db,
 4817: it will return that, otherwise it returns 20 (for backwards 
 4818: compatibility with domains which have not set up a configuration
 4819: db file; the original statically defined portfolio quota was 20 Mb). 
 4820: 
 4821: =cut
 4822: 
 4823: ###############################################
 4824: 
 4825: 
 4826: sub default_quota {
 4827:     my ($udom) = @_;
 4828:     my %defaults = &Apache::lonnet::get_dom('configuration',
 4829:                                             ['portfolioquota'],$udom);
 4830:     if ($defaults{'portfolioquota'} ne '') {
 4831:         return $defaults{'portfolioquota'};
 4832:     } else {
 4833:         return '20';
 4834:     }
 4835: }
 4836: 
 4837: sub get_secgrprole_info {
 4838:     my ($cdom,$cnum,$needroles,$type)  = @_;
 4839:     my %sections_count = &get_sections($cdom,$cnum);
 4840:     my @sections =  (sort {$a <=> $b} keys(%sections_count));
 4841:     my %curr_groups = &Apache::longroup::coursegroups($cdom,$cnum);
 4842:     my @groups = sort(keys(%curr_groups));
 4843:     my $allroles = [];
 4844:     my $rolehash;
 4845:     my $accesshash = {
 4846:                      active => 'Currently has access',
 4847:                      future => 'Will have future access',
 4848:                      previous => 'Previously had access',
 4849:                   };
 4850:     if ($needroles) {
 4851:         $rolehash = {'all' => 'all'};
 4852:         my %user_roles = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
 4853: 	if (&Apache::lonnet::error(%user_roles)) {
 4854: 	    undef(%user_roles);
 4855: 	}
 4856:         foreach my $item (keys(%user_roles)) {
 4857:             my ($role)=split(/\:/,$item,2);
 4858:             if ($role eq 'cr') { next; }
 4859:             if ($role =~ /^cr/) {
 4860:                 $$rolehash{$role} = (split('/',$role))[3];
 4861:             } else {
 4862:                 $$rolehash{$role} = &Apache::lonnet::plaintext($role,$type);
 4863:             }
 4864:         }
 4865:         foreach my $key (sort(keys(%{$rolehash}))) {
 4866:             push(@{$allroles},$key);
 4867:         }
 4868:         push (@{$allroles},'st');
 4869:         $$rolehash{'st'} = &Apache::lonnet::plaintext('st',$type);
 4870:     }
 4871:     return (\@sections,\@groups,$allroles,$rolehash,$accesshash);
 4872: }
 4873: 
 4874: =pod
 4875: 
 4876: =item * get_unprocessed_cgi($query,$possible_names)
 4877: 
 4878: Modify the %env hash to contain unprocessed CGI form parameters held in
 4879: $query.  The parameters listed in $possible_names (an array reference),
 4880: will be set in $env{'form.name'} if they do not already exist.
 4881: 
 4882: Typically called with $ENV{'QUERY_STRING'} as the first parameter.  
 4883: $possible_names is an ref to an array of form element names.  As an example:
 4884: get_unprocessed_cgi($ENV{'QUERY_STRING'},['uname','udom']);
 4885: will result in $env{'form.uname'} and $env{'form.udom'} being set.
 4886: 
 4887: =cut
 4888: 
 4889: sub get_unprocessed_cgi {
 4890:   my ($query,$possible_names)= @_;
 4891:   # $Apache::lonxml::debug=1;
 4892:   foreach my $pair (split(/&/,$query)) {
 4893:     my ($name, $value) = split(/=/,$pair);
 4894:     $name = &unescape($name);
 4895:     if (!defined($possible_names) || (grep {$_ eq $name} @$possible_names)) {
 4896:       $value =~ tr/+/ /;
 4897:       $value =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C",hex($1))/eg;
 4898:       unless (defined($env{'form.'.$name})) { &add_to_env('form.'.$name,$value) };
 4899:     }
 4900:   }
 4901: }
 4902: 
 4903: =pod
 4904: 
 4905: =item * cacheheader() 
 4906: 
 4907: returns cache-controlling header code
 4908: 
 4909: =cut
 4910: 
 4911: sub cacheheader {
 4912:     unless ($env{'request.method'} eq 'GET') { return ''; }
 4913:     my $date=strftime("%a, %d %b %Y %H:%M:%S GMT",gmtime);
 4914:     my $output .='<meta HTTP-EQUIV="Expires" CONTENT="'.$date.'" />
 4915:                 <meta HTTP-EQUIV="Cache-control" CONTENT="no-cache" />
 4916:                 <meta HTTP-EQUIV="Pragma" CONTENT="no-cache" />';
 4917:     return $output;
 4918: }
 4919: 
 4920: =pod
 4921: 
 4922: =item * no_cache($r) 
 4923: 
 4924: specifies header code to not have cache
 4925: 
 4926: =cut
 4927: 
 4928: sub no_cache {
 4929:     my ($r) = @_;
 4930:     if ($ENV{'REQUEST_METHOD'} ne 'GET' &&
 4931: 	$env{'request.method'} ne 'GET') { return ''; }
 4932:     my $date=strftime("%a, %d %b %Y %H:%M:%S GMT",gmtime(time));
 4933:     $r->no_cache(1);
 4934:     $r->header_out("Expires" => $date);
 4935:     $r->header_out("Pragma" => "no-cache");
 4936: }
 4937: 
 4938: sub content_type {
 4939:     my ($r,$type,$charset) = @_;
 4940:     if ($r) {
 4941: 	#  Note that printout.pl calls this with undef for $r.
 4942: 	&no_cache($r);
 4943:     }
 4944:     if ($env{'browser.mathml'} && $type eq 'text/html') { $type='text/xml'; }
 4945:     unless ($charset) {
 4946: 	$charset=&Apache::lonlocal::current_encoding;
 4947:     }
 4948:     if ($charset) { $type.='; charset='.$charset; }
 4949:     if ($r) {
 4950: 	$r->content_type($type);
 4951:     } else {
 4952: 	print("Content-type: $type\n\n");
 4953:     }
 4954: }
 4955: 
 4956: =pod
 4957: 
 4958: =item * add_to_env($name,$value) 
 4959: 
 4960: adds $name to the %env hash with value
 4961: $value, if $name already exists, the entry is converted to an array
 4962: reference and $value is added to the array.
 4963: 
 4964: =cut
 4965: 
 4966: sub add_to_env {
 4967:   my ($name,$value)=@_;
 4968:   if (defined($env{$name})) {
 4969:     if (ref($env{$name})) {
 4970:       #already have multiple values
 4971:       push(@{ $env{$name} },$value);
 4972:     } else {
 4973:       #first time seeing multiple values, convert hash entry to an arrayref
 4974:       my $first=$env{$name};
 4975:       undef($env{$name});
 4976:       push(@{ $env{$name} },$first,$value);
 4977:     }
 4978:   } else {
 4979:     $env{$name}=$value;
 4980:   }
 4981: }
 4982: 
 4983: =pod
 4984: 
 4985: =item * get_env_multiple($name) 
 4986: 
 4987: gets $name from the %env hash, it seemlessly handles the cases where multiple
 4988: values may be defined and end up as an array ref.
 4989: 
 4990: returns an array of values
 4991: 
 4992: =cut
 4993: 
 4994: sub get_env_multiple {
 4995:     my ($name) = @_;
 4996:     my @values;
 4997:     if (defined($env{$name})) {
 4998:         # exists is it an array
 4999:         if (ref($env{$name})) {
 5000:             @values=@{ $env{$name} };
 5001:         } else {
 5002:             $values[0]=$env{$name};
 5003:         }
 5004:     }
 5005:     return(@values);
 5006: }
 5007: 
 5008: 
 5009: =pod
 5010: 
 5011: =back
 5012: 
 5013: =head1 CSV Upload/Handling functions
 5014: 
 5015: =over 4
 5016: 
 5017: =item * upfile_store($r)
 5018: 
 5019: Store uploaded file, $r should be the HTTP Request object,
 5020: needs $env{'form.upfile'}
 5021: returns $datatoken to be put into hidden field
 5022: 
 5023: =cut
 5024: 
 5025: sub upfile_store {
 5026:     my $r=shift;
 5027:     $env{'form.upfile'}=~s/\r/\n/gs;
 5028:     $env{'form.upfile'}=~s/\f/\n/gs;
 5029:     $env{'form.upfile'}=~s/\n+/\n/gs;
 5030:     $env{'form.upfile'}=~s/\n+$//gs;
 5031: 
 5032:     my $datatoken=$env{'user.name'}.'_'.$env{'user.domain'}.
 5033: 	'_enroll_'.$env{'request.course.id'}.'_'.time.'_'.$$;
 5034:     {
 5035:         my $datafile = $r->dir_config('lonDaemons').
 5036:                            '/tmp/'.$datatoken.'.tmp';
 5037:         if ( open(my $fh,">$datafile") ) {
 5038:             print $fh $env{'form.upfile'};
 5039:             close($fh);
 5040:         }
 5041:     }
 5042:     return $datatoken;
 5043: }
 5044: 
 5045: =pod
 5046: 
 5047: =item * load_tmp_file($r)
 5048: 
 5049: Load uploaded file from tmp, $r should be the HTTP Request object,
 5050: needs $env{'form.datatoken'},
 5051: sets $env{'form.upfile'} to the contents of the file
 5052: 
 5053: =cut
 5054: 
 5055: sub load_tmp_file {
 5056:     my $r=shift;
 5057:     my @studentdata=();
 5058:     {
 5059:         my $studentfile = $r->dir_config('lonDaemons').
 5060:                               '/tmp/'.$env{'form.datatoken'}.'.tmp';
 5061:         if ( open(my $fh,"<$studentfile") ) {
 5062:             @studentdata=<$fh>;
 5063:             close($fh);
 5064:         }
 5065:     }
 5066:     $env{'form.upfile'}=join('',@studentdata);
 5067: }
 5068: 
 5069: =pod
 5070: 
 5071: =item * upfile_record_sep()
 5072: 
 5073: Separate uploaded file into records
 5074: returns array of records,
 5075: needs $env{'form.upfile'} and $env{'form.upfiletype'}
 5076: 
 5077: =cut
 5078: 
 5079: sub upfile_record_sep {
 5080:     if ($env{'form.upfiletype'} eq 'xml') {
 5081:     } else {
 5082: 	my @records;
 5083: 	foreach my $line (split(/\n/,$env{'form.upfile'})) {
 5084: 	    if ($line=~/^\s*$/) { next; }
 5085: 	    push(@records,$line);
 5086: 	}
 5087: 	return @records;
 5088:     }
 5089: }
 5090: 
 5091: =pod
 5092: 
 5093: =item * record_sep($record)
 5094: 
 5095: Separate a record into fields $record should be an item from the upfile_record_sep(), needs $env{'form.upfiletype'}
 5096: 
 5097: =cut
 5098: 
 5099: sub takeleft {
 5100:     my $index=shift;
 5101:     return substr('0000'.$index,-4,4);
 5102: }
 5103: 
 5104: sub record_sep {
 5105:     my $record=shift;
 5106:     my %components=();
 5107:     if ($env{'form.upfiletype'} eq 'xml') {
 5108:     } elsif ($env{'form.upfiletype'} eq 'space') {
 5109:         my $i=0;
 5110:         foreach my $field (split(/\s+/,$record)) {
 5111:             $field=~s/^(\"|\')//;
 5112:             $field=~s/(\"|\')$//;
 5113:             $components{&takeleft($i)}=$field;
 5114:             $i++;
 5115:         }
 5116:     } elsif ($env{'form.upfiletype'} eq 'tab') {
 5117:         my $i=0;
 5118:         foreach my $field (split(/\t/,$record)) {
 5119:             $field=~s/^(\"|\')//;
 5120:             $field=~s/(\"|\')$//;
 5121:             $components{&takeleft($i)}=$field;
 5122:             $i++;
 5123:         }
 5124:     } else {
 5125:         my @allfields=split(/\,/,$record);
 5126:         my $i=0;
 5127:         my $j;
 5128:         for ($j=0;$j<=$#allfields;$j++) {
 5129:             my $field=$allfields[$j];
 5130:             if ($field=~/^\s*(\"|\')/) {
 5131: 		my $delimiter=$1;
 5132:                 while (($field!~/$delimiter$/) && ($j<$#allfields)) {
 5133: 		    $j++;
 5134: 		    $field.=','.$allfields[$j];
 5135: 		}
 5136:                 $field=~s/^\s*$delimiter//;
 5137:                 $field=~s/$delimiter\s*$//;
 5138:             }
 5139:             $components{&takeleft($i)}=$field;
 5140: 	    $i++;
 5141:         }
 5142:     }
 5143:     return %components;
 5144: }
 5145: 
 5146: ######################################################
 5147: ######################################################
 5148: 
 5149: =pod
 5150: 
 5151: =item * upfile_select_html()
 5152: 
 5153: Return HTML code to select a file from the users machine and specify 
 5154: the file type.
 5155: 
 5156: =cut
 5157: 
 5158: ######################################################
 5159: ######################################################
 5160: sub upfile_select_html {
 5161:     my %Types = (
 5162:                  csv   => &mt('CSV (comma separated values, spreadsheet)'),
 5163:                  space => &mt('Space separated'),
 5164:                  tab   => &mt('Tabulator separated'),
 5165: #                 xml   => &mt('HTML/XML'),
 5166:                  );
 5167:     my $Str = '<input type="file" name="upfile" size="50" />'.
 5168:         '<br />Type: <select name="upfiletype">';
 5169:     foreach my $type (sort(keys(%Types))) {
 5170:         $Str .= '<option value="'.$type.'" >'.$Types{$type}."</option>\n";
 5171:     }
 5172:     $Str .= "</select>\n";
 5173:     return $Str;
 5174: }
 5175: 
 5176: sub get_samples {
 5177:     my ($records,$toget) = @_;
 5178:     my @samples=({});
 5179:     my $got=0;
 5180:     foreach my $rec (@$records) {
 5181: 	my %temp = &record_sep($rec);
 5182: 	if (! grep(/\S/, values(%temp))) { next; }
 5183: 	if (%temp) {
 5184: 	    $samples[$got]=\%temp;
 5185: 	    $got++;
 5186: 	    if ($got == $toget) { last; }
 5187: 	}
 5188:     }
 5189:     return \@samples;
 5190: }
 5191: 
 5192: ######################################################
 5193: ######################################################
 5194: 
 5195: =pod
 5196: 
 5197: =item * csv_print_samples($r,$records)
 5198: 
 5199: Prints a table of sample values from each column uploaded $r is an
 5200: Apache Request ref, $records is an arrayref from
 5201: &Apache::loncommon::upfile_record_sep
 5202: 
 5203: =cut
 5204: 
 5205: ######################################################
 5206: ######################################################
 5207: sub csv_print_samples {
 5208:     my ($r,$records) = @_;
 5209:     my $samples = &get_samples($records,3);
 5210: 
 5211:     $r->print(&mt('Samples').'<br /><table border="2"><tr>');
 5212:     foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) { 
 5213:         $r->print('<th>'.&mt('Column&nbsp;[_1]',($sample+1)).'</th>'); }
 5214:     $r->print('</tr>');
 5215:     foreach my $hash (@$samples) {
 5216: 	$r->print('<tr>');
 5217: 	foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) {
 5218: 	    $r->print('<td>');
 5219: 	    if (defined($$hash{$sample})) { $r->print($$hash{$sample}); }
 5220: 	    $r->print('</td>');
 5221: 	}
 5222: 	$r->print('</tr>');
 5223:     }
 5224:     $r->print('</tr></table><br />'."\n");
 5225: }
 5226: 
 5227: ######################################################
 5228: ######################################################
 5229: 
 5230: =pod
 5231: 
 5232: =item * csv_print_select_table($r,$records,$d)
 5233: 
 5234: Prints a table to create associations between values and table columns.
 5235: 
 5236: $r is an Apache Request ref,
 5237: $records is an arrayref from &Apache::loncommon::upfile_record_sep,
 5238: $d is an array of 2 element arrays (internal name, displayed name,defaultcol)
 5239: 
 5240: =cut
 5241: 
 5242: ######################################################
 5243: ######################################################
 5244: sub csv_print_select_table {
 5245:     my ($r,$records,$d) = @_;
 5246:     my $i=0;
 5247:     my $samples = &get_samples($records,1);
 5248:     $r->print(&mt('Associate columns with student attributes.')."\n".
 5249: 	     '<table border="2"><tr>'.
 5250:               '<th>'.&mt('Attribute').'</th>'.
 5251:               '<th>'.&mt('Column').'</th></tr>'."\n");
 5252:     foreach my $array_ref (@$d) {
 5253: 	my ($value,$display,$defaultcol)=@{ $array_ref };
 5254: 	$r->print('<tr><td>'.$display.'</td>');
 5255: 
 5256: 	$r->print('<td><select name=f'.$i.
 5257: 		  ' onchange="javascript:flip(this.form,'.$i.');">');
 5258: 	$r->print('<option value="none"></option>');
 5259: 	foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) {
 5260: 	    $r->print('<option value="'.$sample.'"'.
 5261:                       ($sample eq $defaultcol ? ' selected="selected" ' : '').
 5262:                       '>Column '.($sample+1).'</option>');
 5263: 	}
 5264: 	$r->print('</select></td></tr>'."\n");
 5265: 	$i++;
 5266:     }
 5267:     $i--;
 5268:     return $i;
 5269: }
 5270: 
 5271: ######################################################
 5272: ######################################################
 5273: 
 5274: =pod
 5275: 
 5276: =item * csv_samples_select_table($r,$records,$d)
 5277: 
 5278: Prints a table of sample values from the upload and can make associate samples to internal names.
 5279: 
 5280: $r is an Apache Request ref,
 5281: $records is an arrayref from &Apache::loncommon::upfile_record_sep,
 5282: $d is an array of 2 element arrays (internal name, displayed name)
 5283: 
 5284: =cut
 5285: 
 5286: ######################################################
 5287: ######################################################
 5288: sub csv_samples_select_table {
 5289:     my ($r,$records,$d) = @_;
 5290:     my $i=0;
 5291:     #
 5292:     my $samples = &get_samples($records,3);
 5293:     $r->print('<table border=2><tr><th>'.
 5294:               &mt('Field').'</th><th>'.&mt('Samples').'</th></tr>');
 5295: 
 5296:     foreach my $key (sort(keys(%{ $samples->[0] }))) {
 5297: 	$r->print('<tr><td><select name="f'.$i.'"'.
 5298: 		  ' onchange="javascript:flip(this.form,'.$i.');">');
 5299: 	foreach my $option (@$d) {
 5300: 	    my ($value,$display,$defaultcol)=@{ $option };
 5301: 	    $r->print('<option value="'.$value.'"'.
 5302:                       ($i eq $defaultcol ? ' selected="selected" ':'').'>'.
 5303:                       $display.'</option>');
 5304: 	}
 5305: 	$r->print('</select></td><td>');
 5306: 	foreach my $line (0..2) {
 5307: 	    if (defined($samples->[$line]{$key})) { 
 5308: 		$r->print($samples->[$line]{$key}."<br />\n"); 
 5309: 	    }
 5310: 	}
 5311: 	$r->print('</td></tr>');
 5312: 	$i++;
 5313:     }
 5314:     $i--;
 5315:     return($i);
 5316: }
 5317: 
 5318: ######################################################
 5319: ######################################################
 5320: 
 5321: =pod
 5322: 
 5323: =item clean_excel_name($name)
 5324: 
 5325: Returns a replacement for $name which does not contain any illegal characters.
 5326: 
 5327: =cut
 5328: 
 5329: ######################################################
 5330: ######################################################
 5331: sub clean_excel_name {
 5332:     my ($name) = @_;
 5333:     $name =~ s/[:\*\?\/\\]//g;
 5334:     if (length($name) > 31) {
 5335:         $name = substr($name,0,31);
 5336:     }
 5337:     return $name;
 5338: }
 5339: 
 5340: =pod
 5341: 
 5342: =item * check_if_partid_hidden($id,$symb,$udom,$uname)
 5343: 
 5344: Returns either 1 or undef
 5345: 
 5346: 1 if the part is to be hidden, undef if it is to be shown
 5347: 
 5348: Arguments are:
 5349: 
 5350: $id the id of the part to be checked
 5351: $symb, optional the symb of the resource to check
 5352: $udom, optional the domain of the user to check for
 5353: $uname, optional the username of the user to check for
 5354: 
 5355: =cut
 5356: 
 5357: sub check_if_partid_hidden {
 5358:     my ($id,$symb,$udom,$uname) = @_;
 5359:     my $hiddenparts=&Apache::lonnet::EXT('resource.0.hiddenparts',
 5360: 					 $symb,$udom,$uname);
 5361:     my $truth=1;
 5362:     #if the string starts with !, then the list is the list to show not hide
 5363:     if ($hiddenparts=~s/^\s*!//) { $truth=undef; }
 5364:     my @hiddenlist=split(/,/,$hiddenparts);
 5365:     foreach my $checkid (@hiddenlist) {
 5366: 	if ($checkid =~ /^\s*\Q$id\E\s*$/) { return $truth; }
 5367:     }
 5368:     return !$truth;
 5369: }
 5370: 
 5371: 
 5372: ############################################################
 5373: ############################################################
 5374: 
 5375: =pod
 5376: 
 5377: =back 
 5378: 
 5379: =head1 cgi-bin script and graphing routines
 5380: 
 5381: =over 4
 5382: 
 5383: =item get_cgi_id
 5384: 
 5385: Inputs: none
 5386: 
 5387: Returns an id which can be used to pass environment variables
 5388: to various cgi-bin scripts.  These environment variables will
 5389: be removed from the users environment after a given time by
 5390: the routine &Apache::lonnet::transfer_profile_to_env.
 5391: 
 5392: =cut
 5393: 
 5394: ############################################################
 5395: ############################################################
 5396: my $uniq=0;
 5397: sub get_cgi_id {
 5398:     $uniq=($uniq+1)%100000;
 5399:     return (time.'_'.$$.'_'.$uniq);
 5400: }
 5401: 
 5402: ############################################################
 5403: ############################################################
 5404: 
 5405: =pod
 5406: 
 5407: =item DrawBarGraph
 5408: 
 5409: Facilitates the plotting of data in a (stacked) bar graph.
 5410: Puts plot definition data into the users environment in order for 
 5411: graph.png to plot it.  Returns an <img> tag for the plot.
 5412: The bars on the plot are labeled '1','2',...,'n'.
 5413: 
 5414: Inputs:
 5415: 
 5416: =over 4
 5417: 
 5418: =item $Title: string, the title of the plot
 5419: 
 5420: =item $xlabel: string, text describing the X-axis of the plot
 5421: 
 5422: =item $ylabel: string, text describing the Y-axis of the plot
 5423: 
 5424: =item $Max: scalar, the maximum Y value to use in the plot
 5425: If $Max is < any data point, the graph will not be rendered.
 5426: 
 5427: =item $colors: array ref holding the colors to be used for the data sets when
 5428: they are plotted.  If undefined, default values will be used.
 5429: 
 5430: =item $labels: array ref holding the labels to use on the x-axis for the bars.
 5431: 
 5432: =item @Values: An array of array references.  Each array reference holds data
 5433: to be plotted in a stacked bar chart.
 5434: 
 5435: =item If the final element of @Values is a hash reference the key/value
 5436: pairs will be added to the graph definition.
 5437: 
 5438: =back
 5439: 
 5440: Returns:
 5441: 
 5442: An <img> tag which references graph.png and the appropriate identifying
 5443: information for the plot.
 5444: 
 5445: =cut
 5446: 
 5447: ############################################################
 5448: ############################################################
 5449: sub DrawBarGraph {
 5450:     my ($Title,$xlabel,$ylabel,$Max,$colors,$labels,@Values)=@_;
 5451:     #
 5452:     if (! defined($colors)) {
 5453:         $colors = ['#33ff00', 
 5454:                   '#0033cc', '#990000', '#aaaa66', '#663399', '#ff9933',
 5455:                   '#66ccff', '#ff9999', '#cccc33', '#660000', '#33cc66',
 5456:                   ]; 
 5457:     }
 5458:     my $extra_settings = {};
 5459:     if (ref($Values[-1]) eq 'HASH') {
 5460:         $extra_settings = pop(@Values);
 5461:     }
 5462:     #
 5463:     my $identifier = &get_cgi_id();
 5464:     my $id = 'cgi.'.$identifier;        
 5465:     if (! @Values || ref($Values[0]) ne 'ARRAY') {
 5466:         return '';
 5467:     }
 5468:     #
 5469:     my @Labels;
 5470:     if (defined($labels)) {
 5471:         @Labels = @$labels;
 5472:     } else {
 5473:         for (my $i=0;$i<@{$Values[0]};$i++) {
 5474:             push (@Labels,$i+1);
 5475:         }
 5476:     }
 5477:     #
 5478:     my $NumBars = scalar(@{$Values[0]});
 5479:     if ($NumBars < scalar(@Labels)) { $NumBars = scalar(@Labels); }
 5480:     my %ValuesHash;
 5481:     my $NumSets=1;
 5482:     foreach my $array (@Values) {
 5483:         next if (! ref($array));
 5484:         $ValuesHash{$id.'.data.'.$NumSets++} = 
 5485:             join(',',@$array);
 5486:     }
 5487:     #
 5488:     my ($height,$width,$xskip,$bar_width) = (200,120,1,15);
 5489:     if ($NumBars < 3) {
 5490:         $width = 120+$NumBars*32;
 5491:         $xskip = 1;
 5492:         $bar_width = 30;
 5493:     } elsif ($NumBars < 5) {
 5494:         $width = 120+$NumBars*20;
 5495:         $xskip = 1;
 5496:         $bar_width = 20;
 5497:     } elsif ($NumBars < 10) {
 5498:         $width = 120+$NumBars*15;
 5499:         $xskip = 1;
 5500:         $bar_width = 15;
 5501:     } elsif ($NumBars <= 25) {
 5502:         $width = 120+$NumBars*11;
 5503:         $xskip = 5;
 5504:         $bar_width = 8;
 5505:     } elsif ($NumBars <= 50) {
 5506:         $width = 120+$NumBars*8;
 5507:         $xskip = 5;
 5508:         $bar_width = 4;
 5509:     } else {
 5510:         $width = 120+$NumBars*8;
 5511:         $xskip = 5;
 5512:         $bar_width = 4;
 5513:     }
 5514:     #
 5515:     $Max = 1 if ($Max < 1);
 5516:     if ( int($Max) < $Max ) {
 5517:         $Max++;
 5518:         $Max = int($Max);
 5519:     }
 5520:     $Title  = '' if (! defined($Title));
 5521:     $xlabel = '' if (! defined($xlabel));
 5522:     $ylabel = '' if (! defined($ylabel));
 5523:     $ValuesHash{$id.'.title'}    = &escape($Title);
 5524:     $ValuesHash{$id.'.xlabel'}   = &escape($xlabel);
 5525:     $ValuesHash{$id.'.ylabel'}   = &escape($ylabel);
 5526:     $ValuesHash{$id.'.y_max_value'} = $Max;
 5527:     $ValuesHash{$id.'.NumBars'}  = $NumBars;
 5528:     $ValuesHash{$id.'.NumSets'}  = $NumSets;
 5529:     $ValuesHash{$id.'.PlotType'} = 'bar';
 5530:     $ValuesHash{$id.'.Colors'}   = join(',',@{$colors});
 5531:     $ValuesHash{$id.'.height'}   = $height;
 5532:     $ValuesHash{$id.'.width'}    = $width;
 5533:     $ValuesHash{$id.'.xskip'}    = $xskip;
 5534:     $ValuesHash{$id.'.bar_width'} = $bar_width;
 5535:     $ValuesHash{$id.'.labels'} = join(',',@Labels);
 5536:     #
 5537:     # Deal with other parameters
 5538:     while (my ($key,$value) = each(%$extra_settings)) {
 5539:         $ValuesHash{$id.'.'.$key} = $value;
 5540:     }
 5541:     #
 5542:     &Apache::lonnet::appenv(%ValuesHash);
 5543:     return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
 5544: }
 5545: 
 5546: ############################################################
 5547: ############################################################
 5548: 
 5549: =pod
 5550: 
 5551: =item DrawXYGraph
 5552: 
 5553: Facilitates the plotting of data in an XY graph.
 5554: Puts plot definition data into the users environment in order for 
 5555: graph.png to plot it.  Returns an <img> tag for the plot.
 5556: 
 5557: Inputs:
 5558: 
 5559: =over 4
 5560: 
 5561: =item $Title: string, the title of the plot
 5562: 
 5563: =item $xlabel: string, text describing the X-axis of the plot
 5564: 
 5565: =item $ylabel: string, text describing the Y-axis of the plot
 5566: 
 5567: =item $Max: scalar, the maximum Y value to use in the plot
 5568: If $Max is < any data point, the graph will not be rendered.
 5569: 
 5570: =item $colors: Array ref containing the hex color codes for the data to be 
 5571: plotted in.  If undefined, default values will be used.
 5572: 
 5573: =item $Xlabels: Array ref containing the labels to be used for the X-axis.
 5574: 
 5575: =item $Ydata: Array ref containing Array refs.  
 5576: Each of the contained arrays will be plotted as a separate curve.
 5577: 
 5578: =item %Values: hash indicating or overriding any default values which are 
 5579: passed to graph.png.  
 5580: Possible values are: width, xskip, x_ticks, x_tick_offset, among others.
 5581: 
 5582: =back
 5583: 
 5584: Returns:
 5585: 
 5586: An <img> tag which references graph.png and the appropriate identifying
 5587: information for the plot.
 5588: 
 5589: =cut
 5590: 
 5591: ############################################################
 5592: ############################################################
 5593: sub DrawXYGraph {
 5594:     my ($Title,$xlabel,$ylabel,$Max,$colors,$Xlabels,$Ydata,%Values)=@_;
 5595:     #
 5596:     # Create the identifier for the graph
 5597:     my $identifier = &get_cgi_id();
 5598:     my $id = 'cgi.'.$identifier;
 5599:     #
 5600:     $Title  = '' if (! defined($Title));
 5601:     $xlabel = '' if (! defined($xlabel));
 5602:     $ylabel = '' if (! defined($ylabel));
 5603:     my %ValuesHash = 
 5604:         (
 5605:          $id.'.title'  => &escape($Title),
 5606:          $id.'.xlabel' => &escape($xlabel),
 5607:          $id.'.ylabel' => &escape($ylabel),
 5608:          $id.'.y_max_value'=> $Max,
 5609:          $id.'.labels'     => join(',',@$Xlabels),
 5610:          $id.'.PlotType'   => 'XY',
 5611:          );
 5612:     #
 5613:     if (defined($colors) && ref($colors) eq 'ARRAY') {
 5614:         $ValuesHash{$id.'.Colors'}   = join(',',@{$colors});
 5615:     }
 5616:     #
 5617:     if (! ref($Ydata) || ref($Ydata) ne 'ARRAY') {
 5618:         return '';
 5619:     }
 5620:     my $NumSets=1;
 5621:     foreach my $array (@{$Ydata}){
 5622:         next if (! ref($array));
 5623:         $ValuesHash{$id.'.data.'.$NumSets++} = join(',',@$array);
 5624:     }
 5625:     $ValuesHash{$id.'.NumSets'} = $NumSets-1;
 5626:     #
 5627:     # Deal with other parameters
 5628:     while (my ($key,$value) = each(%Values)) {
 5629:         $ValuesHash{$id.'.'.$key} = $value;
 5630:     }
 5631:     #
 5632:     &Apache::lonnet::appenv(%ValuesHash);
 5633:     return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
 5634: }
 5635: 
 5636: ############################################################
 5637: ############################################################
 5638: 
 5639: =pod
 5640: 
 5641: =item DrawXYYGraph
 5642: 
 5643: Facilitates the plotting of data in an XY graph with two Y axes.
 5644: Puts plot definition data into the users environment in order for 
 5645: graph.png to plot it.  Returns an <img> tag for the plot.
 5646: 
 5647: Inputs:
 5648: 
 5649: =over 4
 5650: 
 5651: =item $Title: string, the title of the plot
 5652: 
 5653: =item $xlabel: string, text describing the X-axis of the plot
 5654: 
 5655: =item $ylabel: string, text describing the Y-axis of the plot
 5656: 
 5657: =item $colors: Array ref containing the hex color codes for the data to be 
 5658: plotted in.  If undefined, default values will be used.
 5659: 
 5660: =item $Xlabels: Array ref containing the labels to be used for the X-axis.
 5661: 
 5662: =item $Ydata1: The first data set
 5663: 
 5664: =item $Min1: The minimum value of the left Y-axis
 5665: 
 5666: =item $Max1: The maximum value of the left Y-axis
 5667: 
 5668: =item $Ydata2: The second data set
 5669: 
 5670: =item $Min2: The minimum value of the right Y-axis
 5671: 
 5672: =item $Max2: The maximum value of the left Y-axis
 5673: 
 5674: =item %Values: hash indicating or overriding any default values which are 
 5675: passed to graph.png.  
 5676: Possible values are: width, xskip, x_ticks, x_tick_offset, among others.
 5677: 
 5678: =back
 5679: 
 5680: Returns:
 5681: 
 5682: An <img> tag which references graph.png and the appropriate identifying
 5683: information for the plot.
 5684: 
 5685: =cut
 5686: 
 5687: ############################################################
 5688: ############################################################
 5689: sub DrawXYYGraph {
 5690:     my ($Title,$xlabel,$ylabel,$colors,$Xlabels,$Ydata1,$Min1,$Max1,
 5691:                                         $Ydata2,$Min2,$Max2,%Values)=@_;
 5692:     #
 5693:     # Create the identifier for the graph
 5694:     my $identifier = &get_cgi_id();
 5695:     my $id = 'cgi.'.$identifier;
 5696:     #
 5697:     $Title  = '' if (! defined($Title));
 5698:     $xlabel = '' if (! defined($xlabel));
 5699:     $ylabel = '' if (! defined($ylabel));
 5700:     my %ValuesHash = 
 5701:         (
 5702:          $id.'.title'  => &escape($Title),
 5703:          $id.'.xlabel' => &escape($xlabel),
 5704:          $id.'.ylabel' => &escape($ylabel),
 5705:          $id.'.labels' => join(',',@$Xlabels),
 5706:          $id.'.PlotType' => 'XY',
 5707:          $id.'.NumSets' => 2,
 5708:          $id.'.two_axes' => 1,
 5709:          $id.'.y1_max_value' => $Max1,
 5710:          $id.'.y1_min_value' => $Min1,
 5711:          $id.'.y2_max_value' => $Max2,
 5712:          $id.'.y2_min_value' => $Min2,
 5713:          );
 5714:     #
 5715:     if (defined($colors) && ref($colors) eq 'ARRAY') {
 5716:         $ValuesHash{$id.'.Colors'}   = join(',',@{$colors});
 5717:     }
 5718:     #
 5719:     if (! ref($Ydata1) || ref($Ydata1) ne 'ARRAY' ||
 5720:         ! ref($Ydata2) || ref($Ydata2) ne 'ARRAY'){
 5721:         return '';
 5722:     }
 5723:     my $NumSets=1;
 5724:     foreach my $array ($Ydata1,$Ydata2){
 5725:         next if (! ref($array));
 5726:         $ValuesHash{$id.'.data.'.$NumSets++} = join(',',@$array);
 5727:     }
 5728:     #
 5729:     # Deal with other parameters
 5730:     while (my ($key,$value) = each(%Values)) {
 5731:         $ValuesHash{$id.'.'.$key} = $value;
 5732:     }
 5733:     #
 5734:     &Apache::lonnet::appenv(%ValuesHash);
 5735:     return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
 5736: }
 5737: 
 5738: ############################################################
 5739: ############################################################
 5740: 
 5741: =pod
 5742: 
 5743: =back 
 5744: 
 5745: =head1 Statistics helper routines?  
 5746: 
 5747: Bad place for them but what the hell.
 5748: 
 5749: =over 4
 5750: 
 5751: =item &chartlink
 5752: 
 5753: Returns a link to the chart for a specific student.  
 5754: 
 5755: Inputs:
 5756: 
 5757: =over 4
 5758: 
 5759: =item $linktext: The text of the link
 5760: 
 5761: =item $sname: The students username
 5762: 
 5763: =item $sdomain: The students domain
 5764: 
 5765: =back
 5766: 
 5767: =back
 5768: 
 5769: =cut
 5770: 
 5771: ############################################################
 5772: ############################################################
 5773: sub chartlink {
 5774:     my ($linktext, $sname, $sdomain) = @_;
 5775:     my $link = '<a href="/adm/statistics?reportSelected=student_assessment'.
 5776:         '&amp;SelectedStudent='.&escape($sname.':'.$sdomain).
 5777:         '&amp;chartoutputmode='.HTML::Entities::encode('html, with all links').
 5778:        '">'.$linktext.'</a>';
 5779: }
 5780: 
 5781: #######################################################
 5782: #######################################################
 5783: 
 5784: =pod
 5785: 
 5786: =head1 Course Environment Routines
 5787: 
 5788: =over 4
 5789: 
 5790: =item &restore_course_settings 
 5791: 
 5792: =item &store_course_settings
 5793: 
 5794: Restores/Store indicated form parameters from the course environment.
 5795: Will not overwrite existing values of the form parameters.
 5796: 
 5797: Inputs: 
 5798: a scalar describing the data (e.g. 'chart', 'problem_analysis')
 5799: 
 5800: a hash ref describing the data to be stored.  For example:
 5801:    
 5802: %Save_Parameters = ('Status' => 'scalar',
 5803:     'chartoutputmode' => 'scalar',
 5804:     'chartoutputdata' => 'scalar',
 5805:     'Section' => 'array',
 5806:     'Group' => 'array',
 5807:     'StudentData' => 'array',
 5808:     'Maps' => 'array');
 5809: 
 5810: Returns: both routines return nothing
 5811: 
 5812: =cut
 5813: 
 5814: #######################################################
 5815: #######################################################
 5816: sub store_course_settings {
 5817:     # save to the environment
 5818:     # appenv the same items, just to be safe
 5819:     my $courseid = $env{'request.course.id'};
 5820:     my $udom  = $env{'user.domain'};
 5821:     my $uname = $env{'user.name'};
 5822:     my ($prefix,$Settings) = @_;
 5823:     my %SaveHash;
 5824:     my %AppHash;
 5825:     while (my ($setting,$type) = each(%$Settings)) {
 5826:         my $basename = join('.','internal',$courseid,$prefix,$setting);
 5827:         my $envname = 'environment.'.$basename;
 5828:         if (exists($env{'form.'.$setting})) {
 5829:             # Save this value away
 5830:             if ($type eq 'scalar' &&
 5831:                 (! exists($env{$envname}) || 
 5832:                  $env{$envname} ne $env{'form.'.$setting})) {
 5833:                 $SaveHash{$basename} = $env{'form.'.$setting};
 5834:                 $AppHash{$envname}   = $env{'form.'.$setting};
 5835:             } elsif ($type eq 'array') {
 5836:                 my $stored_form;
 5837:                 if (ref($env{'form.'.$setting})) {
 5838:                     $stored_form = join(',',
 5839:                                         map {
 5840:                                             &escape($_);
 5841:                                         } sort(@{$env{'form.'.$setting}}));
 5842:                 } else {
 5843:                     $stored_form = 
 5844:                         &escape($env{'form.'.$setting});
 5845:                 }
 5846:                 # Determine if the array contents are the same.
 5847:                 if ($stored_form ne $env{$envname}) {
 5848:                     $SaveHash{$basename} = $stored_form;
 5849:                     $AppHash{$envname}   = $stored_form;
 5850:                 }
 5851:             }
 5852:         }
 5853:     }
 5854:     my $put_result = &Apache::lonnet::put('environment',\%SaveHash,
 5855:                                           $udom,$uname);
 5856:     if ($put_result !~ /^(ok|delayed)/) {
 5857:         &Apache::lonnet::logthis('unable to save form parameters, '.
 5858:                                  'got error:'.$put_result);
 5859:     }
 5860:     # Make sure these settings stick around in this session, too
 5861:     &Apache::lonnet::appenv(%AppHash);
 5862:     return;
 5863: }
 5864: 
 5865: sub restore_course_settings {
 5866:     my $courseid = $env{'request.course.id'};
 5867:     my ($prefix,$Settings) = @_;
 5868:     while (my ($setting,$type) = each(%$Settings)) {
 5869:         next if (exists($env{'form.'.$setting}));
 5870:         my $envname = 'environment.internal.'.$courseid.'.'.$prefix.
 5871:             '.'.$setting;
 5872:         if (exists($env{$envname})) {
 5873:             if ($type eq 'scalar') {
 5874:                 $env{'form.'.$setting} = $env{$envname};
 5875:             } elsif ($type eq 'array') {
 5876:                 $env{'form.'.$setting} = [ 
 5877:                                            map { 
 5878:                                                &unescape($_); 
 5879:                                            } split(',',$env{$envname})
 5880:                                            ];
 5881:             }
 5882:         }
 5883:     }
 5884: }
 5885: 
 5886: ############################################################
 5887: ############################################################
 5888: 
 5889: sub commit_customrole {
 5890:     my ($udom,$uname,$url,$three,$four,$five,$start,$end) = @_;
 5891:     my $output = &mt('Assigning custom role').' "'.$five.'" by '.$four.'@'.$three.' in '.$url.
 5892:                          ($start?', '.&mt('starting').' '.localtime($start):'').
 5893:                          ($end?', ending '.localtime($end):'').': <b>'.
 5894:               &Apache::lonnet::assigncustomrole(
 5895:                  $udom,$uname,$url,$three,$four,$five,$end,$start).
 5896:                  '</b><br />';
 5897:     return $output;
 5898: }
 5899: 
 5900: sub commit_standardrole {
 5901:     my ($udom,$uname,$url,$three,$start,$end,$one,$two,$sec) = @_;
 5902:     my $output;
 5903:     my $logmsg;
 5904:     if ($three eq 'st') {
 5905:         my $result = &commit_studentrole(\$logmsg,$udom,$uname,$url,$three,$start,$end,$one,$two,$sec);
 5906:         if (($result =~ /^error/) || ($result eq 'not_in_class') || ($result eq 'unknown_course')) {
 5907:             $output = "Error: $result\n"; 
 5908:         } else {
 5909:             $output = &mt('Assigning').' '.$three.' in '.$url.
 5910:                ($start?', '.&mt('starting').' '.localtime($start):'').
 5911:                ($end?', '.&mt('ending').' '.localtime($end):'').
 5912:                ': <b>'.$result.'</b><br />'.
 5913:                &mt('Add to classlist').': <b>ok</b><br />';
 5914:         }
 5915:     } else {
 5916:         $output = &mt('Assigning').' '.$three.' in '.$url.
 5917:                ($start?', '.&mt('starting').' '.localtime($start):'').
 5918:                ($end?', '.&mt('ending').' '.localtime($end):'').': <b>'.
 5919:                &Apache::lonnet::assignrole(
 5920:                    $udom,$uname,$url,$three,$end,$start).
 5921:                    '</b><br />';
 5922:     }
 5923:     return $output;
 5924: }
 5925: 
 5926: sub commit_studentrole {
 5927:     my ($logmsg,$udom,$uname,$url,$three,$start,$end,$one,$two,$sec) = @_;
 5928:     my $linefeed =  '<br />'."\n";
 5929:     my $result;
 5930:     if (defined($one) && defined($two)) {
 5931:         my $cid=$one.'_'.$two;
 5932:         my $oldsec=&Apache::lonnet::getsection($udom,$uname,$cid);
 5933:         my $secchange = 0;
 5934:         my $expire_role_result;
 5935:         my $modify_section_result;
 5936:         unless ($oldsec eq '-1') {
 5937:             unless ($sec eq $oldsec) {
 5938:                 $secchange = 1;
 5939:                 my $uurl='/'.$cid;
 5940:                 $uurl=~s/\_/\//g;
 5941:                 if ($oldsec) {
 5942:                     $uurl.='/'.$oldsec;
 5943:                 }
 5944:                 $expire_role_result = &Apache::lonnet::assignrole($udom,$uname,$uurl,'st',time);
 5945:                 $result = $expire_role_result;
 5946:             }
 5947:         }
 5948:         if (($expire_role_result eq 'ok') || ($secchange == 0)) {
 5949:             $modify_section_result = &Apache::lonnet::modify_student_enrollment($udom,$uname,undef,undef,undef,undef,undef,$sec,$end,$start,'','',$cid);
 5950:             if ($modify_section_result =~ /^ok/) {
 5951:                 if ($secchange == 1) {
 5952:                     $$logmsg .= "Section for $uname switched from old section: $oldsec to new section: $sec".$linefeed;
 5953:                 } elsif ($oldsec eq '-1') {
 5954:                     $$logmsg .= "New student role for $uname in section $sec in course $cid".$linefeed;
 5955:                 } else {
 5956:                     $$logmsg .= "Student $uname assigned to unchanged section $sec in course $cid".$linefeed;
 5957:                 }
 5958:             } else {
 5959:                 $$logmsg .= "Error when attempting section change for $uname from old section $oldsec to new section: $sec in course $cid -error: $modify_section_result".$linefeed;
 5960:             }
 5961:             $result = $modify_section_result;
 5962:         } elsif ($secchange == 1) {
 5963:             $$logmsg .= "Error when attempting to expire role for $uname in old section $oldsec in course $cid -error: $expire_role_result".$linefeed;
 5964:         }
 5965:     } else {
 5966:         $$logmsg .= "Incomplete course id defined.  Addition of user $uname from domain $udom to course $one\_$two, section $sec not completed.$linefeed";
 5967:         $result = "error: incomplete course id\n";
 5968:     }
 5969:     return $result;
 5970: }
 5971: 
 5972: ############################################################
 5973: ############################################################
 5974: 
 5975: sub construct_course {
 5976:     my ($args,$logmsg,$courseid,$crsudom,$crsunum,$udom,$uname) = @_;
 5977:     my $outcome;
 5978: 
 5979: #
 5980: # Open course
 5981: #
 5982:     my $crstype = lc($args->{'crstype'});
 5983:     my %cenv=();
 5984:     $$courseid=&Apache::lonnet::createcourse($args->{'course_domain'},
 5985:                                              $args->{'cdescr'},
 5986:                                              $args->{'curl'},
 5987:                                              $args->{'course_home'},
 5988:                                              $args->{'nonstandard'},
 5989:                                              $args->{'crscode'},
 5990:                                              $args->{'ccuname'}.':'.
 5991:                                              $args->{'ccdomain'},
 5992:                                              $args->{'crstype'});
 5993: 
 5994:     # Note: The testing routines depend on this being output; see 
 5995:     # Utils::Course. This needs to at least be output as a comment
 5996:     # if anyone ever decides to not show this, and Utils::Course::new
 5997:     # will need to be suitably modified.
 5998:     $outcome .= &mt('New LON-CAPA [_1] ID: [_2]<br />',$crstype,$$courseid);
 5999: #
 6000: # Check if created correctly
 6001: #
 6002:     ($$crsudom,$$crsunum)=($$courseid=~/^\/(\w+)\/(\w+)$/);
 6003:     my $crsuhome=&Apache::lonnet::homeserver($$crsunum,$$crsudom);
 6004:     $outcome .= &mt('Created on').': '.$crsuhome.'<br>';
 6005: #
 6006: # Are we cloning?
 6007: #
 6008:     my $cloneid='';
 6009:     if (($args->{'clonecourse'}) && ($args->{'clonedomain'})) {
 6010: 	$cloneid='/'.$args->{'clonedomain'}.'/'.$args->{'clonecourse'};
 6011:         my ($clonecrsudom,$clonecrsunum)=($cloneid=~/^\/(\w+)\/(\w+)$/);
 6012: 	my $clonehome=&Apache::lonnet::homeserver($clonecrsunum,$clonecrsudom);
 6013: 	if ($clonehome eq 'no_host') {
 6014: 	    $outcome .=
 6015:     '<br /><font color="red">'.&mt('Attempting to clone non-existing [_1]',$crstype).' '.$cloneid.'</font>';
 6016: 	} else {
 6017: 	    $outcome .= 
 6018:     '<br /><font color="green">'.&mt('Cloning [_1] from [_2]',$crstype,$clonehome).'</font>';
 6019: 	    my %oldcenv=&Apache::lonnet::dump('environment',$$crsudom,$$crsunum);
 6020: # Copy all files
 6021: 	    &Apache::lonclonecourse::copycoursefiles($cloneid,$$courseid);
 6022: # Restore URL
 6023: 	    $cenv{'url'}=$oldcenv{'url'};
 6024: # Restore title
 6025: 	    $cenv{'description'}=$oldcenv{'description'};
 6026: # restore grading mode
 6027: 	    if (defined($oldcenv{'grading'})) {
 6028: 		$cenv{'grading'}=$oldcenv{'grading'};
 6029: 	    }
 6030: # Mark as cloned
 6031: 	    $cenv{'clonedfrom'}=$cloneid;
 6032: 	    delete($cenv{'default_enrollment_start_date'});
 6033: 	    delete($cenv{'default_enrollment_end_date'});
 6034: 	}
 6035:     }
 6036: #
 6037: # Set environment (will override cloned, if existing)
 6038: #
 6039:     my @sections = ();
 6040:     my @xlists = ();
 6041:     if ($args->{'crstype'}) {
 6042:         $cenv{'type'}=$args->{'crstype'};
 6043:     }
 6044:     if ($args->{'crsid'}) {
 6045:         $cenv{'courseid'}=$args->{'crsid'};
 6046:     }
 6047:     if ($args->{'crscode'}) {
 6048:         $cenv{'internal.coursecode'}=$args->{'crscode'};
 6049:     }
 6050:     if ($args->{'crsquota'} ne '') {
 6051:         $cenv{'internal.coursequota'}=$args->{'crsquota'};
 6052:     } else {
 6053:         $cenv{'internal.coursequota'}=$args->{'crsquota'} = 20;
 6054:     }
 6055:     if ($args->{'ccuname'}) {
 6056:         $cenv{'internal.courseowner'} = $args->{'ccuname'}.
 6057:                                         ':'.$args->{'ccdomain'};
 6058:     } else {
 6059:         $cenv{'internal.courseowner'} = $args->{'curruser'};
 6060:     }
 6061: 
 6062:     my @badclasses = (); # Used to accumulate sections/crosslistings that did not pass classlist access check for course owner.
 6063:     if ($args->{'crssections'}) {
 6064:         $cenv{'internal.sectionnums'} = '';
 6065:         if ($args->{'crssections'} =~ m/,/) {
 6066:             @sections = split/,/,$args->{'crssections'};
 6067:         } else {
 6068:             $sections[0] = $args->{'crssections'};
 6069:         }
 6070:         if (@sections > 0) {
 6071:             foreach my $item (@sections) {
 6072:                 my ($sec,$gp) = split/:/,$item;
 6073:                 my $class = $args->{'crscode'}.$sec;
 6074:                 my $addcheck = &Apache::lonnet::auto_new_course($$crsunum,$$crsudom,$class,$cenv{'internal.courseowner'});
 6075:                 $cenv{'internal.sectionnums'} .= $item.',';
 6076:                 unless ($addcheck eq 'ok') {
 6077:                     push @badclasses, $class;
 6078:                 }
 6079:             }
 6080:             $cenv{'internal.sectionnums'} =~ s/,$//;
 6081:         }
 6082:     }
 6083: # do not hide course coordinator from staff listing, 
 6084: # even if privileged
 6085:     $cenv{'nothideprivileged'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
 6086: # add crosslistings
 6087:     if ($args->{'crsxlist'}) {
 6088:         $cenv{'internal.crosslistings'}='';
 6089:         if ($args->{'crsxlist'} =~ m/,/) {
 6090:             @xlists = split/,/,$args->{'crsxlist'};
 6091:         } else {
 6092:             $xlists[0] = $args->{'crsxlist'};
 6093:         }
 6094:         if (@xlists > 0) {
 6095:             foreach my $item (@xlists) {
 6096:                 my ($xl,$gp) = split/:/,$item;
 6097:                 my $addcheck =  &Apache::lonnet::auto_new_course($$crsunum,$$crsudom,$xl,$cenv{'internal.courseowner'});
 6098:                 $cenv{'internal.crosslistings'} .= $item.',';
 6099:                 unless ($addcheck eq 'ok') {
 6100:                     push @badclasses, $xl;
 6101:                 }
 6102:             }
 6103:             $cenv{'internal.crosslistings'} =~ s/,$//;
 6104:         }
 6105:     }
 6106:     if ($args->{'autoadds'}) {
 6107:         $cenv{'internal.autoadds'}=$args->{'autoadds'};
 6108:     }
 6109:     if ($args->{'autodrops'}) {
 6110:         $cenv{'internal.autodrops'}=$args->{'autodrops'};
 6111:     }
 6112: # check for notification of enrollment changes
 6113:     my @notified = ();
 6114:     if ($args->{'notify_owner'}) {
 6115:         if ($args->{'ccuname'} ne '') {
 6116:             push(@notified,$args->{'ccuname'}.':'.$args->{'ccdomain'});
 6117:         }
 6118:     }
 6119:     if ($args->{'notify_dc'}) {
 6120:         if ($uname ne '') { 
 6121:             push(@notified,$uname.'@'.$udom);
 6122:         }
 6123:     }
 6124:     if (@notified > 0) {
 6125:         my $notifylist;
 6126:         if (@notified > 1) {
 6127:             $notifylist = join(',',@notified);
 6128:         } else {
 6129:             $notifylist = $notified[0];
 6130:         }
 6131:         $cenv{'internal.notifylist'} = $notifylist;
 6132:     }
 6133:     if (@badclasses > 0) {
 6134:         my %lt=&Apache::lonlocal::texthash(
 6135:                 'tclb' => 'The courses listed below were included as sections or crosslistings affiliated with your new LON-CAPA course.  However, if automated course roster updates are enabled for this class, these particular sections/crosslistings will not contribute towards enrollment, because the user identified as the course owner for this LON-CAPA course',
 6136:                 'dnhr' => 'does not have rights to access enrollment in these classes',
 6137:                 'adby' => 'as determined by the policies of your institution on access to official classlists'
 6138:         );
 6139:         $outcome .= '<font color="red">'.$lt{'tclb'}.' ('.$cenv{'internal.courseowner'}.') - '.$lt{'dnhr'}.' ('.$lt{'adby'}.').<br /><ul>'."\n";
 6140:         foreach (@badclasses) {
 6141:             $outcome .= "<li>$_</li>\n";
 6142:         }
 6143:         $outcome .= "</ul><br /><br /></font>\n";
 6144:     }
 6145:     if ($args->{'no_end_date'}) {
 6146:         $args->{'endaccess'} = 0;
 6147:     }
 6148:     $cenv{'internal.autostart'}=$args->{'enrollstart'};
 6149:     $cenv{'internal.autoend'}=$args->{'enrollend'};
 6150:     $cenv{'default_enrollment_start_date'}=$args->{'startaccess'};
 6151:     $cenv{'default_enrollment_end_date'}=$args->{'endaccess'};
 6152:     if ($args->{'showphotos'}) {
 6153:       $cenv{'internal.showphotos'}=$args->{'showphotos'};
 6154:     }
 6155:     $cenv{'internal.authtype'} = $args->{'authtype'};
 6156:     $cenv{'internal.autharg'} = $args->{'autharg'}; 
 6157:     if ( ($cenv{'internal.authtype'} =~ /^krb/) && ($cenv{'internal.autoadds'} == 1)) {
 6158:         if (! defined($cenv{'internal.autharg'}) || $cenv{'internal.autharg'}  eq '') {
 6159:             $outcome .= '<font color="red" size="+1">'.
 6160:                       &mt('As you did not include the default Kerberos domain to be used for authentication in this class, the institutional data used by the automated enrollment process must include the Kerberos domain for each new student').'</font></p>';
 6161:         }
 6162:     }
 6163:     if (($args->{'ccdomain'}) && ($args->{'ccuname'})) {
 6164:        if ($args->{'setpolicy'}) {
 6165:            $cenv{'policy.email'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
 6166:        }
 6167:        if ($args->{'setcontent'}) {
 6168:            $cenv{'question.email'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
 6169:        }
 6170:     }
 6171:     if ($args->{'reshome'}) {
 6172: 	$cenv{'reshome'}=$args->{'reshome'}.'/';
 6173: 	$cenv{'reshome'}=~s/\/+$/\//;
 6174:     }
 6175: #
 6176: # course has keyed access
 6177: #
 6178:     if ($args->{'setkeys'}) {
 6179:        $cenv{'keyaccess'}='yes';
 6180:     }
 6181: # if specified, key authority is not course, but user
 6182: # only active if keyaccess is yes
 6183:     if ($args->{'keyauth'}) {
 6184: 	$args->{'keyauth'}=~s/[^\w\@]//g;
 6185: 	if ($args->{'keyauth'}) {
 6186: 	    $cenv{'keyauth'}=$args->{'keyauth'};
 6187: 	}
 6188:     }
 6189: 
 6190:     if ($args->{'disresdis'}) {
 6191:         $cenv{'pch.roles.denied'}='st';
 6192:     }
 6193:     if ($args->{'disablechat'}) {
 6194:         $cenv{'plc.roles.denied'}='st';
 6195:     }
 6196: 
 6197:     # Record we've not yet viewed the Course Initialization Helper for this 
 6198:     # course
 6199:     $cenv{'course.helper.not.run'} = 1;
 6200:     #
 6201:     # Use new Randomseed
 6202:     #
 6203:     $cenv{'rndseed'}=&Apache::lonnet::latest_rnd_algorithm_id();;
 6204:     $cenv{'receiptalg'}=&Apache::lonnet::latest_receipt_algorithm_id();;
 6205:     #
 6206:     # The encryption code and receipt prefix for this course
 6207:     #
 6208:     $cenv{'internal.encseed'}=$Apache::lonnet::perlvar{'lonReceipt'}.$$.time.int(rand(9999));
 6209:     $cenv{'internal.encpref'}=100+int(9*rand(99));
 6210:     #
 6211:     # By default, use standard grading
 6212:     if (!defined($cenv{'grading'})) { $cenv{'grading'} = 'standard'; }
 6213: 
 6214:     $outcome .= ('<br />'.&mt('Setting environment').': '.                 
 6215:           &Apache::lonnet::put('environment',\%cenv,$$crsudom,$$crsunum).'<br>');
 6216: #
 6217: # Open all assignments
 6218: #
 6219:     if ($args->{'openall'}) {
 6220:        my $storeunder=$$crsudom.'_'.$$crsunum.'.0.opendate';
 6221:        my %storecontent = ($storeunder         => time,
 6222:                            $storeunder.'.type' => 'date_start');
 6223:        
 6224:        $outcome .= &mt('Opening all assignments').': '.&Apache::lonnet::cput
 6225:                  ('resourcedata',\%storecontent,$$crsudom,$$crsunum).'<br>';
 6226:    }
 6227: #
 6228: # Set first page
 6229: #
 6230:     unless (($args->{'nonstandard'}) || ($args->{'firstres'} eq 'blank')
 6231: 	    || ($cloneid)) {
 6232: 	use LONCAPA::map;
 6233: 	$outcome .= &mt('Setting first resource').': ';
 6234: 
 6235: 	my $map = '/uploaded/'.$$crsudom.'/'.$$crsunum.'/default.sequence';
 6236:         my ($errtext,$fatal)=&LONCAPA::map::mapread($map);
 6237: 
 6238:         $outcome .= ($fatal?$errtext:'read ok').' - ';
 6239:         my $title; my $url;
 6240:         if ($args->{'firstres'} eq 'syl') {
 6241: 	    $title='Syllabus';
 6242:             $url='/public/'.$$crsudom.'/'.$$crsunum.'/syllabus';
 6243:         } else {
 6244:             $title='Navigate Contents';
 6245:             $url='/adm/navmaps';
 6246:         }
 6247: 
 6248:         $LONCAPA::map::resources[1]=$title.':'.$url.':false:start:res';
 6249: 	(my $outtext,$errtext) = &LONCAPA::map::storemap($map,1);
 6250: 
 6251: 	if ($errtext) { $fatal=2; }
 6252:         $outcome .= ($fatal?$errtext:'write ok').'<br />';
 6253:     }
 6254:     return $outcome;
 6255: }
 6256: 
 6257: ############################################################
 6258: ############################################################
 6259: 
 6260: sub course_type {
 6261:     my ($cid) = @_;
 6262:     if (!defined($cid)) {
 6263:         $cid = $env{'request.course.id'};
 6264:     }
 6265:     if (defined($env{'course.'.$cid.'.type'})) {
 6266:         return $env{'course.'.$cid.'.type'};
 6267:     } else {
 6268:         return 'Course';
 6269:     }
 6270: }
 6271: 
 6272: sub group_term {
 6273:     my $crstype = &course_type();
 6274:     my %names = (
 6275:                   'Course' => 'group',
 6276:                   'Group' => 'team',
 6277:                 );
 6278:     return $names{$crstype};
 6279: }
 6280: 
 6281: sub icon {
 6282:     my ($file)=@_;
 6283:     my $curfext = (split(/\./,$file))[-1];
 6284:     my $iconname=$Apache::lonnet::perlvar{'lonIconsURL'}.'/unknown.gif';
 6285:     my $embstyle = &Apache::loncommon::fileembstyle($curfext);
 6286:     if (!(!defined($embstyle) || $embstyle eq 'unk' || $embstyle eq 'hdn')) {
 6287: 	if (-e  $Apache::lonnet::perlvar{'lonDocRoot'}.'/'.
 6288: 	          $Apache::lonnet::perlvar{'lonIconsURL'}.'/'.
 6289: 	            $curfext.".gif") {
 6290: 	    $iconname=$Apache::lonnet::perlvar{'lonIconsURL'}.'/'.
 6291: 		$curfext.".gif";
 6292: 	}
 6293:     }
 6294:     return &lonhttpdurl($iconname);
 6295: } 
 6296: 
 6297: sub lonhttpdurl {
 6298:     my ($url)=@_;
 6299:     my $lonhttpd_port=$Apache::lonnet::perlvar{'lonhttpdPort'};
 6300:     if (!defined($lonhttpd_port)) { $lonhttpd_port='8080'; }
 6301:     return 'http://'.$ENV{'SERVER_NAME'}.':'.$lonhttpd_port.$url;
 6302: }
 6303: 
 6304: sub connection_aborted {
 6305:     my ($r)=@_;
 6306:     $r->print(" ");$r->rflush();
 6307:     my $c = $r->connection;
 6308:     return $c->aborted();
 6309: }
 6310: 
 6311: #    Escapes strings that may have embedded 's that will be put into
 6312: #    strings as 'strings'.
 6313: sub escape_single {
 6314:     my ($input) = @_;
 6315:     $input =~ s/\\/\\\\/g;	# Escape the \'s..(must be first)>
 6316:     $input =~ s/\'/\\\'/g;	# Esacpe the 's....
 6317:     return $input;
 6318: }
 6319: 
 6320: #  Same as escape_single, but escape's "'s  This 
 6321: #  can be used for  "strings"
 6322: sub escape_double {
 6323:     my ($input) = @_;
 6324:     $input =~ s/\\/\\\\/g;	# Escape the /'s..(must be first)>
 6325:     $input =~ s/\"/\\\"/g;	# Esacpe the "s....
 6326:     return $input;
 6327: }
 6328:  
 6329: #   Escapes the last element of a full URL.
 6330: sub escape_url {
 6331:     my ($url)   = @_;
 6332:     my @urlslices = split(/\//, $url,-1);
 6333:     my $lastitem = &escape(pop(@urlslices));
 6334:     return join('/',@urlslices).'/'.$lastitem;
 6335: }
 6336: 
 6337: # -------------------------------------------------------- Initliaze user login
 6338: sub init_user_environment {
 6339:     my ($r, $username, $domain, $authhost, $form, $args) = @_;
 6340:     my $lonids=$Apache::lonnet::perlvar{'lonIDsDir'};
 6341: 
 6342:     my $public=($username eq 'public' && $domain eq 'public');
 6343: 
 6344: # See if old ID present, if so, remove
 6345: 
 6346:     my ($filename,$cookie,$userroles);
 6347:     my $now=time;
 6348: 
 6349:     if ($public) {
 6350: 	my $max_public=100;
 6351: 	my $oldest;
 6352: 	my $oldest_time=0;
 6353: 	for(my $next=1;$next<=$max_public;$next++) {
 6354: 	    if (-e $lonids."/publicuser_$next.id") {
 6355: 		my $mtime=(stat($lonids."/publicuser_$next.id"))[9];
 6356: 		if ($mtime<$oldest_time || !$oldest_time) {
 6357: 		    $oldest_time=$mtime;
 6358: 		    $oldest=$next;
 6359: 		}
 6360: 	    } else {
 6361: 		$cookie="publicuser_$next";
 6362: 		last;
 6363: 	    }
 6364: 	}
 6365: 	if (!$cookie) { $cookie="publicuser_$oldest"; }
 6366:     } else {
 6367: 	# if this isn't a robot, kill any existing non-robot sessions
 6368: 	if (!$args->{'robot'}) {
 6369: 	    opendir(DIR,$lonids);
 6370: 	    while ($filename=readdir(DIR)) {
 6371: 		if ($filename=~/^$username\_\d+\_$domain\_$authhost\.id$/) {
 6372: 		    unlink($lonids.'/'.$filename);
 6373: 		}
 6374: 	    }
 6375: 	    closedir(DIR);
 6376: 	}
 6377: # Give them a new cookie
 6378: 	my $id = ($args->{'robot'} ? 'robot'.$args->{'robot'}
 6379: 		                   : $now);
 6380: 	$cookie="$username\_$id\_$domain\_$authhost";
 6381:     
 6382: # Initialize roles
 6383: 
 6384: 	$userroles=&Apache::lonnet::rolesinit($domain,$username,$authhost);
 6385:     }
 6386: # ------------------------------------ Check browser type and MathML capability
 6387: 
 6388:     my ($httpbrowser,$clientbrowser,$clientversion,$clientmathml,
 6389:         $clientunicode,$clientos) = &decode_user_agent($r);
 6390: 
 6391: # -------------------------------------- Any accessibility options to remember?
 6392:     if (($form->{'interface'}) && ($form->{'remember'} eq 'true')) {
 6393: 	foreach my $option ('imagesuppress','appletsuppress',
 6394: 			    'embedsuppress','fontenhance','blackwhite') {
 6395: 	    if ($form->{$option} eq 'true') {
 6396: 		&Apache::lonnet::put('environment',{$option => 'on'},
 6397: 				     $domain,$username);
 6398: 	    } else {
 6399: 		&Apache::lonnet::del('environment',[$option],
 6400: 				     $domain,$username);
 6401: 	    }
 6402: 	}
 6403:     }
 6404: # ------------------------------------------------------------- Get environment
 6405: 
 6406:     my %userenv = &Apache::lonnet::dump('environment',$domain,$username);
 6407:     my ($tmp) = keys(%userenv);
 6408:     if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
 6409: 	# default remote control to off
 6410: 	if ($userenv{'remote'} ne 'on') { $userenv{'remote'} = 'off'; }
 6411:     } else {
 6412: 	undef(%userenv);
 6413:     }
 6414:     if (($userenv{'interface'}) && (!$form->{'interface'})) {
 6415: 	$form->{'interface'}=$userenv{'interface'};
 6416:     }
 6417:     $env{'environment.remote'}=$userenv{'remote'};
 6418:     if ($userenv{'texengine'} eq 'ttm') { $clientmathml=1; }
 6419: 
 6420: # --------------- Do not trust query string to be put directly into environment
 6421:     foreach my $option ('imagesuppress','appletsuppress',
 6422: 			'embedsuppress','fontenhance','blackwhite',
 6423: 			'interface','localpath','localres') {
 6424: 	$form->{$option}=~s/[\n\r\=]//gs;
 6425:     }
 6426: # --------------------------------------------------------- Write first profile
 6427: 
 6428:     {
 6429: 	my %initial_env = 
 6430: 	    ("user.name"          => $username,
 6431: 	     "user.domain"        => $domain,
 6432: 	     "user.home"          => $authhost,
 6433: 	     "browser.type"       => $clientbrowser,
 6434: 	     "browser.version"    => $clientversion,
 6435: 	     "browser.mathml"     => $clientmathml,
 6436: 	     "browser.unicode"    => $clientunicode,
 6437: 	     "browser.os"         => $clientos,
 6438: 	     "server.domain"      => $Apache::lonnet::perlvar{'lonDefDomain'},
 6439: 	     "request.course.fn"  => '',
 6440: 	     "request.course.uri" => '',
 6441: 	     "request.course.sec" => '',
 6442: 	     "request.role"       => 'cm',
 6443: 	     "request.role.adv"   => $env{'user.adv'},
 6444: 	     "request.host"       => $ENV{'REMOTE_ADDR'},);
 6445: 
 6446:         if ($form->{'localpath'}) {
 6447: 	    $initial_env{"browser.localpath"}  = $form->{'localpath'};
 6448: 	    $initial_env{"browser.localres"}   = $form->{'localres'};
 6449:         }
 6450: 	
 6451: 	if ($public) {
 6452: 	    $initial_env{"environment.remote"} = "off";
 6453: 	}
 6454: 	if ($form->{'interface'}) {
 6455: 	    $form->{'interface'}=~s/\W//gs;
 6456: 	    $initial_env{"browser.interface"} = $form->{'interface'};
 6457: 	    $env{'browser.interface'}=$form->{'interface'};
 6458: 	    foreach my $option ('imagesuppress','appletsuppress',
 6459: 				'embedsuppress','fontenhance','blackwhite') {
 6460: 		if (($form->{$option} eq 'true') ||
 6461: 		    ($userenv{$option} eq 'on')) {
 6462: 		    $initial_env{"browser.$option"} = "on";
 6463: 		}
 6464: 	    }
 6465: 	}
 6466: 
 6467: 	$env{'user.environment'} = "$lonids/$cookie.id";
 6468: 	
 6469: 	if (tie(my %disk_env,'GDBM_File',"$lonids/$cookie.id",
 6470: 		 &GDBM_WRCREAT(),0640)) {
 6471: 	    &_add_to_env(\%disk_env,\%initial_env);
 6472: 	    &_add_to_env(\%disk_env,\%userenv,'environment.');
 6473: 	    &_add_to_env(\%disk_env,$userroles);
 6474: 	    if (ref($args->{'extra_env'})) {
 6475: 		&_add_to_env(\%disk_env,$args->{'extra_env'});
 6476: 	    }
 6477: 	    untie(%disk_env);
 6478: 	} else {
 6479: 	    &Apache::lonnet::logthis("<font color=\"blue\">WARNING: ".
 6480: 			   'Could not create environment storage in lonauth: '.$!.'</font>');
 6481: 	    return 'error: '.$!;
 6482: 	}
 6483:     }
 6484:     $env{'request.role'}='cm';
 6485:     $env{'request.role.adv'}=$env{'user.adv'};
 6486:     $env{'browser.type'}=$clientbrowser;
 6487: 
 6488:     return $cookie;
 6489: 
 6490: }
 6491: 
 6492: sub _add_to_env {
 6493:     my ($idf,$env_data,$prefix) = @_;
 6494:     while (my ($key,$value) = each(%$env_data)) {
 6495: 	$idf->{$prefix.$key} = $value;
 6496: 	$env{$prefix.$key}   = $value;
 6497:     }
 6498: }
 6499: 
 6500: 
 6501: =pod
 6502: 
 6503: =back
 6504: 
 6505: =cut
 6506: 
 6507: 1;
 6508: __END__;
 6509: 

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